【问题标题】:Run pyQT GUI main app in seperate Thread在单独的线程中运行 pyQT GUI 主应用程序
【发布时间】:2016-10-08 05:01:20
【问题描述】:

我正在尝试在我已经建立的应用程序中添加一个 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 应用程序之前进行线程处理。

标签: python multithreading user-interface pyqt pyqt4


【解决方案1】:

一种方法是

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 吗? .通过注释掉该行代码仍然可以顺利运行。
  • 这意味着它将是一个子进程。我不知道确切的术语,但这意味着该过程将在任务完成时结束。
  • 不支持在非主线程中使用任何 Qt GUI 代码,并可能导致各种有趣的崩溃。见the Qt docs
猜你喜欢
  • 2017-11-15
  • 2012-08-10
  • 2021-06-17
  • 2023-03-27
  • 2012-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多