# This Python file uses the following encoding: utf-8 import sys from PySide6.QtWidgets import QApplication, QWidget,QMessageBox from PySide6.QtGui import QStandardItemModel, QStandardItem # 导入需要的类 # Important: # 你需要通过以下指令把 form.ui转为ui_form.py # pyside6-uic form.ui -o ui_form.py from ui_form import Ui_Widget # 前提具备 连接库和建立一个user1的表 import pymysql as p # 模块名尽量用小写 ,刚才有大写,所以一直在报红 class Widget(QWidget): def __init__(self, parent=None): super().__init__(parent) self.ui = Ui_Widget() self.ui.setupUi(self) # 连接按钮点击事件到槽函数 self.ui.pushButton.clicked.connect(self.show_message) def show_message(self): # 弹出对话框,显示 "你好" QMessageBox.information(self, "消息", "你好") self.abc() def abc(self): # 连接数据库 conn = p.connect(host='mysql.sqlpub.com', port=3306, user='laocooon', passwd='fc12f7a5215e8e0a', db='huangjin') cur = conn.cursor() try: #查找 sql = "select * from user1" cur.execute(sql) result = cur.fetchall() print(result) # 创建模型 model = QStandardItemModel(len(result), len(result[0])) # 行数和列数 model.setHorizontalHeaderLabels(["ID", "Name", "Password"]) # 设置表头 # 将数据填充到模型中 for row_idx, row_data in enumerate(result): for col_idx, item in enumerate(row_data): model.setItem(row_idx, col_idx, QStandardItem(str(item))) # 将模型设置到 QTableView self.ui.tableView.setModel(model) # 注意:tableView 应该是通过 UI 文件定义的 conn.commit() except Exception as e: print("数据操作错误", e) conn.rollback() finally: cur.close() conn.close() if __name__ == "__main__": app = QApplication(sys.argv) widget = Widget() widget.show() sys.exit(app.exec())