Skip to content Skip to sidebar Skip to footer

Updating Pyqt Label

I'm attempting to use a timer for scheduling to update certain values across the grid. Below is the example where I am attempting to update a label based on a timed event. I've suc

Solution 1:

Your code has some errors, if you want to use an attribute of the class with the reserved word self, this method must be a method of the class, for this it changes:

defupdateTime():

to

defupdateTime(self):

If you want to change the text of a QLabel you must use its setText().

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *


classApp(QWidget):
    def__init__(self, parent=None):
        super(App, self).__init__(parent=parent)  # these values change where the main window is placed
        self.title = 'This is my title'
        self.left = 400
        self.top = 400
        self.width = 300
        self.height = 200
        self.initUI()

    definitUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        # call the gridlayout function
        self.createGridLayout()
        self.time_label.text = 'change the value'
        windowLayout = QVBoxLayout()
        windowLayout.addWidget(self.horizontalGroupBox)
        self.setLayout(windowLayout)
        self.show()  # this sets the main window to the screen sizedefcreateGridLayout(self):
        time = self.getTime()
        self.time_label = QLabel(time, self)
        self.horizontalGroupBox = QGroupBox()
        layout = QGridLayout()
        layout.addWidget(QPushButton('1'), 0, 0)
        layout.addWidget(QPushButton(time), 0, 1)
        layout.addWidget(self.time_label, 0, 2)
        self.horizontalGroupBox.setLayout(layout)

    defgetTime(self):
        time = QTime.currentTime().toString()
        return time

    defupdateTime(self):
        time = QTime.currentTime().toString()
        print("Time: " + time)
        self.time_label.setText(time)
        return time


defmain():
    app = QApplication(sys.argv)
    ex = App()

    timer = QTimer()
    timer.timeout.connect(ex.updateTime)
    timer.start(1000)

    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

enter image description here

enter image description here

Post a Comment for "Updating Pyqt Label"