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