Unsolved QThread create in PyQt5
-
AttributeError: type object 'QThread' has no attribute 'create'
Here is my code.
from PyQt5.QtCore import QThread
def fun(num):
print(num)thread1 = QThread.create(fun)
thread1.start()But Qt documentation says there is a function called create since Qt 5.10. I am using PyQt5 5.11.3. Someone please help me with this.
-
@VijayalakshmiSundaravaradhan Better construct and use threads as in this article described https://medium.com/@webmamoffice/getting-started-gui-s-with-python-pyqt-qthread-class-1b796203c18c
-
@Volodymyr14 You can try something like this:
from PyQt5 import QtCore class YouThread(QtCore.QThread): def __init__(self, parent=None, num=None): QtCore.QThread.__init__(self, parent) self.num = num def run(self): print(self.num) thread = YouThread(num=14) thread.start()
-
But why is the create function not available?
-
-
@VijayalakshmiSundaravaradhan If You want to use threads in the manner You try, You can use the Python stdlib threading module.
-
Thank You @Volodymyr14
-
@VijayalakshmiSundaravaradhan Your problem is solved? The error that You provides in Your code completely describing why. This related to both PyQt5 and PySide2
-
@Volodymyr14 I decided to use threading module whenever I need to run a function in a separate thread. Do you say that Qthread.Create cannot be used in both PyQt5 and PySide2?
-
@VijayalakshmiSundaravaradhan Very well. You can use the threading module like this:
import threading def fun(num): for i in range(num): print(i) thread1 = threading.Thread(target=fun, args=(100,)) thread1.start()
-
#!/usr/bin/python3 # Threading example with QThread and moveToThread (PyQt5) import sys import time from PyQt5 import QtWidgets, QtCore class WorkerThread(QtCore.QObject): signalExample = QtCore.pyqtSignal(str, int) def __init__(self): super().__init__() @QtCore.pyqtSlot() def run(self): while True: # Long running task ... self.signalExample.emit("leet", 1337) time.sleep(5) class Main(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.worker = WorkerThread() self.workerThread = QtCore.QThread() self.workerThread.started.connect(self.worker.run) # Init worker run() at startup (optional) self.worker.signalExample.connect(self.signalExample) # Connect your signals/slots self.worker.moveToThread(self.workerThread) # Move the Worker object to the Thread object self.workerThread.start() def signalExample(self, text, number): print(text) print(number) if __name__== '__main__': app = QtWidgets.QApplication([]) gui = Main() sys.exit(app.exec_())