Qt程序中調用pthread_create創建線程改變UI


剛開始寫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);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM