Issue
I am trying to port code from PyQt4 to PyQt5 and am not understanding why the following does not work. The slot is not being called. I see a bunch of ticks and no tocks. What am I missing?
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
Solution
First QThread already inherits from QObject so it is not necessary to use it as an interface. On the other hand the QThread must live in an eventloop since that is what allows the transmission of the signals, for example in your case you are blocking the eventloop with the time.sleep(6), instead if you want to finish the loop after 6 seconds use a 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_())
Answered By - eyllanesc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.