该按钮btn
是唯一的窗口小部件。它绑定到new_thread
创建新线程的方法。
线程内部有一个方法func_1
。它必须创建一个计时器 3 次,其操作应导致调用func_2
. 由于某种原因,方法代码func_2
没有被执行。请告诉我我做错了什么?
from PyQt5 import QtCore, QtWidgets
class MyThread(QtCore.QThread):
def __init__(self, parent=None):
QtCore.QThread.__init__(self, parent)
def run(self):
print('THREAD: run')
self.func_1()
def func_1(self):
for i in range(0, 3):
print('a')
QtCore.QTimer.singleShot(150, self.func_2)
def func_2(self):
print('This doesn`t work :(')
class MyWindow(QtWidgets.QWidget):
def __init__(self, parent = None):
super().__init__(parent)
box = QtWidgets.QHBoxLayout(self)
btn = QtWidgets.QPushButton('Button', clicked = self.new_thread)
box.addWidget(btn)
def new_thread(self):
self.mythread = MyThread()
self.mythread.started.connect(self.on_started)
self.mythread.finished.connect(self.on_finished)
self.mythread.start()
def on_started(self):
print('THREAD: start')
def on_finished(self):
print('THREAD: finish')
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
window = MyWindow()
window.setWindowTitle(' ')
window.show()
sys.exit(app.exec_())
UPD
from PyQt5 import QtCore, QtWidgets
class MyThread(QtCore.QThread):
singlTimer = QtCore.pyqtSignal()
def __init__(self, parent=None):
QtCore.QThread.__init__(self, parent)
def run(self):
print('THREAD: run')
self.func_1()
def func_1(self):
for i in range(0, 3):
print('a')
self.singlTimer.emit()
def on_singlTimer(self):
QtCore.QTimer.singleShot(150, self.func_2)
def func_2(self):
print('This doesn`t work :)')
class MyWindow(QtWidgets.QWidget):
def __init__(self, parent = None):
super().__init__(parent)
box = QtWidgets.QHBoxLayout(self)
btn = QtWidgets.QPushButton('Button', clicked = self.new_thread)
box.addWidget(btn)
def new_thread(self):
self.mythread = MyThread()
self.mythread.started.connect(self.on_started)
self.mythread.finished.connect(self.on_finished)
self.mythread.singlTimer.connect(self.mythread.on_singlTimer)
self.mythread.start()
def on_started(self):
print('THREAD: start')
def on_finished(self):
print('THREAD: finish')
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
window = MyWindow()
window.setWindowTitle(' ')
window.show()
sys.exit(app.exec_())
我认为正确的做法是: