Change QLabel text dynamically in PyQt4

前端 未结 2 1188
误落风尘
误落风尘 2020-12-06 03:02

My question is: how can I change the text in a label? The label is inside a layout, but setText() does not seem to work - maybe I am not doing it right.

<
相关标签:
2条回答
  • 2020-12-06 03:33

    You are not using the modules created by pyuic correctly. You should never directly edit these modules - they should imported into your main application.

    The UI classes that pyuic generates have a setupUi method. This method takes an instance of the top-level class that you created in Qt Designer, and it will add all the widgets from designer to that instance. So label_nombre, for example, would become an attribute of the instance passed to setupUi. Usually, you will create a subclass of the top-level class, and then pass in self as the instance (see below).

    I would suggest that you re-generate your ui files with pyuic and save them as, say dialog_ui.py and dashboard_ui.py.

    The structure of your program would then become something like this:

    from PyQt4 import QtCore, QtGui
    from dashboard_ui import Ui_dashboard
    from dialog_ui import Ui_Dialog
    
    class logica_login(QtGui.QDialog, Ui_Dialog):
        def __init__(self):
            QtGui.QDialog.__init__(self)
            self.setupUi(self)
            self.bloguin_aceptar.clicked.connect(self.validacion)
            self.blogin_cancelar.clicked.connect(self.reject)
    
        def validacion(self):
            ...
    
    class logica_tablero(QtGui.QMainWindow, Ui_dashboard):
        def __init__(self):
            QtGui.QMainWindow.__init__(self)
            self.setupUi(self)
            self.label_nombre.setText("hola")
            ...
    
    if __name__ == "__main__":
    
        app = QtGui.QApplication(sys.argv)
        login = logica_login()
        if login.exec_() == QtGui.QDialog.Accepted:
            dashboard = logica_tablero()
            dashboard.showMaximized()
            sys.exit(app.exec_())
    
    0 讨论(0)
  • 2020-12-06 03:50

    Replace this line in logica_tablero:

    self.ui.self.label_nombre.setText("hola")
    

    with this:

    self.ui.label_nombre.setText("hola")
    
    0 讨论(0)
提交回复
热议问题