大家都知道Qt中信号槽的连接方式有五种:其中Qt::QueuedConnection就是其中之一,他主要就使用在不同线程中,当两个线程中处理数据的速度不一致的时候,使用这种连接方式,可以提供用户的使用体验。
Qt::QueuedConnection:使用队列的连接方式,在不同的线程中,信号的发出对象和槽函数的接收对象分别在不同的线程中,数据处理过程在工作线程中,数据展示在主线程中。这时需要把处理完成的数据在界面上显示出来,就需要通过信号槽的方式把处理完成的数据展示出来。
#pragma once
#include <QtWidgets/QMainWindow>
#include "ui_QtGuiQueueConnect.h"
class UpdateThread;
class QtGuiQueueConnect : public QMainWindow {
Q_OBJECT
public:
QtGuiQueueConnect(QWidget *parent = Q_NULLPTR);
private:
void init();
private slots:
void slotBtnTime();
void slotThreadUpdate();
private:
Ui::QtGuiQueueConnectClass ui;
UpdateThread* _updateThread = nullptr;
int _time = 0;
};
#include "QtGuiQueueConnect.h"
#include "UpdateThread.h"
QtGuiQueueConnect::QtGuiQueueConnect(QWidget *parent)
: QMainWindow(parent) {
ui.setupUi(this);
init();
}
void QtGuiQueueConnect::init() {
connect(ui.pushButtonTime, SIGNAL(clicked()), this, SLOT(slotBtnTime()));
if (_updateThread == nullptr){
_updateThread = new UpdateThread;
}
connect(_updateThread, SIGNAL(sigUpdate()), this, SLOT(slotThreadUpdate()), Qt::QueuedConnection);
}
void QtGuiQueueConnect::slotBtnTime() {
_updateThread->start();
}
void QtGuiQueueConnect::slotThreadUpdate() {
int a = 0;
for (int i = 0; i < 50; i++){
for (int j = 0; j < 100;j++){
a++;
QString aStr = QString("%1").arg(a);
ui.label_2->setText(aStr);
}
}
_time++;
QString timeStr = QString("%1").arg(_time);
ui.lineEdit->setText(timeStr);
}
处理数据的工作线程:
#pragma once
#include <QThread>
class UpdateThread : public QThread {
Q_OBJECT
public:
UpdateThread(QObject *parent = Q_NULLPTR);
~UpdateThread();
virtual void run()override;
signals:
void sigUpdate();
private:
int _times = 0;
};
#include <QDebug>
#include "UpdateThread.h"
UpdateThread::UpdateThread(QObject *parent)
: QThread(parent) {
}
UpdateThread::~UpdateThread() {
}
void UpdateThread::run() {
while (true) {
QThread::msleep(10);
_times++;
qDebug() << "_times" << _times;
emit sigUpdate();
if (_times > 10000) {
break;
}
}
}
当线程退出以后,界面刷新还没有完成,所有工作线程虽然完成了但是主线程还在继续运行!
aaa