Qt程序中调用pthread_create创建线程改变UI

转至:http://t.zoukankan.com/duxie-p-15085468.html
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

加入从当前一个普通线程发送信号到 ui,更新 Ui 只能使用 Qt::BlockingQueuedConnection,用 Qt::QueuedConnection 会一会有用一会没用,并且会导致崩溃。
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)),Qt::BlockingQueuedConnection);
    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);
    }
}
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值