簡體   English   中英

如何制作我的QThread塊並等待從主線程調用的函數返回值?

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

簡單的答案-使用條件。

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

如果仍然使用信號和插槽,則也可以使用Qt :: BlockingQueuedConnection連接類型。 該連接將等待直到插槽(在另一個線程中)執行完畢。 注意不要死鎖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM