I'm trying to make a simple Weather app that also shows the current time. However, after multiple trial and error i am asking for help. I've come to the conclusion that i must commit to threading where the clock is continously run in the background to my PyQt UI. Although, it only freezes and crashes, and i can't understand why. As you can understand i've checked multiple posts already on this issue such as, [1] and [2]. But i'm none the wiser...
This is the minimal reproducible code:
class Clock(QObject):
updated_time = pyqtSignal()
def __init__(self, parent=None):
QObject.__init__(self,parent=parent)
def get_time(self):
#This code is meant to be run continously
#For troubleshooting, ive removed the while-loop momentarily
QThread.sleep(1)
now = datetime.now()
current_time = now.strftime("%H:%M")
self.updated_time.emit()
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.initUI()
def initUI(self):
self.setWindowTitle('WeatherApp')
self.resize(700, 500)
self.clock_label = QLabel(self)
self.clock_label.setText('make me change')
self.show()
thread = QThread()
worker = Clock()
worker.moveToThread(thread)
thread.started.connect(lambda: worker.get_time())
worker.updated_time.connect(self.update_clock())
thread.start()
def update_clock(self):
self.clock_label.setText(current_time)
def main():
app = QApplication(sys.argv)
mw = MainWindow()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
The current code creates the window with the clock label taking the value of the intially declard variable, current_time. In the background, the function from the worker (do_work) is running in the background, iterating continously with a 1 second delay. As i understand from post 1, i should not update the UI from a thread, but even with the invokeMethod i am unable to achieve any success.. Shouldn't the problem be as easy as to emit a signal from the function do_work back to the App? I've adding one but i receive the error: "AttributeError: 'QThread' object has no attribute ".