Multithreading with pyqt - Can't start individual threads at the same time?

I am trying to run the PyQT GUI on my python application and I tried to split it into 2 threads so that the GUI was responsive while my main loop was running, but I couldn’t get it going. Perhaps I do not understand. Here is what I tried:

My Window and Worker thread is defined as follows:

 class Window(QWidget): def __init__(self, parent = None): QWidget.__init__(self, parent) self.thread = Worker() start = QPushButton("Start", self) QObject.connect(start, SIGNAL("clicked()"), MAIN_WORLD.begin) hbox = QVBoxLayout(self) hbox.addStretch(4) class Worker(QThread): def __init__(self, parent = None): QThread.__init__(self, parent) if __name__ == '__main__': MAIN_WORLD = World() app = QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec_()) 

which seems to be very close to online examples. My World class starts a loop that is endless as soon as the user clicks the Start button until he clicks again. Here is part of his definition.

 class World(QThread): def __init__(self, parent = None): QThread.__init__(self, parent) self.currentlyRunning = False //snip def begin(self): if self.currentlyRunning: self.currentlyRunning = False else: self.currentlyRunning = True self.MethodThatDoesUsefulStuff() 

edit: I noticed that I am not using my workflow. How to create my thread as a workflow?

+4
source share
2 answers

After taking a closer look at your code, you have MAIN_WORLD, which was launched before QApplication, but this is not what you want.

You want to do something like this:

 if __name__ == '__main__': app = QApplication(sys.argv) sys.exit(app.exec_()) 

And in your Window class:

 class Window(QWidget): def __init__(self, *args): self.world_thread = World(); # ... 

The above will allow the main thread to control gui and allow worker threads to run in the background.

+1
source

This is supposed to be PyQt, not PySide, but:

  • Not subclasses of QThread, subclass of QObject (see http://blog.qt.io/blog/2010/06/17/youre-doing-it-wrong/ ).
  • Then the main workflow is to create a new thread, move your worker to the thread, start the thread of your worker too. Your problem may be that you never start your new thread, initialization will not do it - while both your GUI and your worker work with the same thread as others commented on. GIL really is not included in the picture. Check out the QThread docs: http://doc.qt.io/qt-4.8/qthread.html .
0
source

Source: https://habr.com/ru/post/1300086/


All Articles