Qt信号和槽连接方式测试

Qt信号和槽的连接方式

1. 常用的连接方式

Qt::ConnectionType代表信号和槽的连接方式,在connect时指定。

  • Qt::AutoConnection :缺省的默认方式,如果接收者位于发出信号的线程中,则使用Qt::DirectConnection。否则,将使用Qt::QueuedConnection。连接类型在发出信号时确定。
  • Qt::DirectConnection:当发出信号时,将立即调用槽函数。槽函数在发送信号的线程中执行。
  • Qt::QueuedConnection:当控制权返回到接收者线程的事件循环时,将调用槽函数。槽函数在接收者的线程中执行。
  • Qt::UniqueConnection:防止重复连接。

2. 代码测试

首先在头文件中声明信号和槽:

signals:
    void connSig();
public slots:
    void connSlot();

在源文件中实现槽函数,并连接信号和槽,发射信号。

槽函数:

void MainWindow::connSlot()
{
    qDebug()<<"slot thread: "<<QThread::currentThread();
}

1. 默认连接方式

// 1. 连接信号槽
connect(this, SIGNAL(connSig()), this, SLOT(connSlot()));

qDebug()<<"signal1 thread: "<<QThread::currentThread();
// 2. 发送信号,发送信号线程和信号接收者在同一线程
emit connSig();

// 3. 发送信号,发送信号线程和信号接收者在不同线程
QtConcurrent::run([=](){
    qDebug()<<"signal2 thread: "<<QThread::currentThread();
    emit connSig();
});

输出结果:

// 信号和信号接收者在同一线程时,槽函数在发送信号的线程中执行
signal1 thread:  QThread(0x837ec8)
slot thread:  	 QThread(0x837ec8)

// 信号和信号接收者在不同线程时,槽函数在信号接收者的线程中执行,和发送信号的线程相比是不同的线程
signal2 thread:  QThread(0x191aa568, name = "Thread (pooled)")
slot thread:  	 QThread(0x837ec8)

2. Qt::QueuedConnection

connect(this, SIGNAL(connSig()), this, SLOT(connSlot()), Qt::QueuedConnection)

这种连接方式的输出结果和默认方式输出结果相同。

3. Qt::DirectConnection

connect(this, SIGNAL(connSig()), this, SLOT(connSlot()), Qt::DirectConnection);

输出结果:

// 信号和信号接收者在同一线程时,槽函数在发送信号的线程中执行
signal1 thread:  QThread(0x957ec8)
slot thread:     QThread(0x957ec8)

// 信号和信号接收者在不同线程时,槽函数在发送信号的线程中执行,和发送信号的线程相比是相同的线程
signal2 thread:  QThread(0xad1a828, name = "Thread (pooled)")
slot thread:     QThread(0xad1a828, name = "Thread (pooled)")
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

VectorAL

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值