从线程内部调用方法到 python pyqt 中的另一个 class

Calling a method from inside a thread to another class in python pyqt

从 pyqt window,我调用一个线程来执行,它将数据发回 window 以更新 QLCDNumber,它工作正常。但是当线程完成 运行 时,我希望它在接收 window 中调用一个方法。或者接收 window,在接收到所有数据后,调用它自己的方法。我不确定如何在 window 中正确使用语句来使其工作,也不确定如何从线程中调用该方法。我已经尝试了很多方法,但我已经在代码中写下了我想要完成的事情。有什么想法吗?

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 对象已经有一个已定义的信号,只要它们完成并即将退出,就会发出该信号。您可以简单地将其连接到线程完成其工作后要执行的主 window 插槽。

将 class 的构造函数修改为如下所示:

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)