【问题标题】:How can i show MessageBox in another thread Qt如何在另一个线程 Qt 中显示 MessageBox
【发布时间】:2014-07-22 10:21:56
【问题描述】:

这是我的代码:

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

TestClass.h

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

            thread -> start();
        }

};

TestThread.h

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

};

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

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

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

【问题讨论】:

  • 您可以使用signal/slot 机制。在主线程中创建消息框,当您想要显示来自线程的消息时,使用您想要显示的消息从它“发出”一个信号。看看here(虽然是4.8版本)

标签: c++ multithreading qt qmessagebox


【解决方案1】:

你做错了什么?

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

};

【讨论】:

  • 您知道为什么需要BlockingQueuedConnection 吗?我的理解是它阻塞发射器并在接收器处理其事件队列时等待。如果您想防止发射器堆栈变量在接收器处理信号时超出范围,这很有用,这与此处无关。它还可以确保发射器线程不会过早结束 - 这就是这里的动机吗?
  • @HeathRaftery BlockingQueuedConnection 是逻辑所必需的。在用户与消息框(来自 GUI 线程)进行交互之前,我们不应该更进一步。
猜你喜欢
  • 2021-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-03
相关资源
最近更新 更多