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);
        }
    }
  • 相关阅读:
    【C语言】23typedef
    C#蓝牙开发之查找设备以及配对
    GridView获取隐藏列的值
    PDA(Windows Mobile)调用远程WebService
    VS2008使用宏记录来实现自动增加注释信息
    CS 系统框架二[部分内容更新]
    GridView里面嵌套RadioButton
    .Net 以报表的形式加载SAP里面的数据
    取GridView的PagerTemplate里面的控件ID
    《深入Ajax架构和最佳实践》读书笔记
  • 原文地址:https://www.cnblogs.com/duxie/p/15085468.html
Copyright © 2011-2022 走看看