直接上代码:
qt的ui操作必须在主线程做的,分支线程只能发送消息给主线程进行引导操作。
所以平常我们的代码都是直接使用一个线程来调动UI,但是不同的线程同时需要使用UI来显示结果之类的就需要相互协调;
如果没有invoke之类的方法,可以考虑直接使用qt 的Qthread;直接使用thread会冲突;
1 需要使用UI的线程所在的类必须是继承自Qthread; 头文件#include<qthread.h>
定义 信号函数
#include <QObject>
#include<qthread.h>
#include<thread>
using namespace std;
class QTgui :public QThread
{
Q_OBJECT
signals :
void sigCurrentImage2(int img);
2 链接类线程函数(信号)和主界面显示UI的函数(槽)
g1 = new QTgui(this);
connect(g1, SIGNAL(sigCurrentImage2(int)), this, SLOT(slot3(int)));
3 在类中重写run函数
void QTgui::run()
{
while (add == 0)
{
k += 3;
this_thread::sleep_for(std::chrono::milliseconds(timee));
emit sigCurrentImage2(k);
}
}
4 启动run线程
void QTgui::addd()
{
add = 0;
start();
//std::thread thread1(std::bind(&QTgui::porcess, this));
//tthread = &thread1;
//tthread->detach();
}
5 全部代码 在这里:
#pragma once
#include <QObject>
#include<qthread.h>
#include<thread>
using namespace std;
class QTgui :public QThread
{
Q_OBJECT
signals :
void sigCurrentImage2(int img);
public:
QTgui(QObject *parent);
~QTgui();
int k;
int add;
int timee=3;
std::thread * tthread;
void run();
void addd();
void porcess();
};
#include "QTgui.h"
QTgui::QTgui(QObject *parent)
: QThread(parent)
{
k = 0;
add = 0;
}
QTgui::~QTgui()
{
}
void QTgui::run()
{
while (add == 0)
{
k += 2;
this_thread::sleep_for(std::chrono::milliseconds(timee));
emit sigCurrentImage2(k);
}
}
void QTgui::addd()
{
start();
//std::thread thread1(std::bind(&QTgui::porcess, this));
//tthread = &thread1;
//tthread->detach();
}
void QTgui::porcess()
{
while (add == 0)
{
k += 2;
this_thread::sleep_for(std::chrono::milliseconds(timee));
emit sigCurrentImage2(k);
}
}
#pragma once
#include <QtWidgets/QMainWindow>
#include "ui_threadGui.h"
#include"QTgui.h"
class threadGui : public QMainWindow
{
Q_OBJECT
public:
threadGui(QWidget *parent = Q_NULLPTR);
QTgui* g1;
QTgui* g2;
private:
Ui::threadGuiClass ui;
private slots:
void slot2();
void slot1();
void slot3(int k);
};
#include "threadGui.h"
threadGui::threadGui(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
g1 = new QTgui(this);
/*connect(g1, &QTgui::sigCurrentImage2, [=](int img) {
slot3(img);
});*/
g2 = new QTgui(this);
g2->k = 1;
g2->timee = 50;
//connect(g2, &QTgui::sigCurrentImage2, [=](int img) {
// slot3(img);
//});
connect(g1, SIGNAL(sigCurrentImage2(int)), this, SLOT(slot3(int)));
connect(g2, SIGNAL(sigCurrentImage2(int)), this, SLOT(slot3(int)));
}
void threadGui::slot3(int k)
{
if (k %2 ==0 ||true)
{
ui.label->setText(QString::number(k));
}
else {
ui.label_2->setText(QString::number(k));
}
}
void threadGui::slot1()
{
g1->addd();
g2->addd();
}
void threadGui::slot2()
{
g1->add = 1;
g2->add = 1;
ui.label_3->setText(QString::number(g1->k) + QString::number(g2->k));
}