转至: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);
}
}