Qthread locking up Gui PySide

扶醉桌前 提交于 2019-12-06 08:29:21

The issue you are experiencing is that the function you are connecting to the started signal is not run in the thread, it's run in the context of where it was set, which seems to be your UI thread.

Normally you would want to create a custom class which inherits from QThread, and any code that you want to be executed would be in the run() function of that class. Like so:

class MyTask(QThread):
  def __init__ (self):
    QThread.__init__(self)

  def run(self):
    print("Code to run in the thread goes here.")

If that seems like overkill you could just set the value of self.cipher_thread.run to your own function. Here's an example:

import time
from PySide.QtCore import QThread
from PySide import QtGui

app = QtGui.QApplication("")

def main():
  task = SomeTask()
  thread = QThread()

  # Just some variables to pass into the task
  a, b, c = (1, 2, 3)
  thread.run = lambda: task.runTask(a, b, c)


  print("Starting thread")
  thread.start()

  # Doing this so the application does not exit while we wait for the thread to complete.
  while not thread.isFinished():
    time.sleep(1)

  print("Thread complete")

class SomeTask():
  def runTask(self, a, b, c):
    print a, b, c
    print("runTask Started")
    time.sleep(5)
    print("runTask Complete")


if __name__ == "__main__":
  main()

As Ekhumoro suggested, I was running into issues with the GIL. using the Multiprocessing module has worked for me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!