PyQt6中登录凭证的全局复用及代码优化问题
PyQt6 登录凭证传递与代码优化方案
核心问题解决:登录凭证传递
原代码通过全局变量直接获取登录凭证,耦合性极高。优化方案是在登录验证通过后,将凭证作为参数传入主窗口的构造函数,实现数据解耦传递。
代码优化要点
- 替换绝对定位为Qt布局管理器,提升界面自适应能力
- 移除全局变量,通过构造函数传递数据,降低模块耦合
- 减少
app_login重复调用,提升性能 - 动态设置主窗口标题,匹配用户角色
- 规范类结构与实例化流程,避免全局变量污染
- 完善
TableModel方法实现,符合Qt框架规范
完整优化后代码
import sys from sqlprograma import app_login, entidades from PyQt6.QtCore import QSize, QAbstractTableModel, Qt from PyQt6.QtWidgets import (QApplication, QMainWindow, QPushButton, QDialog, QLabel, QLineEdit, QMessageBox, QVBoxLayout, QTableView, QWidget, QSpacerItem, QSizePolicy) class TableModel(QAbstractTableModel): def __init__(self, data): super().__init__() self._data = data def data(self, index, role=Qt.ItemDataRole.DisplayRole): if not index.isValid(): return None if role in (Qt.ItemDataRole.DisplayRole, Qt.ItemDataRole.EditRole): value = self._data.iloc[index.row(), index.column()] return str(value) return super().data(index, role) def rowCount(self, index): return self._data.shape[0] def columnCount(self, index): return self._data.shape[1] def headerData(self, section, orientation, role): if role == Qt.ItemDataRole.DisplayRole: if orientation == Qt.Orientation.Horizontal: return str(self._data.columns[section]) elif orientation == Qt.Orientation.Vertical: return str(self._data.index[section]) return super().headerData(section, orientation, role) class LoginDialog(QDialog): def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("¡Bienvenida!") self.setFixedSize(QSize(300, 200)) self._setup_ui() def _setup_ui(self): layout = QVBoxLayout(self) title_label = QLabel("Ingrese sus datos para iniciar") title_label.setAlignment(Qt.AlignmentFlag.AlignCenter) layout.addWidget(title_label) layout.addSpacerItem(QSpacerItem(20, 20, QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Fixed)) self.username_input = QLineEdit() self.username_input.setPlaceholderText("Usuario") layout.addWidget(self.username_input) self.password_input = QLineEdit(echoMode=QLineEdit.EchoMode.Password) self.password_input.setPlaceholderText("Contraseña") layout.addWidget(self.password_input) layout.addSpacerItem(QSpacerItem(20, 30, QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Fixed)) login_btn = QPushButton("Conectar") login_btn.clicked.connect(self._handle_login) layout.addWidget(login_btn) def _handle_login(self): username = self.username_input.text().strip() password = self.password_input.text().strip() self.username_input.clear() self.password_input.clear() role = app_login(username, password) if not role: QMessageBox.critical(self, "¡Ups!", "Usuario y/o contraseña incorrectos") return main_window = MainWindow(username, password, role) main_window.show() self.accept() class MainWindow(QMainWindow): def __init__(self, username, password, role): super().__init__() self.username = username self.password = password self.role = role self._setup_window() self._setup_table() def _setup_window(self): role_titles = { "public": "Impulsa OE - Contabilidad", "fact": "Impulsa OE - Facturación", "prod": "Impulsa OE - Producción" } self.setWindowTitle(role_titles.get(self.role, "Impulsa OE")) self.setFixedSize(700, 500) def _setup_table(self): table_data = entidades(self.username, self.password) self.table_view = QTableView() self.model = TableModel(table_data) self.table_view.setModel(self.model) self.setCentralWidget(self.table_view) def main(): app = QApplication(sys.argv) login_dialog = LoginDialog() if login_dialog.exec() == QDialog.DialogCode.Accepted: sys.exit(app.exec()) if __name__ == '__main__': main()
优化说明
- 凭证传递:登录验证通过后,直接将用户名、密码和角色传入主窗口构造函数,彻底消除全局变量依赖。
- 布局优化:使用
QVBoxLayout替代绝对定位,控件自动适配窗口,避免界面错位。 - 代码规范:
- 类名采用大驼峰命名(如
MainWindow替代原Acc),方法名采用下划线分隔的小驼峰,符合Python编码规范。 - 将UI初始化、业务逻辑拆分到独立方法,提升代码可读性与可维护性。
- 移除冗余代码与无效语句。
- 类名采用大驼峰命名(如
- 性能优化:仅调用一次
app_login完成身份验证,避免重复执行验证逻辑。 - Qt规范:完善
TableModel的方法实现,对未覆盖的角色返回父类默认处理结果,符合Qt框架要求。
内容的提问来源于stack exchange,提问作者Raknaros
相关产品推荐
相关产品推荐

