connectionType

connectionType

conenctionType 是Qt在连接信号和槽时使用的第五个参数。
它是个枚举值,详细描述了信号到槽之间可以使用的连接类型。

描述

枚举描述
Qt::AutoConnection0(默认)如果接收器位于发出信号的线程中,则使用Qt::DirectConnection。否则,使用Qt::QueuedConnection。连接类型在信号发出时确定。
Qt::DirectConnection1在信号发出时,立即调用该槽。槽在发出信号所在的线程中执行。
Qt::QueuedConnection2当控制返回到接收方线程的事件循环时,调用插槽。插槽在接收者的线程中执行。
Qt::BlockingQueuedConnection3与Qt::QueuedConnection相同,不同的是信号发出的线程会阻塞,直到槽返回。如果信号和槽在同一线程中,则不能使用此连接,否则应用程序将死锁。
Qt::UniqueConnection0x80这是一个标志,可以使用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;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值