移动到QThread后,单击按钮时不会发出pyqt信号



本质上我有一个过程,它将在单击按钮时开始。一旦我开始这个过程,一切都很好,直到需要用户输入。但是,当用户点击按钮时,不会发出"点击"信号。信号适当地连接到插槽。在我将代码移动到QThread后,单击按钮停止工作。

class Procedure(QObject):

def __init__(self, parent):
super().__init__()
self.parent = parent
self.parent.button_a.clicked.connect(self.on_button_a_clicked)
self.event = threading.Event()
def run(self):
# started running, doing some stuff here
# waits for button click, i.e. when button is clicked, the event is set and then you may proceed
self.event.wait()
# NEVER REACHES HERE
def on_button_a_clicked(self):
self.event.set()
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.setupUi(self)
self.setFixedSize(self.size())
self.start_button.clicked.connect(self.on_start_clicked)
def on_start_clicked(self):
self.thread = QThread()
self.worker = Procedure(self)
self.worker.moveToThread(self.thread)
self.thread.started.connect(self.worker.run)
self.thread.start()
def main():
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()

if __name__ == '__main__':
main()

然而,我确实有一个指示,即信号已正确连接到插槽,因为当在函数run((中手动发出信号时,按钮点击被成功模拟。因此,我认为问题在于按钮点击没有正确注册。

def run(self):
# started running, doing some stuff here
# following line successfully emulates the button click
self.parent.button_a.clicked.emit()
self.event.wait()
# reaches here successfully

我还认为这与QThread有关,因为这个问题是在我开始在QThread中运行过程后出现的,但我有点迷失在这里,我不知道如何调试这个问题。提前谢谢。

您可以在Procedure中创建插槽并将其直接连接到button_a.clicked,而不需要threading.Event,而且您根本不需要run

最新更新