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

2024-04-19

这是我的代码:

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

测试类.h

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

            thread -> start();
        }

};

测试线程.h

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

};

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

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

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


你做错了什么?

您正在尝试在非 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();
    }

};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我如何在另一个线程Qt中显示MessageBox 的相关文章

随机推荐