【项目实践】Pyside6+Qtdesigner:登录窗体设计

代码功能:

可实现应用程序用户管理,实现用户登录、注册、密码修改

代码文档结构:

  • user_database.db:数据库文件,用于存储用户数据,第一运行代码时自动生成
  • login.ui:UI文件,由QT设计
  • ui_login.py(由login.ui编译过来)
  • 在终端Windows PowerShell运行如下代码即可生成
bash 复制代码
pyside6-uic login.ui -o ui_login.py
  • test_login.py(如下代码:)
python 复制代码
from PySide6.QtWidgets import QApplication, QWidget, QLineEdit, QPushButton, QVBoxLayout, QHBoxLayout, QLabel, \
    QMessageBox, QDialog
from PySide6.QtCore import Qt, QSize, QFile
from PySide6.QtGui import QPixmap, QPalette, QBrush, QShortcut, QKeySequence

import sqlite3

from src.ui.ui_login import Ui_login_widget


def create_user_table():
    conn = sqlite3.connect('user_database.db')
    cursor = conn.cursor()
    cursor.execute("""
    CREATE TABLE IF NOT EXISTS user (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT NOT NULL UNIQUE,
        password TEXT NOT NULL
    );
    """)
    conn.commit()
    conn.close()


create_user_table()


class LoginWidget(QWidget, Ui_login_widget):
    def __init__(self):
        super().__init__()
        self.setupUi(self)  # Ui_login_widget中的方法,用于设置UI
        # 设置窗口标志:隐藏最小化和最大化
        self.setWindowFlags(Qt.Window | Qt.WindowCloseButtonHint)
        self.setWindowTitle("登录")

        # 连接信号和槽
        self.btn_login.clicked.connect(self.login)
        self.btn_quit.clicked.connect(self.quit)

        # 设置快捷键
        self.shortcut_register = QShortcut(QKeySequence("Ctrl+Alt+R"), self)
        self.shortcut_register.activated.connect(self.register)

        self.shortcut_changePassword = QShortcut(QKeySequence("Ctrl+Alt+P"), self)
        self.shortcut_changePassword.activated.connect(self.changePassword)

        # 设置登录窗体背景颜色和字体
        self.set_default_styleSheet()

        # 设置登录窗体背景图片
        # self.set_background()

    def set_background(self):
        # 加载背景图片
        pixmap = QPixmap("resources/images/images/login_example.jpg")
        # 调整图片尺寸以适应窗体大小
        scaled_pixmap = pixmap.scaled(self.size(), Qt.KeepAspectRatioByExpanding)
        palette = QPalette()
        palette.setBrush(QPalette.Window, QBrush(scaled_pixmap))
        self.setPalette(palette)

    def set_default_styleSheet(self):
        # 设置登录窗体背景颜色和字体
        self.setStyleSheet("""
        background-color: rgb(40, 44, 52);
        color: rgb(255, 255, 255);
        """)

        # 设置登录窗体默认logo,如需更换需要重新编译resources/resources.qrc文件
        self.lb_app_logo.setStyleSheet("""
       background-image: url(:/images/images/images/login_example.png);
       background-position: center;
       background-repeat: no-repeat;
        """)

    def login(self):
        username = self.cBox_username.currentText()
        password = self.le_password.text()

        if len(password) == 0:
            QMessageBox.warning(self, "登录失败", "用户名和密码不能为空!")
            return

        conn = sqlite3.connect('user_database.db')
        cursor = conn.cursor()
        cursor.execute("SELECT password FROM user WHERE username = ?", (username,))
        result = cursor.fetchone()

        if result and result[0] == password:
            QMessageBox.information(self, "登录成功", "您已成功登录!")
        else:
            QMessageBox.warning(self, "登录失败", "密码错误!")

        conn.close()

    def register(self):
        self.register_widget = RegisterWidget()
        self.register_widget.show()

    def changePassword(self):
        username = '普通用户'
        self.change_password_widget = ChangePasswordWidget(username)
        self.change_password_widget.show()

    def quit(self):
        self.close()


