In have the modified the code from This Answer
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import time
class MyWorker(QObject):
@pyqtSlot()
def firstWork(self):
print ('doing first work')
time.sleep(2)
print ('first work done')
@pyqtSlot()
def secondWork(self):
print ('doing second work')
time.sleep(2)
print ('second work done')
class Window(QWidget):
def __init__(self, parent = None):
super(Window, self).__init__()
self.initUi()
self.setupThread()
def initUi(self):
layout = QVBoxLayout()
self.button1 = QPushButton('1')
self.button2 = QPushButton('2')
layout.addWidget(self.button1)
layout.addWidget(self.button2)
self.setLayout(layout)
self.show()
def setupThread(self):
self.thread = QThread()
self.worker = MyWorker()
self.worker.moveToThread(self.thread)
self.button2.clicked.connect(self.worker.secondWork)
self.button1.clicked.connect(self.worker.firstWork)
# Start thread
self.thread.start()
if __name__ == "__main__":
app = QApplication([])
w = Window()
app.exec_()
Everything works perfectly but i want to start methods in separate threads by simple line of code and not by event signals.
Is there was how to perform this?
Something like self.worker.secondWork()
instead of event from button self.button2.clicked.connect(self.worker.secondWork)
(This of course does not works)
The only way i have found with my skill is create invisible button and simulate his click event for this but it is not good solution of course!