PDA

View Full Version : How to update GUI from a thread?



kiskivancsi
7th February 2021, 04:37
I'm trying to update the QLabel in the GUI with the number, generated in a thread. Can this be done?



import threading, random, sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5 import QtCore, QtTest


def update():
while True:
n = random.randint(0,22)
QtTest.QTest.qWait(500)

threading.Thread(target=update, daemon = True).start()

class MainWindow(QMainWindow):

def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.setFixedSize(200, 200)

self.labl = QLabel(self)
self.labl.setText("value of n goes here")


app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())

d_stranz
7th February 2021, 18:49
The usual way is to have your thread emit a signal that is handled by a slot in the your GUI thread, where you pass the value as an argument in the signal.

This also means you probably need to use QThread for your thread implementation.

queenelizabeth
13th April 2021, 21:34
Have same problem