PyQt5:如何连接()和发射()

问题描述 投票:0回答:2

我正在尝试将代码从 PyQt4 移植到 PyQt5,但不明白为什么以下内容不起作用。该插槽未被调用。我看到一堆蜱虫,但没有看到蜱虫。我错过了什么?

from PyQt5 import QtCore
import time

# expect to see ticks & tocks
class Alarm(QtCore.QThread, QtCore.QObject):
    signal = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super(Alarm, self).__init__(parent)
        self.signal.connect(self.eventp)
        self.start()

    def run(self):
        while True:
            print('tick')
            self.signal.emit()
            time.sleep(1)

    @QtCore.pyqtSlot()
    def eventp(self):
        print('Tock')

# main
alarm = Alarm()
time.sleep(6)  # wait for countdown, then terminate
python pyqt pyqt5 qthread
2个回答
4
投票

首先QThread已经继承自QObject,因此没有必要将其用作接口。另一方面,QThread 必须存在于事件循环中,因为这就是允许传输信号的原因,例如,在您的情况下,您使用 time.sleep(6) 阻止事件循环,而不是如果您想在之后完成循环使用 QTimer 6 秒:

import time
from PyQt5 import QtCore
# expect to see ticks & tocks
class Alarm(QtCore.QThread):
    signal = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super(Alarm, self).__init__(parent)
        self.signal.connect(self.eventp)
        self.start()

    def run(self):
        while True:
            print('tick')
            self.signal.emit()
            time.sleep(1)

    @QtCore.pyqtSlot()
    def eventp(self):
        print('Tock')

if __name__ == '__main__':
    import sys
    app = QtCore.QCoreApplication(sys.argv)
    alarm = Alarm()
    QtCore.QTimer.singleShot(6*1000, QtCore.QCoreApplication.quit)
    sys.exit(app.exec_())

0
投票

子类化 QThread 不是不好的做法吗?,我记得官方文档是这么说的。

© www.soinside.com 2019 - 2024. All rights reserved.