![](/img/trans.png)
[英]Qt 5 - How to make QThread exit from its `wait` function where it got stuck after executing a QProcess on Windows?
[英]How can I make my QThread block and wait for a function called from the main thread to return a value?
我正在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();
}
簡單的答案-使用條件。
如果仍然使用信號和插槽,則也可以使用Qt :: BlockingQueuedConnection連接類型。 該連接將等待直到插槽(在另一個線程中)執行完畢。 注意不要死鎖。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.