[英]Calling a method from inside a thread to another class in python pyqt
从pyqt窗口,我调用一个线程来执行,该线程将数据发送回该窗口以更新QLCDNumber,并且工作正常。 但是,当线程完成运行时,我希望它在接收窗口中调用一个方法。 或在接收到所有数据之后,接收窗口调用它自己的方法。 我不确定如何在窗口内正确使用语句以使其正常工作,也不确定如何从线程中调用方法。 我已经尝试了很多方法,但是我已经在代码中写了我要完成的工作。
class MyThread(QtCore.QThread):
countChange = QtCore.pyqtSignal(int)
countReset = QtCore.pyqtSignal(int)
def __init__(self, parent=None):
super(MyThread, self).__init__(parent)
self.stopped = QtCore.QEvent(QtCore.QEvent.User)
def start(self):
self.stopped.setAccepted(False)
super(MyThread, self).start()
def run(self):
while not self.stopped.isAccepted():
credit = 0
limit = 13
while credit <= limit:
press = int(input('add a number'))
if press == 1:
if not credit >= limit:
credit=(credit + 1)
print (credit)
self.countChange.emit(credit)
if credit >= limit:
print ('Enough Credit')
self.stop()
def stop(self):
self.stopped.setAccepted(True)
## What I want to have here is:
## send a command to class winDow.move_on() to execute
class winDow(QtGui.QMainWindow,cashwin.Ui_MainWindow):
def __init__(self, parent=None):
super(winDow, self).__init__(parent)
self.setupUi(self)
self.thread = MyThread(self)
self.thread.countChange.connect(self.lcdNumber.display)
self.pull_credit()
## or if self.thread.countChange.connect == 13:
## self.move_on()
@QtCore.pyqtSlot()
def pull_credit(self):
self.thread.start()
def move_on(self):
self.window = NextWindow()
self.window.show()
self.close()
这正是信号和插槽的用途:对象之间的通信,尤其是不同线程中的对象之间的通信。
幸运的是, QThread
对象已经有一个已定义的信号,该信号在完成时将发出并即将退出。 您可以简单地将其连接到线程完成其工作之后要执行的主窗口的插槽。
修改类的构造函数,如下所示:
class winDo(QtGui.QMainWindow, cashwin.Ui_MainWindow):
def __init__(self, parent=None):
# What you already have ...
self.thread = MyThread(self)
self.thread.countChange.connect(self.lcdNumber.display)
self.thread.finished.connect(self.move_on)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.