线程.Qt更新界面
1、信号&槽 机制 即可
ZC:个人暂时 测试下来,类似是 PostMessage(...)的方式:
a、是在各自的线程中执行代码,
b、调用 emit不耗时(指的意思是 像调用PostMessage(...)一样 扔完就算,具体 slot中需要执行多久 不关“emit ???()”的事)
2、测试代码:
2.1、h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QThread> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: void slot01(); void on_pushButton_3_clicked(); private: Ui::MainWindow *ui; int FiCnt; public: void UpdateCnt(); }; class TthreadZ :public QThread { Q_OBJECT public: explicit TthreadZ(QObject *parent = 0){} ~TthreadZ(){} protected: void run(); signals: void signal01(); }; #endif // MAINWINDOW_H
2.2、cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include "UdpSocket_ClientZ.h" #include <QThread> #include <Windows.h> MainWindow *g_pMainWindow = nullptr; void TthreadZ::run() { while (1) { DWORD dwThreadId = ::GetCurrentThreadId(); DWORD dw1 = ::GetTickCount(); emit signal01(); DWORD dw2 = ::GetTickCount(); qDebug() << "TthreadZ.dwThreadId : " << dwThreadId << ". Take time : " << dw1 << " --> " << dw2 << " : " << (dw2-dw1)<<"ms"; // if (g_pMainWindow != nullptr) // g_pMainWindow->UpdateCnt(); Sleep(1000); qDebug() << ""; } } MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); g_pMainWindow = this; } MainWindow::~MainWindow() { delete ui; } void MainWindow::slot01() { DWORD dwThreadId = ::GetCurrentThreadId(); DWORD dw1 = ::GetTickCount(); UpdateCnt(); DWORD dw2 = ::GetTickCount(); qDebug() << "MainWindow.dwThreadId : " << dwThreadId << ". Take time : " << dw1 << " --> " << dw2 << " : " << (dw2-dw1)<<"ms"; } void MainWindow::UpdateCnt() { FiCnt ++; ui->plainTextEdit->appendPlainText(QString::number(FiCnt)); Sleep(500); } void MainWindow::on_pushButton_3_clicked() { qDebug() << "on_pushButton_3_clicked(1)"; //UpdateCnt(); TthreadZ* p = new TthreadZ(); p->start(); qDebug() << "on_pushButton_3_clicked(2)"; connect(p, &TthreadZ::signal01, this, &MainWindow::slot01);// ZC: 注意这里的参数 函数指针 }
2.3、界面
2.4、控制台输出
on_pushButton_3_clicked(1) on_pushButton_3_clicked(2) TthreadZ.dwThreadId : 5344 . Take time : 3605015 --> 3605015 : 0 ms MainWindow.dwThreadId : 4468 . Take time : 3605015 --> 3605515 : 500 ms TthreadZ.dwThreadId : 5344 . Take time : 3606015 --> 3606015 : 0 ms MainWindow.dwThreadId : 4468 . Take time : 3606015 --> 3606515 : 500 ms TthreadZ.dwThreadId : 5344 . Take time : 3607015 --> 3607015 : 0 ms MainWindow.dwThreadId : 4468 . Take time : 3607015 --> 3607515 : 500 ms TthreadZ.dwThreadId : 5344 . Take time : 3608015 --> 3608015 : 0 ms MainWindow.dwThreadId : 4468 . Take time : 3608015 --> 3608531 : 516 ms TthreadZ.dwThreadId : 5344 . Take time : 3609015 --> 3609015 : 0 ms MainWindow.dwThreadId : 4468 . Take time : 3609015 --> 3609531 : 516 ms
3、
4、
5、