在QT中,子線程是無法直接操作UI的,否則會報錯,會出現線程衝突之類的錯誤。
可以用兩種方法實現:
1)使用信號和操操作,子線程給UI所在的主線程發信號;
2)使用InvokeMethod方法。
方法樣例如下:
threadtest.h
#ifndef THREADTEST_H
#define THREADTEST_H
#include <QThread>
#include <QProgressDialog>
class MainWindow;
class QThreadTest: public QThread
{
Q_OBJECT
public:
QThreadTest(MainWindow *mainwnd);
~QThreadTest();
virtual void run();
private:
QProgressDialog* m_pQProgressDlg;
//MainWindow *m_pMainWindow;
};
#endif // THREADTEST_H
threadtest.cpp
#include "threadtest.h"
QThreadTest::QThreadTest(MainWindow *mainwnd)
{
//this->m_pMainWindow = mainwnd;
m_pQProgressDlg = new QProgressDialog();
//m_pQProgressDlg->setLabel("測試");
}
QThreadTest::~QThreadTest()
{
if(m_pQProgressDlg != NULL)
{
delete m_pQProgressDlg;
m_pQProgressDlg = NULL;
}
}
void QThreadTest::run()
{
QMetaObject::invokeMethod(m_pQProgressDlg, "show", Qt::QueuedConnection);
//m_pQProgressDlg->show();
//usleep(200000);
sleep(30);
//QMetaObject::invokeMethod(m_pQProgressDlg, "hide", Qt::QueuedConnection);
QMetaObject::invokeMethod(m_pQProgressDlg, "hide", Qt::QueuedConnection);
}