如何创建QThread块并等待从主线程调用的函数返回值?

时间:2021-10-07 20:58:11

I am doing some work in a QThread reimplementation. Every now and then, I'd like to ask the user a Yes/No question, so I was planning on using QMessageBox::question(). Problem is, I can't call it from the thread. That's not a big one, I can emit a signal that connects to a slot in the main GUI thread which will display the message box, but I also need the custom thread to block and wait for the message box to be dismissed and retrieve the return value as well (here, a QMessageBox::StandardButton). How do I get around to doing that?

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

EDIT: Will the following (pseudo-)code do the trick?

编辑:以下(伪)代码会这样做吗?

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

2 个解决方案

#1


2  

If you are working with signals and slots anyway, you can also use the Qt::BlockingQueuedConnection connection type. This connection will wait until the slot (in another thread) is finished executing. Be careful not to deadlock though.

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

#2


2  

Simple answer - use a condition.

简单的答案 - 使用条件。

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

#1


2  

If you are working with signals and slots anyway, you can also use the Qt::BlockingQueuedConnection connection type. This connection will wait until the slot (in another thread) is finished executing. Be careful not to deadlock though.

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

#2


2  

Simple answer - use a condition.

简单的答案 - 使用条件。

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