connectionType
conenctionType 是Qt在连接信号和槽时使用的第五个参数。
它是个枚举值,详细描述了信号到槽之间可以使用的连接类型。
描述
枚举 | 值 | 描述 |
---|---|---|
Qt::AutoConnection | 0 | (默认)如果接收器位于发出信号的线程中,则使用Qt::DirectConnection。否则,使用Qt::QueuedConnection。连接类型在信号发出时确定。 |
Qt::DirectConnection | 1 | 在信号发出时,立即调用该槽。槽在发出信号所在的线程中执行。 |
Qt::QueuedConnection | 2 | 当控制返回到接收方线程的事件循环时,调用插槽。插槽在接收者的线程中执行。 |
Qt::BlockingQueuedConnection | 3 | 与Qt::QueuedConnection相同,不同的是信号发出的线程会阻塞,直到槽返回。如果信号和槽在同一线程中,则不能使用此连接,否则应用程序将死锁。 |
Qt::UniqueConnection | 0x80 | 这是一个标志,可以使用OR与上述任何一种连接类型结合使用。当Qt::UniqueConnection被设置时,如果连接已经存在(即,如果相同的信号已经连接到同一对对象的同一插槽)时,QObject::connect()将失败。这个标志是在Qt 4.6中引入的。 |
使用Qt::QueuedConnection时,参数必须是Qt元对象系统已知的类型,因为Qt需要复制参数以将它们存储在后台的事件中。如果你尝试使用排队连接并得到错误消息:
QObject::connect: Cannot queue arguments of type 'MyType'
此时你可以通过qRegisterMetaType()
/Q_DECLARE_METATYPE()
注册你需要的数据类型。
Tips:必须在connection之前注册
注意事项
在使用Qt::UniqueConnection
时要注意,此参数当槽函数为成员函数时才可以起作用。在槽函数为lambdas,非成员函数或者functors时,该参数不起作用。
使用方法
class Sender : public QObject
{
Q_OBJECT
public:
signals:
void signal_send();
};
class Receiver : public QObject
{
Q_OBJECT
public slots:
void slot_rcv(){
qDebug()<<"slot";
}
};
int main()
{
Sender *sender = new Sender();
Receiver *receiver = new Receiver();
// 未指定,默认为Qt::AutoConnection
connect(sender, &Sender::signal_send, receiver, &Receiver::slot_rcv);
// 指定为Qt::DirectConnection
connect(sender, &Sender::signal_send, receiver, &Receiver::slot_rcv, Qt::DirectConnection);
// 指定为Qt::QueuedConnection
connect(sender, &Sender::signal_send, receiver, &Receiver::slot_rcv, Qt::QueuedConnection);
// 指定为Qt::BlockingQueuedConnection
connect(sender, &Sender::signal_send, receiver, &Receiver::slot_rcv, Qt::BlockingQueuedConnection);
// 只允许连接一次,且为Qt::QueuedConnection
connect(sender, &Sender::signal_send, receiver, &Receiver::slot_rcv, Qt::connectionType(Qt::QueuedConnection || Qt::UniqueConnection));
// Qt::UniqueConnection不起作用的例子1
connect(sender, &Sender::signal_send, receiver, &std::bind(&Receiver::slot_rcv, receiver), Qt::connectionType(Qt::QueuedConnection || Qt::UniqueConnection));
// Qt::UniqueConnection不起作用的例子2
connect(sender, &Sender::signal_send, receiver, []{qDebug()<<"in lambdas";}), Qt::connectionType(Qt::QueuedConnection || Qt::UniqueConnection));
return 0;
}