Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pyQt: How do I update a label?

I created this simple UI with qtDesigner and I want to update my label every 10 seconds with the value of a function, but I have no idea how to do this.I've tried different things but nothing worked.

def example():
    ...
    return text

UI:

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(400, 300)
        self.label = QtWidgets.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(165, 125, 61, 16))
        self.label.setObjectName("label")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.label.setText(_translate("Form", plsupdatethis)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())
like image 702
T.T. Avatar asked Apr 13 '16 18:04

T.T.


People also ask

How do I change the text of a label in PyQt?

setText() method is used to change the content of the label.

What is setText in Python?

setText(string)Sets the text of the object to string. Example: message.

What is a widget in PyQt?

Widgets are the basic building blocks for graphical user interface (GUI) applications built with Qt. Each GUI component (e.g. buttons, labels, text editors) is a widget that is placed somewhere within a user interface window, or is displayed as an independent window.

What is layout in PyQt?

In PyQt, layout managers are classes that provide the required functionality to automatically manage the size, position, and resizing behavior of the widgets in the layout. With layout managers, you can automatically arrange child widgets within any parent, or container, widget.


1 Answers

Ideally, you would create a subclass of QWidget (instead of simply instantiating it the way you are doing with Form). But here is a way you could do it with minimal changes.

You have a function that is capable of updating the label. Then use a QTimer to trigger it at regular intervals (in this case, every 10 seconds).

import datetime

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()

    def update_label():
        current_time = str(datetime.datetime.now().time())
        ui.label.setText(current_time)

    timer = QtCore.QTimer()
    timer.timeout.connect(update_label)
    timer.start(10000)  # every 10,000 milliseconds

    sys.exit(app.exec_())
like image 85
Brendan Abel Avatar answered Sep 21 '22 07:09

Brendan Abel