Reputation: 197
This is my first attempt at trying to subclass QThreads and use it in a program but I'm getting something kind of weird. I'm not sure if my constructor is wrong or something like that, but basically when I run my QThread the entire program sleeps (not just the thread) when the QThread is sleeping
For example, the provided code will print "Hello there" after 3 seconds which is how long the QThread is supposed to sleep for
How do I fix my code so that I can have my thread running in the background while the program is running
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QThread, pyqtSignal
import time
class MyThread(QThread):
def __init__(self):
QThread.__init__(self)
def __del__(self):
self.wait()
def run(self):
self.sleep(3)
print("Slept for 3 seconds")
def main():
qThread = MyThread()
qThread.run()
print("Hello there")
main()
Upvotes: 0
Views: 407
Reputation: 572
To complete ptolemy0's answer, i can share you the code i'm using to practice on Qt:
from PyQt5.QtCore import QThread
from PyQt5.QtWidgets import QWidget, QApplication
import sys, time
class MyThread(QThread):
def __init__(self, parent=None):
super(MyThread, self).__init__(parent)
def __del__(self):
self.wait()
def run(self):
while True:
self.sleep(3)
print("Slept for 3 seconds")
class Main(QWidget):
def __init__(self, parent=None):
super(Main,self).__init__(parent)
qThread = MyThread()
qThread.start()
i=0
while True:
print(i)
i+=1
time.sleep(1)
def main():
app = QApplication(sys.argv)
example = Main()
print("Hello there")
sys.exit(app.exec())
main()
Hope it can help you!
Upvotes: -1
Reputation: 809
Use start
not run
:
def main():
qThread = MyThread()
qThread.start()
print("Hello there")
Since run
is the starting point for the thread (which exists in case you wanted to reuse the code not in a thread),
whilst start
is the method to start the thread itself, so it will in turn call run
Upvotes: 2