[英]Qt thread waiting input from the GUI
I have a QThread which does a lot of calculations (it can run for minutes), and at one (and only one) point it requires user input, for example in the form of a yes/no dialog. 我有一个QThread,可以进行大量的计算(它可以运行几分钟),并且在一个(且只有一个)点需要用户输入,例如以是/否对话的形式。 Of course, no GUI elements can be accessed and no dialogs opened from the thread (a Qt design choice), as it is not the main thread.
当然,没有GUI元素可以访问,并且没有从线程打开对话框(Qt设计选择),因为它不是主线程。
Well there are many obvious solutions, but I'm interested in a "recommended" solution, or a "best practice". 那么有很多明显的解决方案,但我对“推荐”解决方案或“最佳实践”感兴趣。
My ideas: 我的想法:
run()
method where the calculations are being done? run()
方法? If the run()
exits, the thread dies. run()
退出,则线程死亡。 So I have something like this in my run()
function: while (!can_continue) { sleep(); }
run()
函数中有这样的东西: while (!can_continue) { sleep(); }
while (!can_continue) { sleep(); }
and I set can_continue
in the slot where I caught the signal sent form the main. while (!can_continue) { sleep(); }
和予设定can_continue
在我赶上了信号发送的形式的主要的插槽。 However, I have some doubts about this being the most simple / most elegant solution. Your problems with second version arises because you are working with Qt thread wrong . 你的第二个版本的问题出现是因为你正在使用Qt线程错误 。
You should create new object class Worker: public QObject
that has signals: 您应该创建具有信号的新对象
class Worker: public QObject
:
void stage1Finished();
void stage2Fibished();
and slots: 和插槽:
void startStage1();
void startStage2();
then create Qthread
thread object, push Worker
to the thread, connect startStage1()
with started()
signal of thread, show dialog on signal stage1Finished()
and connect dialog-accepted-signal with startStage2()
. 然后创建
Qthread
线程对象,将Worker
推送到线程,将startStage1()
连接到线程的started()
信号,在信号stage1Finished()
上显示对话框,并使用startStage2()
连接dialog-accepted-signal 。 Connect stage2Finished
with exit()
slot of thread. 连接
stage2Finished
与线程的exit()
槽。
Then you will not have to sleep anywhere, all signals processing will go through standard mechanism in Qthread
. 然后你不必在任何地方睡觉,所有信号处理都将通过
Qthread
标准机制。 Then you just start the thread to start processing and get finished
signal on processing finished. 然后,您只需启动线程即可开始处理,并在处理完成后获得
finished
信号。
While connecting signals to slots, use Qt::QueuedConnection
. 在将信号连接到插槽时,请使用
Qt::QueuedConnection
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.