2

我正在 QThread 重新实现中做一些工作。时不时地,我想问用户一个是/否的问题,所以我打算使用 QMessageBox::question()。问题是,我不能从线程中调用它。这不是一个大问题,我可以发出一个连接到主 GUI 线程中的插槽的信号,该插槽将显示消息框,但我还需要自定义线程阻塞并等待消息框被关闭并检索返回值(这里是 QMessageBox::StandardButton)。我该如何去做呢?

编辑: 以下(伪)代码会起作用吗?

class MyThread
{
public:
    MyThread(QObject *parent)
    {
        connect(this, SIGNAL(inputRequired()), parent, SLOT(popMsgBox()), Qt::QueuedConnection);
    }

void MyThread::run()
{
    QMutex m;
    for (...)
    {
        if (something) 
        {
            m.lock();
            emit inputRequired();
            w.wait(&m);
            m.unlock();
        }

        if (MyGui->ans_ == Yes) do_something();
    }
}

signals:
    void inputRequired();

protected:
    QWaitCondition w;

};

void MyGui::popMsgBox()
{
    ans_ = QMessageBox::question(this, "Question", "Yes or no?", Yes | No);
    MyThread->w->wakeAll();
}
4

2 回答 2

3

简单的答案 - 使用条件。

http://doc.qt.io/qt-5/qwaitcondition.html

于 2011-09-26T15:42:00.470 回答
2

如果您仍然使用信号和插槽,您还可以使用Qt::BlockingQueuedConnection连接类型。此连接将一直等到插槽(在另一个线程中)完成执行。不过要小心不要陷入僵局。

于 2011-09-26T16:26:53.253 回答