pyQt:如何更新标签? [英] pyQt: How do I update a label?

查看:676
本文介绍了pyQt:如何更新标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用qtDesigner创建了这个简单的UI,我想每10秒用一个函数的值更新标签,但是我不知道该怎么做.我尝试了不同的方法,但是没有用.

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_())

推荐答案

理想情况下,您将创建QWidget的子类(而不是像使用Form那样简单地实例化它).但是这是一种您可以进行最少更改的方法.

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.

您具有可以更新标签的功能.然后使用QTimer定期触发它(在这种情况下,每10秒触发一次).

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_())

这篇关于pyQt:如何更新标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