class RegisterWidget(QDialog):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("注册")

        # 设置窗口标志:隐藏最小化和最大化
        self.setWindowFlags(Qt.Window | Qt.WindowCloseButtonHint)

        # 设置窗体为模态
        self.setModal(True)

        self.setup_ui()

    def setup_ui(self):
        self.layout = QVBoxLayout(self)

        self.username = QLineEdit(self)
        self.username.setPlaceholderText("用户名")
        self.layout.addWidget(self.username)

        self.password = QLineEdit(self)
        self.password.setPlaceholderText("密码")
        self.layout.addWidget(self.password)

        self.register_button = QPushButton("注册", self)
        self.register_button.clicked.connect(self.register)
        self.layout.addWidget(self.register_button)

    def register(self):
        username = self.username.text()
        password = self.password.text()

        if not username or not password:
            QMessageBox.warning(self, "注册失败", "用户名和密码不能为空!")
            return

        try:
            conn = sqlite3.connect('user_database.db')
            cursor = conn.cursor()
            cursor.execute("INSERT INTO user (username, password) VALUES (?, ?)", (username, password))
            conn.commit()
            QMessageBox.information(self, "注册成功", "您已成功注册!请返回登录。")
            self.close()
        except sqlite3.IntegrityError:
            QMessageBox.warning(self, "注册失败", "用户名已存在!")
        finally:
            conn.close()


class ChangePasswordWidget(QDialog):
    def __init__(self, username):
        super().__init__()
        self.username = username  # 用户名应该在实例化时提供
        self.setWindowTitle("修改密码")

        # 设置窗口标志:隐藏最小化和最大化
        self.setWindowFlags(Qt.Window | Qt.WindowCloseButtonHint)

        # 设置窗体为模态
        self.setModal(True)
        self.setup_ui()

    def setup_ui(self):
        self.layout = QVBoxLayout(self)

        # 旧密码输入框
        self.old_password = QLineEdit(self)
        self.old_password.setPlaceholderText("旧密码")
        self.old_password.setEchoMode(QLineEdit.Password)
        self.layout.addWidget(self.old_password)

        # 新密码输入框
        self.new_password = QLineEdit(self)
        self.new_password.setPlaceholderText("新密码")
        self.new_password.setEchoMode(QLineEdit.Password)
        self.layout.addWidget(self.new_password)

        # 确认新密码输入框
        self.confirm_new_password = QLineEdit(self)
        self.confirm_new_password.setPlaceholderText("确认新密码")
        self.confirm_new_password.setEchoMode(QLineEdit.Password)
        self.layout.addWidget(self.confirm_new_password)

        # 修改密码按钮
        self.change_password_button = QPushButton("修改密码", self)
        self.change_password_button.clicked.connect(self.change_password)
        self.layout.addWidget(self.change_password_button)

    def change_password(self):
        old_password = self.old_password.text()
        new_password = self.new_password.text()
        confirm_new_password = self.confirm_new_password.text()

        if new_password != confirm_new_password:
            QMessageBox.warning(self, "修改失败", "新密码和确认密码不匹配!")
            return

        conn = sqlite3.connect('user_database.db')
        cursor = conn.cursor()

        # 验证旧密码
        cursor.execute("SELECT password FROM user WHERE username = ?", (self.username,))
        result = cursor.fetchone()
        if not result or result[0] != old_password:
            QMessageBox.warning(self, "修改失败", "旧密码错误!")
            conn.close()
            return

        # 更新数据库中的密码
        cursor.execute("UPDATE user SET password = ? WHERE username = ?", (new_password, self.username))
        conn.commit()
        QMessageBox.information(self, "修改成功", "密码修改成功!")
        conn.close()
        self.close()

if __name__ == "__main__":
    app = QApplication([])
    login_widget = LoginWidget()
    login_widget.show()
    app.exec()
相关推荐
小白学大数据11 分钟前
JavaScript重定向对网络爬虫的影响及处理
开发语言·javascript·数据库·爬虫
Python大数据分析@14 分钟前
python操作CSV和excel,如何来做?
开发语言·python·excel
黑叶白树16 分钟前
简单的签到程序 python笔记
笔记·python
Shy96041829 分钟前
Bert完形填空
python·深度学习·bert
time never ceases32 分钟前
使用docker方式进行Oracle数据库的物理迁移(helowin/oracle_11g)
数据库·docker·oracle
Frank牛蛙36 分钟前
1.每日SQL----2024/11/7
数据库·sql
Ciderw38 分钟前
块存储、文件存储和对象存储详细介绍
网络·数据库·nvme·对象存储·存储·块存储·文件存储
薛晓刚39 分钟前
数据库优化指南:如何将基本功能运用到极致?
数据库
上海_彭彭40 分钟前
【提效工具开发】Python功能模块执行和 SQL 执行 需求整理
开发语言·python·sql·测试工具·element
stars_User42 分钟前
MySQL数据库面试题(下)
数据库·mysql