QT子线程操作UI

在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);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章