动态更改QLabel文本不起作用

时间:2019-07-17 10:34:38

标签: python pyqt pyqt5 qt-designer qlabel

我正在尝试使用QtDesigner pyqt5动态更改QLabel文本。

下面是我试图用来动态更改QLabel文本的代码。

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setObjectName("label")
        self.horizontalLayout.addWidget(self.label, 0, QtCore.Qt.AlignHCenter)
        MainWindow.setCentralWidget(self.centralwidget)

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

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-size:28pt;\">" + self.getTime() + "</span></p></body></html>"))

    def getTime(self):
        time = QTime.currentTime().toString()
        return time

    def data(self):
        time = QTime.currentTime().toString()
        print("Time: " + time)
        self.label.setText(time)
        return time

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()

    ex = Ui_MainWindow()
    timer = QtCore.QTimer()
    timer.timeout.connect(ex.data)
    timer.start(1000) # 1 Second Refesh Rate

    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

当我尝试在QtDesigner中运行代码时,输​​出窗口打开一秒钟,然后自动关闭。不知道是什么导致输出窗口关闭。请建议我解决问题。

3 个答案:

答案 0 :(得分:0)

我建议您在终端/ CMD中执行代码,因为许多IDE无法处理Qt错误,如果执行此操作,则会出现以下错误:

Traceback (most recent call last):
  File "main.py", line 33, in data
    self.label.setText(time)
AttributeError: 'Ui_MainWindow' object has no attribute 'label

该错误表明标签不存在,这是正确的,因为标签是在调用setupUi()之后创建的,但是在您的情况下,“ ex”不会调用它。一种可能的解决方案是首先创建窗口,然后启动计时器:

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    timer = QtCore.QTimer()
    timer.timeout.connect(ui.data)
    timer.start(1000) # 1 Second Refesh Rate
    sys.exit(app.exec_())

但是更好的解决方案是遵循PyQt (1)的建议,该建议指出,您不应修改Qt提供的类,而应将其用作小部件接口:

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setObjectName("label")
        self.horizontalLayout.addWidget(self.label, 0, QtCore.Qt.AlignHCenter)
        MainWindow.setCentralWidget(self.centralwidget)

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

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(
            _translate(
                "MainWindow",
                '<html><head/><body><p><span style=" font-size:28pt;"></span></p></body></html>',
            )
        )


class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        timer = QtCore.QTimer(self)
        timer.timeout.connect(self.data)
        timer.start(1000)
        self.data()

    def data(self):
        time_str = QTime.currentTime().toString()
        self.label.setText(
            '<html><head/><body><p><span style=" font-size:28pt;">{}</span></p></body></html>'.format(
                time_str
            )
        )


if __name__ == "__main__":
    import sys

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

(1)Using the Generated Code

答案 1 :(得分:0)

问题在于您两次Ui_MainWindow处于虚假状态:首先是ex,然后是ui。您将timer.timeout连接到ex,但是仅为setupUi呼叫showui

尝试一下:

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()

    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()

    timer = QtCore.QTimer()
    timer.timeout.connect(ui.data)
    timer.start(1000) # 1 Second Refesh Rate

    sys.exit(app.exec_())

答案 2 :(得分:-1)

Qt Designer仅用于设计 UI,它不允许运行程序。 Qt Creator可以运行程序,但只能运行“真正的” Qt C ++程序。

您需要在Qt Designer之外启动.py脚本,就像正常的Python脚本一样。