参考
QT信号槽的5种连接方式(非常溜)
Qt::QueuedConnection例子(666)
Qt信号槽的五种连接方式(简洁清晰)
Qt::UniqueConnection 防止重复连接
综合
例子
updatethread.h
#ifndef UPDATETHREAD_H
#define UPDATETHREAD_H
#include <QObject>
#include<QThread>
class UpdateThread : public QThread
{
Q_OBJECT
public:
explicit UpdateThread(QObject *parent = 0);
~UpdateThread();
virtual void run()override;// 重载线程
signals:
void signalUpdate();// 自定义信号
private:
int _times;
};
#endif // UPDATETHREAD_H
updatethread.cpp 数据处理线程1
#include "updatethread.h"
#include<QDebug>
UpdateThread::UpdateThread(QObject *parent):
QThread(parent),
_times(0)
{
}
UpdateThread::~UpdateThread()
{
}
void UpdateThread::run()
{
_times=0;
while (true) {
QThread::msleep(10);// 10ms
_times++;
qDebug()<<"_times:"<<_times<<endl;
emit signalUpdate();//发出信号
if(_times>2000)
{
qDebug()<<QString::fromUtf8("数据处理线程结束")<<endl;
break;
}
}
}
qrguiqueueconnect.h
#ifndef QTGUIQUEUECONNECT_H
#define QTGUIQUEUECONNECT_H
#include <QWidget>
#include"updatethread.h"
class UpdateThread;
namespace Ui {
class QtGuiQueueConnect;
}
class QtGuiQueueConnect : public QWidget
{
Q_OBJECT
public:
explicit QtGuiQueueConnect(QWidget *parent = 0);
~QtGuiQueueConnect();
private slots:
void on_beginBtn_clicked();// 转到槽:按键触发
void slotThreadUpdate();// 自定义槽:响应线程的信号
private:
Ui::QtGuiQueueConnect *ui;
void init();// 初始化
UpdateThread *_updateThread;
int _mytime;
};
#endif // QTGUIQUEUECONNECT_H
qrguiqueueconnect.cpp 数据展示主线程2
#include "qtguiqueueconnect.h"
#include "ui_qtguiqueueconnect.h"
QtGuiQueueConnect::QtGuiQueueConnect(QWidget *parent) :
QWidget(parent),
ui(new Ui::QtGuiQueueConnect),
_mytime(0)
{
ui->setupUi(this);
init();// 初始化
}
QtGuiQueueConnect::~QtGuiQueueConnect()
{
delete ui;
}
// 初始化
void QtGuiQueueConnect::init()
{
_updateThread=new UpdateThread;
/*1.Qt::DirectConnection当信号发出时,立即调用槽,此例子崩溃*/
//connect(_updateThread,SIGNAL(signalUpdate()),this,SLOT(slotThreadUpdate()),Qt::DirectConnection);
/*2.多线程环境一般使用Qt::QueuedConnection*/
connect(_updateThread,SIGNAL(signalUpdate()),this,SLOT(slotThreadUpdate()),Qt::QueuedConnection);
}
// 开始按键-转到槽
void QtGuiQueueConnect::on_beginBtn_clicked()
{
_mytime=0;
_updateThread->start();// 开启线程
}
void QtGuiQueueConnect::slotThreadUpdate()
{
int a=0;
// 等待,慢响应
for(int i=0;i<50;i++)
{
for(int j=0;j<180;j++)
{
a++;
ui->waitLabel->setText(QString::number(a));
}
}
_mytime++;
ui->timeLineEdit->setText(QString::number(_mytime));
}
qrguiqueueconnect.ui
执行结果
Qt::DirectConnection
当信号发出时,立即调用槽,此例子崩溃
Qt::QueuedConnection
信号的发出对象 和 槽函数的接收对象在不同的线程中,数据处理线程1,数据展示主线程2。这时需要把处理完成的数据在界面上显示出来,就需要通过信号槽的方式把处理完成的数据展示出来。
数据处理线程1退出以后,数据展示主线程2还没有完成,线程虽然ti停止发信号,但是主线程还在继续运行槽函数