qtcreator ejemplo descargar convertir convert python text pyqt qlabel pyuic

ejemplo - pyqt to python



Cambie el texto de QLabel dinĂ¡micamente en PyQt4 (2)

Mi pregunta es: ¿cómo puedo cambiar el texto en una etiqueta? La etiqueta está dentro de un diseño, pero setText() no parece funcionar, tal vez no lo estoy haciendo bien.

Aquí está mi código:

esta es la GUI de la ventana principal, la que proporciona 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))

esta es la lógica de las 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_())

Quiero cambiar las etiquetas una vez que el usuario inicia sesión en el programa. La etiqueta que quiero cambiar es label_nombre , y quiero reemplazarla por le_user , que corresponde a uno de los QLineEdits.

ACTUALIZAR

Realicé todos los cambios que me pediste que hiciera, el proyecto parece bastante organizado, pero ahora obtengo esta salida:

TypeError: el descriptor '' init '' requiere un objeto ''sip.simplewrapper'' pero recibió un ''logica_login''

ACTUALIZACIÓN 2

* TypeError: el descriptor '' init '' requiere un objeto ''sip.simplewrapper'' pero recibió un ''logica_login'' -------------------------> SOLVE

Ahora, tengo el mismo problema que comenzó con este trato, la etiqueta no cambiará su contenido.


No está utilizando correctamente los módulos creados por pyuic. Nunca debe editar directamente estos módulos; deben importarse a su aplicación principal.

Las clases de UI que pyuic genera tienen un método setupUi . Este método toma una instancia de la clase de nivel superior que creó en Qt Designer y agregará todos los widgets del diseñador a esa instancia. Así que label_nombre , por ejemplo, se convertiría en un atributo de la instancia pasada a setupUi . Por lo general, creará una subclase de la clase de nivel superior y luego pasará en self como instancia (ver a continuación).

Le sugiero que vuelva a generar sus archivos ui con pyuic y los guarde como, digamos dialog_ui.py y dashboard_ui.py .

La estructura de su programa se convertiría en algo así:

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


Reemplace esta línea en logica_tablero :

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

con este:

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