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

时间:2018-03-17 01:07:57

标签: python pyqt qthread

从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()

1 个答案:

答案 0 :(得分:1)

这正是信号和插槽的用途:对象之间的通信,尤其是不同线程的对象。

幸运的是,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)