剛開始寫Qt程序的時候,用 CreateThread 或者 pthread_create 創建線程的時候,不知道怎么跟 UI 交互,最近研究出來了,所以做個記錄。
當然用QThread也可以,但是我就是不想創建那個線程類。
UI界面只有一個 lineEdit 控件。
CMainWindow.h 頭文件代碼
#ifndef CMAINWINDOW_H #define CMAINWINDOW_H #include <QMainWindow> #include <pthread.h> #include <sys/types.h> #include <unistd.h> #include <string.h> #include <QDateTime> namespace Ui { class CMainWindow; } class CMainWindow : public QMainWindow { Q_OBJECT public: explicit CMainWindow(QWidget *parent = 0); ~CMainWindow(); signals: void sig_changeUI(QString str); private slots: void slot_changeUI(QString str); private: Ui::CMainWindow *ui; pthread_t m_tid; static void* threadFun(void* arg); }; #endif // CMAINWINDOW_H
CMainWindow.cpp 文件代碼
#include "CMainWindow.h" #include "ui_CMainWindow.h" CMainWindow::CMainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::CMainWindow) { ui->setupUi(this); connect(this, SIGNAL(sig_changeUI(QString)), this, SLOT(slot_changeUI(QString))); m_tid = 0; pthread_create(&m_tid, NULL, threadFun, (void*)this); pthread_detach(m_tid); } CMainWindow::~CMainWindow() { delete ui; } void CMainWindow::slot_changeUI(QString str) { ui->lineEdit->setText(str); } void *CMainWindow::threadFun(void *arg) { CMainWindow* mainWindow = (CMainWindow*)arg; while(true) { // 獲取當前時間 QDateTime current_date_time =QDateTime::currentDateTime(); QString current_date =current_date_time.toString("yyyy.MM.dd hh:mm:ss.zzz ddd"); // 發射信號,改變UI mainWindow->sig_changeUI(current_date); sleep(1); } }
