代码之家  ›  专栏  ›  技术社区  ›  Jason

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

  •  0
  • Jason  · 技术社区  · 7 年前

    在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 回复  |  直到 7 年前
        1
  •  1
  •   bnaecker    7 年前

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

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