zoukankan      html  css  js  c++  java
  • 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);
        }
    }
  • 相关阅读:
    POJ 2723 Get Luffy Out(2-SAT)
    ZOJ 3613 Wormhole Transport
    HDU 4085 Peach Blossom Spring
    NBUT 1221 Intermediary
    NBUT 1223 Friends number
    NBUT 1220 SPY
    NBUT 1218 You are my brother
    PAT 1131. Subway Map (30)
    ZSTU OJ 4273 玩具
    ZSTU OJ 4272 最佳淘汰算法
  • 原文地址:https://www.cnblogs.com/duxie/p/15085468.html
Copyright © 2011-2022 走看看