在单独的线程中运行pyQT GUI主应用程序

4

我正在尝试在已经建立的应用程序中添加一个PyQt GUI控制台。但是PyQt GUI会阻塞整个应用程序,导致无法完成其他工作。我尝试使用QThread,但是它是从mainWindow类调用的。我想要的是在单独的线程中运行MainWindow应用程序。

def main()
      app = QtGui.QApplication(sys.argv)
      ex = Start_GUI()
      app.exec_()  #<---------- code blocks over here !

      #After running the GUI, continue the rest of the application task
      doThis = do_Thread("doThis")
      doThis.start()
      doThat = do_Thread("doThat")
      doThat.start()

我的应用程序已经使用Python线程,因此我的问题是,以线程形式实现这个过程的最佳方法是什么。


如果PyQt的工作方式类似于tkinter,那么在启动GUI应用程序之前,最好先进行线程处理。 - Pax Vobiscum
1个回答

5
这可以通过一种方法来实现:
import threading

def main()
      app = QtGui.QApplication(sys.argv)
      ex = Start_GUI()
      app.exec_()  #<---------- code blocks over here !

#After running the GUI, continue the rest of the application task

t = threading.Thread(target=main)
t.daemon = True
t.start()

doThis = do_Thread("doThis")
doThis.start()
doThat = do_Thread("doThat")
doThat.start()

以下代码将使您的主应用程序转为线程,然后让您继续进行其他想要执行的操作。


谢谢 @Uzzee,这解决了问题。你能解释一下为什么需要设置 daemon = True 吗?即使注释掉那行代码,程序仍然可以正常运行。 - Anum Sheraz
这意味着它将成为一种子进程。我不知道确切的术语,但它意味着当任务完成时,该进程将结束。 - Pax Vobiscum
14
在非主线程中使用任何Qt GUI代码都是不受支持的,可能会导致各种有趣的崩溃。请参阅Qt文档 - The Compiler

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接