如何在另一个线程Qt中显示MessageBox

EXT*_*RAM 8 c++ qt multithreading qmessagebox

这是我的代码:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    testApp w;
    w.show();
    TestClass *test = new TestClass;
    QObject::connect(w.ui.pushButton, SIGNAL(clicked()), test, SLOT(something()));
    return a.exec();
}
Run Code Online (Sandbox Code Playgroud)

TestClass.h

class TestClass: public QObject
{
    Q_OBJECT
    public slots:
        void something()
        {
            TestThread *thread = new TestThread;

            thread -> start();
        }

};
Run Code Online (Sandbox Code Playgroud)

TestThread.h

class TestThread: public QThread
{
    Q_OBJECT
protected:
    void run()
    {
        sleep(1000);
        QMessageBox Msgbox;
        Msgbox.setText("Hello!");
        Msgbox.exec();
    }

};
Run Code Online (Sandbox Code Playgroud)

如果我这样做,我会看到错误

必须在gui线程中创建小部件

我究竟做错了什么?请帮我.我知道我不能在另一个线程中改变gui,但我不知道qt中的构造.

Dmi*_*nov 7

你做错了什么?

您正试图在非gui线程中显示小部件.

怎么修?

class TestClass: public QObject
{
    Q_OBJECT
    public slots:
        void something()
        {
            TestThread *thread = new TestThread();

            // Use Qt::BlockingQueuedConnection !!!
            connect( thread, SIGNAL( showMB() ), this, SLOT( showMessageBox() ), Qt::BlockingQueuedConnection ) ;

            thread->start();
        }
        void showMessageBox()
        {
            QMessageBox Msgbox;
            Msgbox.setText("Hello!");
            Msgbox.exec();
        }
};


class TestThread: public QThread
{
    Q_OBJECT
signals:
    void showMB();
protected:
    void run()
    {
        sleep(1);
        emit showMB();
    }

};
Run Code Online (Sandbox Code Playgroud)

  • @HeathRaftery逻辑需要`BlockingQueuedConnection`.我们不应该再进一步,直到用户将与消息框(来自GUI线程)进行交互. (2认同)