我试图将代码从PyQt4移植到PyQt5,但不理解为什么以下内容不起作用。未调用该插槽。我看到一堆of子,没有to。我想念什么?
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
答案 0 :(得分:2)
第一个QThread已经从QObject继承,因此没有必要将其用作接口。另一方面,QThread必须存在于事件循环中,因为这允许信号的传输,例如,在您的情况下,您要用time.sleep(6)阻塞事件循环,而不是如果您想在之后完成循环6秒使用QTimer:
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_())