1、在MainWindow的构造函数中创建了QTimer对象,QTimer运行在主线程中(本线程)
2、在新建线程MyThread中,想要更新UI,则发出信号,由主线程中连接的SLOT函数处理(跨线程)
//------------------------------------------------------------------------------线程头文件--------------------------------
#include <QThread>
class MyThread : public QThread
{
Q_OBJECT
public:
MyThread();
bool task_start();
bool end_request;
int task_cnt;
signals:
void update_ui_signal();
private:
void run()
override;
};
//------------------------------------------------------------------------------线程源文件-------------------------------
#include "mythread.h"
#
include <
QPushButton>
MyThread::
MyThread()
{
end_request =
false;
task_cnt =
0;
}
bool MyThread::
task_start()
{
start();
return isRunning();
}
void MyThread::
run()
{
while(!
end_request)
{
task_cnt++;
emit update_ui_signal();
//发出信号,通知SLOT(连接到MainWindow::update_ui_slot()) msleep(
10);
}
}
//------------------------------------------------------------------------------UI头文件----------------------------------#
include <
QMainWindow>
#
include <
QTimer>
#
include "mythread.h"namespace Ui {
class MainWindow;
}
class MainWindow :
public QMainWindow{
Q_OBJECTpublic:
explicit MainWindow(
QWidget *
parent =
nullptr);
~
MainWindow();
private slots:
void on_pushButton_clicked();
void update_ui_slot();
private:
Ui::
MainWindow *
ui;
int xCnt;
QTimer *
tmr;
MyThread *
thd;
};
//------------------------------------------------------------------------------UI源文件----------------------------------
#
include "mainwindow.h"#
include "ui_mainwindow.h"MainWindow::
MainWindow(
QWidget *
parent)
:
QMainWindow(
parent),
ui(
new Ui::
MainWindow)
{
ui->
setupUi(
this);
xCnt =
0;
//连接QTimer的timeout()信号到pushButton的click(),模拟点击事件
//点击事件通过自动连接,由on_pushButton_clicked()由处理
tmr = new QTimer(this);
connect(tmr, SIGNAL(timeout()), ui->pushButton, SLOT(click()));
tmr->
start(
10);
//连接QThread的update_ui_signal()信号到update_ui_slot()
thd = new MyThread();
thd->
task_start();
connect(
thd,
SIGNAL(
update_ui_signal()),
this,
SLOT(
update_ui_slot()));
}
MainWindow::~
MainWindow()
{
delete ui;
tmr->
stop();
delete tmr;
tmr =
nullptr;
if(
thd->
isRunning())
{
thd->
end_request =
true;
QThread::
msleep(
100);
}
delete thd;
thd =
nullptr;
}
void MainWindow::
on_pushButton_clicked()
{
xCnt++;
ui->
pushButton->
setText(
"OK ui=" + QString::
number(
xCnt)
+ ", thd=" + QString::
number(
thd->
task_cnt));
}
void MainWindow::
update_ui_slot()
{
//xCnt++; ui->
pushButton->
setText(
"OK ui=" + QString::
number(
xCnt)
+ ", thd=" + QString::
number(
thd->
task_cnt));
}