Python 在 PyQt4 中动态更改 QLabel 文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19985640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:09:29  来源:igfitidea点击:

Change QLabel text dynamically in PyQt4

pythontextpyqtqlabelpyuic

提问by n3rio

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.

我的问题是:如何更改标签中的文本?标签在布局内,但setText()似乎不起作用 - 也许我做得不对。

Here is my code:

这是我的代码:

this is the Main windows GUI, the one Qt-Designer gives:

这是主窗口 GUI,Qt-Designer 提供的一个:

class Ui_dashboard(QtGui.QMainWindow):
def setupUi(self, dashboard):
    dashboard.setObjectName(_fromUtf8("dashboard"))
    dashboard.resize(734, 703)
    icon = QtGui.QIcon()
    icon.addPixmap(QtGui.QPixmap(_fromUtf8("../../../../Documents and Settings/cgarcia/Escritorio/metromara - imagenes - nerio/logoM.JPG")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
    dashboard.setWindowIcon(icon)
    dashboard.setWindowOpacity(1.0)
    self.centralwidget = QtGui.QWidget(dashboard)
    self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
    self.frame = QtGui.QFrame(self.centralwidget)
    self.frame.setGeometry(QtCore.QRect(30, 20, 261, 119))
    self.frame.setFrameShape(QtGui.QFrame.Box)
    self.frame.setFrameShadow(QtGui.QFrame.Plain)
    self.frame.setObjectName(_fromUtf8("frame"))
    self.gridLayout = QtGui.QGridLayout(self.frame)
    self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
    self.label_5 = QtGui.QLabel(self.frame)
    font = QtGui.QFont()
    font.setBold(True)
    font.setWeight(75)
    self.label_5.setFont(font)
    self.label_5.setObjectName(_fromUtf8("label_5"))
    self.gridLayout.addWidget(self.label_5, 4, 0, 1, 1)
    self.label_4 = QtGui.QLabel(self.frame)
    font = QtGui.QFont()
    font.setBold(True)
    font.setWeight(75)
    self.label_4.setFont(font)
    self.label_4.setObjectName(_fromUtf8("label_4"))
    self.gridLayout.addWidget(self.label_4, 3, 0, 1, 1)
    self.label_ci = QtGui.QLabel(self.frame)
    font = QtGui.QFont()
    font.setBold(True)
    font.setWeight(75)
    self.label_ci.setFont(font)
    self.label_ci.setObjectName(_fromUtf8("label_ci"))
    self.gridLayout.addWidget(self.label_ci, 1, 1, 1, 1)
    self.label_cargo = QtGui.QLabel(self.frame)
    font = QtGui.QFont()
    font.setBold(True)
    font.setWeight(75)
    self.label_cargo.setFont(font)
    self.label_cargo.setObjectName(_fromUtf8("label_cargo"))
    self.gridLayout.addWidget(self.label_cargo, 2, 1, 1, 1)
    self.label_gerencia = QtGui.QLabel(self.frame)
    font = QtGui.QFont()
    font.setBold(True)
    font.setWeight(75)
    self.label_gerencia.setFont(font)
    self.label_gerencia.setObjectName(_fromUtf8("label_gerencia"))
    self.gridLayout.addWidget(self.label_gerencia, 3, 1, 1, 1)
    self.label_nombre = QtGui.QLabel(self.frame)
    font = QtGui.QFont()
    font.setBold(True)
    font.setWeight(75)
    self.label_nombre.setFont(font)
    self.label_nombre.setObjectName(_fromUtf8("label_nombre"))
    self.gridLayout.addWidget(self.label_nombre, 0, 1, 1, 1)
    self.label_2 = QtGui.QLabel(self.frame)
    font = QtGui.QFont()
    font.setBold(True)
    font.setWeight(75)
    self.label_2.setFont(font)
    self.label_2.setObjectName(_fromUtf8("label_2"))
    self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1)
    self.label = QtGui.QLabel(self.frame)
    font = QtGui.QFont()
    font.setBold(True)
    font.setWeight(75)
    self.label.setFont(font)
    self.label.setObjectName(_fromUtf8("label"))
    self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
    self.label_3 = QtGui.QLabel(self.frame)
    font = QtGui.QFont()
    font.setBold(True)
    font.setWeight(75)
    self.label_3.setFont(font)
    self.label_3.setObjectName(_fromUtf8("label_3"))
    self.gridLayout.addWidget(self.label_3, 2, 0, 1, 1)
    self.label_departamento = QtGui.QLabel(self.frame)
    font = QtGui.QFont()
    font.setBold(True)
    font.setWeight(75)
    self.label_departamento.setFont(font)
    self.label_departamento.setObjectName(_fromUtf8("label_departamento"))
    self.gridLayout.addWidget(self.label_departamento, 4, 1, 1, 1)
    self.treeView = QtGui.QTreeView(self.centralwidget)
    self.treeView.setGeometry(QtCore.QRect(30, 160, 161, 481))
    self.treeView.setFrameShape(QtGui.QFrame.Box)
    self.treeView.setFrameShadow(QtGui.QFrame.Plain)
    self.treeView.setObjectName(_fromUtf8("treeView"))
    dashboard.setCentralWidget(self.centralwidget)
    self.menubar = QtGui.QMenuBar(dashboard)
    self.menubar.setGeometry(QtCore.QRect(0, 0, 734, 20))
    self.menubar.setObjectName(_fromUtf8("menubar"))
    dashboard.setMenuBar(self.menubar)
    self.statusbar = QtGui.QStatusBar(dashboard)
    self.statusbar.setObjectName(_fromUtf8("statusbar"))
    dashboard.setStatusBar(self.statusbar)

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

def retranslateUi(self, dashboard):
    dashboard.setWindowTitle(_translate("dashboard", "Metro de Maracaibo.", None))
    self.label_5.setText(_translate("dashboard", "DEPARTAMENTO", None))
    self.label_4.setText(_translate("dashboard", "GERENCIA", None))
    self.label_ci.setText(_translate("dashboard", "...", None))
    self.label_cargo.setText(_translate("dashboard", "...", None))
    self.label_gerencia.setText(_translate("dashboard", "...", None))
    self.label_nombre.setText(_translate("dashboard", "...", None))
    self.label_2.setText(_translate("dashboard", "C.I.:", None))
    self.label.setText(_translate("dashboard", "NOMBRE", None))
    self.label_3.setText(_translate("dashboard", "CARGO", None))
    self.label_departamento.setText(_translate("dashboard", "...", None))

this is the logic of the interfaces:

这是接口的逻辑:

class logica_login(Ui_Dialog):
def __init__(self):
    QtGui.QDialog.__init__(self)
    #QtGui.QMainWindow.__init__(self)
    Dialog = Ui_Dialog(self)
    self.setupUi(Dialog)
    self.bloguin_aceptar.clicked.connect(self.validacion)
    self.blogin_cancelar.clicked.connect(self.reject)
    Dialog.show()
    Dialog.exec_()
    #PRINT DE PRUEBA
    print('hola')

#METODO DE VALIDACION
#####################
def validacion(self):
    #CONEXION A LA BASE DE DATOS.
    #############################
    db = QSqlDatabase.addDatabase("QPSQL")
    db.setHostName("localhost")
    db.setDatabaseName("postgres")
    db.setUserName("postgres")
    db.setPassword("1234")
    #self.ui.label_nombre.setText(str(Ui_Dialog.le_user.text()))

    #RESPUESTA EN CASO DE FALLO EN CONEXION CON LA BASE DE DATOS.
    #############################################################
    if not db.open():
        QtGui.QMessageBox.about(self, "ERROR","LO SENTIMOS, EXPERIMENTAMOS PROBLEMAS DE CONEXION CON EL SERVIDOR.")

    #CONSULTA A LA BASE DE DATOS DE LA CLAVE Y CONTRASE?A
    #####################################################
    consulta = QSqlQueryModel()
    consulta.setQuery("SELECT usuario, contrase?a, id FROM usuarios")
    lista = []
    i = consulta.rowCount()

    #BUCLE DE EXTRACCION Y REORDENACION DE DATOS EN LA LISTA "LISTA"
    ################################################################
    while i >= 0:
        db_user = consulta.record(i).value("usuario");
        db_pass = consulta.record(i).value("contrase?a");
        db_id = consulta.record(i).value("id")
        str_user = str(db_user)
        str_pass = str(db_pass)
        auth_db = (str_user, str_pass)
        lista.append(auth_db)

        i = (i-1)
        print(lista)

    user = self.le_user.text()
    passw = self.le_pass.text()



    for usrname, password in lista:
        if ((user == usrname) and (passw == password)):
            print('logueo exitoso')
            QtGui.QMessageBox.about(self, "Logue Exitoso.", "ACCESO CONCEDIDO.")
            self.deleteLater()
            go = True
            print(go)
            dashboard.showMaximized()
            #self.ui.label_nombre.setText(str(Ui_Dialog.le_user.text())) ### LOGICA_LOGIN NO TIENE ATRIBUTO UI
            break;
        elif ((user == usrname) and (passw != password)):
            QtGui.QMessageBox.about(self, "ERROR","Contrase?a Incorrecta.")
            break;
        elif ((user != usrname) and (passw == password)):
            QtGui.QMessageBox.about(self, "ERROR","Nombre de usuario Incorrecto")
            break;
    else:
        QtGui.QMessageBox.about(self, "ERROR","Nombre de usuario y Contrase?a Incorrecto")


class logica_tablero(Ui_dashboard):

def __init__(self):
    l_n = Ui_dashboard.label_nombre()
    QtGui.QMainWindow.__init__(self)
    self.ui = Ui_dashboard(self)
    self.ui.setupUi(self)
    #logica_tablero.ui.l_n.setText("hola")
    Ui_dashboard.label_5.setText(("hola"))



def main():
    app = QtGui.QApplication(sys.argv)
    if 1 == 1 :
        loginApp = logica_login()
        loginApp.show()
    else:
        mainApp = Ui_dashboard()
        mainApp.setupUi(dash)
        dash.showMaximized()
        #Ui_dashboard.label_nombre.setText(("hola"))

    sys.exit(app.exec_())

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    ## ESTA PARTE HA SIDO UN DOLOR DE CABEZA, NO OLVIDAR NI BORRAR.
    #BUCLE DE DASHBOARD
    #---------------------------------
    dashboard = QtGui.QMainWindow()
    mainApp = Ui_dashboard()
    mainApp.setupUi(dashboard)
    #BUCLE DE LOGIN
    #---------------------------------
    l = logica_login()
    l   
    #---------------------------------
    sys.exit(app.exec_())    

I want to change the labels once the user logs in to the program. The label I want to change is label_nombre, and I want to replace it for le_user, which corresponds to one of the QLineEdits.

我想在用户登录程序后更改标签。我想更改的标签是label_nombre,我想将其替换为le_user,它对应于 QLineEdits 之一。

UPDATE

更新

I made all the changes you told me to do, the project is looking pretty much organized, but now i am getting this output:

我做了你告诉我要做的所有改变,这个项目看起来很有条理,但现在我得到了这个输出:

TypeError: descriptor 'init' requires a 'sip.simplewrapper' object but received a 'logica_login'

类型错误:描述符“ init”需要“sip.simplewrapper”对象,但收到“logica_login”

UPDATE 2

更新 2

*TypeError: descriptor 'init' requires a 'sip.simplewrapper' object but received a 'logica_login' -------------------------> SOLVE

*TypeError: 描述符 ' init' 需要一个 'sip.simplewrapper' 对象但收到了一个 'logica_login' ------------------------->解决

Now, I have the same problem that began this all deal, the label wont change its content.

现在,我遇到了与开始这一切交易相同的问题,标签不会改变其内容。

采纳答案by ekhumoro

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

您没有正确使用 pyuic 创建的模块。您永远不应该直接编辑这些模块 - 它们应该导入到您的主应用程序中。

The UI classes that pyuic generates have a setupUimethod. 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 attributeof the instance passed to setupUi. Usually, you will create a subclass of the top-level class, and then pass in selfas the instance (see below).

pyuic 生成的 UI 类有一个setupUi方法。此方法采用您在 Qt 设计器中创建的顶级类的实例,并将设计器中的所有小部件添加到该实例中。因此label_nombre,例如,将成为传递给 的实例的属性setupUi。通常,您会创建顶级类的子类,然后self作为实例传入(见下文)。

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

我建议你用 pyuic 重新生成你的 ui 文件并将它们保存为,比如说dialog_ui.pydashboard_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_())

回答by Roberto Bonvallet

Replace this line in logica_tablero:

将此行替换为logica_tablero

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

with this:

有了这个:

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