为了完整起见,这是@hank 答案的扩展。我提供了六个connect
类似的功能:
connect_from_pointer
将 QSharedPointer 作为其第一个参数,将通常QObject *
作为其第三个参数。
connect_to_pointer
将通常QObject *
作为它的第一个参数和一个 QSharedPointer 作为它的第三个参数。
connect_pointers
两个参数都采用 QSharedPointers。
每个都有两个版本:一个接受SIGNAL()
/SLOT()
语法,另一个接受(推荐的)函数指针。
这些在语法上很糟糕,但这是给你的模板。
template<class T>
QMetaObject::Connection connect_from_pointer(
const QSharedPointer<T>& sender,
const char *signal,
const QObject *receiver,
const char *method,
Qt::ConnectionType type = Qt::AutoConnection)
{
return QObject::connect(sender.data(), signal, receiver, method, type);
}
template <typename Func1, typename Func2>
QMetaObject::Connection connect_from_pointer(
const QSharedPointer<typename QtPrivate::FunctionPointer<Func1>::Object>& sender,
Func1 signal,
const typename QtPrivate::FunctionPointer<Func2>::Object *receiver,
Func2 slot,
Qt::ConnectionType type = Qt::AutoConnection)
{
return QObject::connect(sender.data(), signal, receiver, slot, type);
}
template<class T>
QMetaObject::Connection connect_to_pointer(
const QObject *sender,
const char *signal,
const QSharedPointer<T>& receiver,
const char *method,
Qt::ConnectionType type = Qt::AutoConnection)
{
return QObject::connect(sender, signal, receiver.data(), method, type);
}
template <typename Func1, typename Func2>
QMetaObject::Connection connect_to_pointer(
const typename QtPrivate::FunctionPointer<Func1>::Object *sender,
Func1 signal,
const QSharedPointer<typename QtPrivate::FunctionPointer<Func2>::Object>& receiver,
Func2 slot,
Qt::ConnectionType type = Qt::AutoConnection)
{
return QObject::connect(sender, signal, receiver.data(), slot, type);
}
template<class T, class U>
QMetaObject::Connection connect_pointers(
const QSharedPointer<T>& sender,
const char *signal,
const QSharedPointer<U>& receiver,
const char *method,
Qt::ConnectionType type = Qt::AutoConnection)
{
return QObject::connect(sender.data(), signal, receiver.data(), method, type);
}
template <typename Func1, typename Func2>
QMetaObject::Connection connect_pointers(
const QSharedPointer<typename QtPrivate::FunctionPointer<Func1>::Object>& sender,
Func1 signal,
const QSharedPointer<typename QtPrivate::FunctionPointer<Func2>::Object>& receiver,
Func2 slot,
Qt::ConnectionType type = Qt::AutoConnection)
{
return QObject::connect(sender.data(), signal, receiver.data(), slot, type);
}