当前位置: 首页 > article >正文

Pyqt5高级技巧:多线程任务、窗体交互、常用控件介绍(含基础Demo)

一、多线程任务和多窗体交互

【main】

import MainForm
#import CRUD
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox

if __name__ == '__main__':
    app = QApplication(sys.argv)
    MainWindow = QMainWindow()
    ui = MainForm.Ui_MainWindow()#也可能是Ui_Form/Ui_widget这里填写的是生成的类名
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

【MainForm.py】

# -*- coding: utf-8 -*-
import time

# Form implementation generated from reading ui file 'MainForm.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QThread, pyqtSignal


class Ui_MainWindow(object):
    def __init__(self):
        super().__init__()


    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("ril.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        MainWindow.setWindowIcon(icon)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(300, 150, 181, 31))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.clicked.connect(self.open_new_window)
        self.progressBar = QtWidgets.QProgressBar(self.centralwidget)
        self.progressBar.setGeometry(QtCore.QRect(30, 440, 741, 51))
        self.progressBar.setProperty("value", 0)
        self.progressBar.setObjectName("progressBar")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(290, 260, 201, 28))
        self.pushButton_2.setObjectName("pushButton_2")

        MainWindow.setCentralWidget(self.centralwidget)

        self.worker = WorkerThread()  # 创建WorkerThread实例
        self.worker.progress.connect(self.update_progress)  # 多线程连接进度条
        self.pushButton_2.clicked.connect(self.worker.start) # 开始按钮连接多线程


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

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "点击我打开另一个窗体"))
        self.pushButton_2.setText(_translate("MainWindow", "点击我,执行多线程任务"))

    def open_new_window(self):
        import Form2
        # 创建新的子窗口
        self.new_window = Form2.Ui_Form()  # 使用 Form2 类
        self.new_window.setWindowTitle("一个新的窗体")
        # Form2信号 关联 主窗口获取方法getdata
        self.new_window.signal.connect(self.MainGetData)
        # 发送消息到Form2
        self.new_window.SubGetData("hello")
        self.new_window.show()  # 显示新窗体

    def update_progress(self, value):#设置进度条的值
        self.progressBar.setValue(value)

    def MainGetData(self,msg):#接收Form2的信息
        print(f"我是主窗体,我收到了: {msg}")

class WorkerThread(QThread):  #多线程任务
    progress = pyqtSignal(int)  # 自定义信号用于发送进度

    def run(self):
        for i in range(1, 6):
            time.sleep(i)  # 模拟耗时操作
            self.progress.emit(i * 20)  # 发送当前进度
            print(f"任务{i}完成了")
        self.progress.emit(100)  # 任务全部完成

【Form2】

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'Form2.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import pyqtSignal


class Ui_Form(QtWidgets.QWidget):#【改】1.改为继承QtWidgets.QWidget

    signal = pyqtSignal(str)#信号,沟通主窗体的getdata方法

    def __init__(self):# 【加】2.初始化界面方法
        super().__init__()
        self.setupUi(self)

    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(571, 345)
        self.label = QtWidgets.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(190, 30, 281, 161))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(36)
        self.label.setFont(font)
        self.label.setObjectName("label")
        self.lineEdit = QtWidgets.QLineEdit(Form)
        self.lineEdit.setGeometry(QtCore.QRect(220, 160, 151, 31))
        self.lineEdit.setObjectName("lineEdit")
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(240, 210, 111, 28))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.clicked.connect(self.SubSendData)

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

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.label.setText(_translate("Form", "子窗体"))
        self.pushButton.setText(_translate("Form", "发送给主窗体"))

    def SubGetData(self,msg):#接收主窗体的信息
        print(f"我是Form2,我收到了: {msg}")

    def SubSendData(self):#发送信息给主窗体
        outputdata = self.lineEdit.text()
        self.signal.emit(outputdata)
        self.close()

【效果图】

运行main.py函数,点击打开窗体即打开Form2,点击多线程任务即可实现多线程任务。

二、增删改查Demo

【main.py】

#import MainForm
import CRUD
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox

if __name__ == '__main__':
    app = QApplication(sys.argv)
    MainWindow = QMainWindow()
    ui = CRUD.Ui_Form()#也可能是Ui_Form/Ui_widget这里填写的是生成的类名
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

【CRUD.py】 

import SQLiterConnect


from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(1074, 759)
        self.label = QtWidgets.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(410, 0, 281, 91))
        #icon = QtGui.QIcon()
        #icon.addPixmap(QtGui.QPixmap("ril.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        #Form.setWindowIcon(icon)#设置icon图标
        font = QtGui.QFont()
        font.setFamily("黑体")
        font.setPointSize(26)
        self.label.setFont(font)
        self.label.setObjectName("label")
        self.lineEdit = QtWidgets.QLineEdit(Form)
        self.lineEdit.setGeometry(QtCore.QRect(80, 110, 111, 31))
        self.lineEdit.setObjectName("lineEdit")
        self.comboBox = QtWidgets.QComboBox(Form)
        self.comboBox.setGeometry(QtCore.QRect(520, 110, 141, 31))
        self.comboBox.setObjectName("comboBox")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.checkBox = QtWidgets.QCheckBox(Form)
        self.checkBox.setGeometry(QtCore.QRect(700, 110, 111, 21))
        self.checkBox.setObjectName("checkBox")
        self.lineEdit_2 = QtWidgets.QLineEdit(Form)
        self.lineEdit_2.setGeometry(QtCore.QRect(300, 110, 131, 31))
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(840, 110, 93, 28))
        self.pushButton.setObjectName("pushButton")
        self.tableWidget = QtWidgets.QTableWidget(Form)
        self.tableWidget.setGeometry(QtCore.QRect(30, 170, 1021, 571))
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setColumnCount(0)
        self.tableWidget.setRowCount(0)
        self.label_2 = QtWidgets.QLabel(Form)
        self.label_2.setGeometry(QtCore.QRect(30, 120, 72, 15))
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(Form)
        self.label_3.setGeometry(QtCore.QRect(250, 120, 72, 15))
        self.label_3.setObjectName("label_3")
        self.label_4 = QtWidgets.QLabel(Form)
        self.label_4.setGeometry(QtCore.QRect(470, 120, 72, 15))
        self.label_4.setObjectName("label_4")
        self.pushButton_2 = QtWidgets.QPushButton(Form)
        self.pushButton_2.setGeometry(QtCore.QRect(940, 110, 93, 28))
        self.pushButton_2.setObjectName("pushButton_2")
        #绑定事件
        self.pushButton.clicked.connect(self.query)
        self.pushButton_2.clicked.connect(self.add)
        self.lineEdit.textChanged.connect(self.query)
        self.lineEdit_2.textChanged.connect(self.query)
        self.checkBox.stateChanged.connect(self.query)
        self.comboBox.currentIndexChanged.connect(self.query)
        #初始化
        self.tableWidget.setColumnCount(8)#设置8列
        self.tableWidget.setHorizontalHeaderLabels(["ID", "姓名", "年龄", "班级", "性别", "是否是领导", "编辑", "删除"])
        self.query()
        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "增删改查演示"))
        self.label.setText(_translate("Form", "增删改查Demo"))
        self.comboBox.setItemText(0, _translate("Form", "全部"))
        self.comboBox.setItemText(1, _translate("Form", "男"))
        self.comboBox.setItemText(2, _translate("Form", "女"))
        self.checkBox.setText(_translate("Form", "是否是领导"))
        self.pushButton.setText(_translate("Form", "查询"))
        self.label_2.setText(_translate("Form", "姓名:"))
        self.label_3.setText(_translate("Form", "班级:"))
        self.label_4.setText(_translate("Form", "性别:"))
        self.pushButton_2.setText(_translate("Form", "新增"))

    def query(self):
        try:
            # 清空表格
            self.tableWidget.setRowCount(0)

            # 获取输入数据
            name = self.lineEdit.text()
            classes = self.lineEdit_2.text()
            sex = self.comboBox.currentText()
            is_leader = 1 if self.checkBox.isChecked() else 0

            #拼接SQL
            sql = "SELECT * FROM Student WHERE 1=1"
            if name:
                sql += f" AND Name LIKE '%{name}%'"
            if classes:
                sql += f" AND Classes LIKE '%{classes}%'"
            if sex and sex!="全部":
                sql+= f" AND Sex = '{sex}'"
            if is_leader:
                sql += f" AND IsLeader = {is_leader}"

            rows = SQLiterConnect.sqlquery(sql)


            # 填充表格
            for row in rows:
                rowPosition = self.tableWidget.rowCount()
                self.tableWidget.insertRow(rowPosition)
                for col, item in enumerate(row):
                    table_item = QtWidgets.QTableWidgetItem(str(item))
                    # 设置内容居中对齐
                    table_item.setTextAlignment(QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter)
                    self.tableWidget.setItem(rowPosition, col, table_item)

                editButton = QtWidgets.QPushButton("编辑")
                editButton.clicked.connect(lambda checked, row=row: self.edit(row))
                self.tableWidget.setCellWidget(rowPosition, 6, editButton)

                deleteButton = QtWidgets.QPushButton("删除")
                deleteButton.clicked.connect(lambda checked, row=rowPosition: self.delete(row))
                self.tableWidget.setCellWidget(rowPosition, 7, deleteButton)
        except Exception as e:
            print(f"查询出错{e}")

    def add(self):
        try:
            dialog = EditDialog((None, '', '', '', '', 0))  # 创建空记录的对话框
            if dialog.exec_():
                data = dialog.get_data()
                #编写SQL:
                sql = f"INSERT INTO Student (Name, Age, Classes, Sex, IsLeader) VALUES ('{data['name']}', {data['age']}, '{data['classes']}', '{data['sex']}', {data['is_leader']})"
                SQLiterConnect.sqlexecute(sql)
                self.query()
        except Exception as e:
            print(f"新增出错{e}")

    def edit(self, row):
        try:
            dialog = EditDialog(row)
            if dialog.exec_():
                data = dialog.get_data()
                item_id = row[0]

                #编写并执行SQL
                sql=f"""
                UPDATE Student 
                SET Name = '{data['name']}', Age = '{data['age']}', Classes = '{data['classes']}', 
                Sex = '{data['sex']}', IsLeader = '{data['is_leader']}' 
                WHERE ID = {item_id}"""
                SQLiterConnect.sqlexecute(sql)
                self.query()
        except Exception as e:
            print(f"编辑出错{e}")

    def delete(self, row):
        try:
            item_id = self.tableWidget.item(row, 0).text()
            reply = QtWidgets.QMessageBox.question(None, '删除', '确定删除吗?',
                                                   QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
                                                   QtWidgets.QMessageBox.No)
            if reply == QtWidgets.QMessageBox.Yes:
                sql = f"DELETE FROM Student WHERE ID = {item_id}"
                SQLiterConnect.sqlexecute(sql)
                self.query()
        except Exception as e:
            print(f"删除出错{e}")

class EditDialog(QtWidgets.QDialog):#编辑对话框
    def __init__(self, row, parent=None):
        super(EditDialog, self).__init__(parent)

        self.row = row
        self.setWindowTitle("编辑框")
        self.setGeometry(100, 100, 300, 200)

        # self.setWindowIcon(QtGui.QIcon("ril.ico"))#设置icon图标

        self.name_edit = QtWidgets.QLineEdit(self)
        self.name_edit.setText(row[1])

        self.age_edit = QtWidgets.QLineEdit(self)
        self.age_edit.setText(str(row[2]))

        self.classes_edit = QtWidgets.QLineEdit(self)
        self.classes_edit.setText(row[3])

        self.sex_combo = QtWidgets.QComboBox(self)
        self.sex_combo.addItems(["全部","男", "女"])
        self.sex_combo.setCurrentText(row[4])

        self.is_leader_check = QtWidgets.QCheckBox("Is Leader", self)
        self.is_leader_check.setChecked(row[5])

        self.save_button = QtWidgets.QPushButton("保存", self)
        self.save_button.clicked.connect(self.save)

        layout = QtWidgets.QFormLayout(self)
        layout.addRow("Name:", self.name_edit)
        layout.addRow("Age:", self.age_edit)
        layout.addRow("Classes:", self.classes_edit)
        layout.addRow("Sex:", self.sex_combo)
        layout.addRow("Is Leader:", self.is_leader_check)
        layout.addWidget(self.save_button)

        # 计算并设置对话框位置为屏幕中心
        screen_rect = QtWidgets.QDesktopWidget().screenGeometry()
        dialog_rect = self.geometry()
        x = (screen_rect.width() - dialog_rect.width()) // 2
        y = (screen_rect.height() - dialog_rect.height()) // 2
        self.move(x, y)

    def save(self):
        self.accept()

    def get_data(self):
        try:
            return {
                'name': self.name_edit.text(),
                'age': int(self.age_edit.text()),
                'classes': self.classes_edit.text(),
                'sex': self.sex_combo.currentText(),
                'is_leader': 1 if self.is_leader_check.isChecked() else 0
            }
        except Exception as e:
            print(f"编辑框转化数据出错{e}")

【SQLiterConnect】(sqlite数据库)

from datetime import datetime
import sqlite3

conn = sqlite3.connect('database.db')
cursor = conn.cursor()
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

def sqlquery(sql):
    try:
        rows = cursor.execute(sql).fetchall()
        print(f"查询成功,数据:{len(rows)}条,时间:{now}")
        return rows
    except Exception as e:
        print(f"查询出现错误: {e},时间:{now},出错SQL:\n{sql}")

def sqlexecute(sql):
    try:
        cursor.execute(sql)
        cursor.connection.commit()
        print(f"增删改成功,时间:{now}")
    except Exception as e:
        print(f"增删改出现错误: {e},时间:{now},出错SQL:\n{sql}")#不要出现GO等脚本关键字
        cursor.connection.rollback()

if __name__ == '__main__':
    pass
    # data = sqlquery("SELECT * FROM BuyTable WHERE ID='1'")
    # ins = 100
    # data = sqlquery(f"SELECT * FROM BuyTable WHERE ID={ins}")

 

 

 

不断更新中..... 


http://www.kler.cn/a/284002.html

相关文章:

  • 【VIM】vim 常用命令
  • 鸿蒙next版开发:相机开发-适配不同折叠状态的摄像头变更(ArkTS)
  • C语言 | Leetcode C语言题解之第556题下一个更大元素III
  • qt QKeySequence详解
  • 树形dp总结
  • 【Pikachu】目录遍历实战
  • Apache Tomcat与反向代理
  • Elastic Stack(三):Logstash介绍及安装
  • JDBC中的execute, executeQuery, 和 executeUpdate方法区别
  • 如何构建小学至大学素质评价档案系统 —— php Vue 实践指南
  • 【 html+css 绚丽Loading 】 000027 旋风破云扇
  • HTML5 数据 URL(data URL)是什么?
  • Android中AsyncTask的基本用法
  • 如何处理时间序列异常值?理解、检测和替换时间序列中的异常值
  • 智能合约漏洞(四)
  • 美国洛杉矶多ip服务器特点
  • dp+差分数组
  • 8.29笔记
  • 组合式API-reactive和ref函数,computed计算属性,watch函数
  • NASA数据集:ASO L4雷达雪神数据集
  • BSV区块链发布Golang软件开发工具包
  • 开源网络安全大模型 - SecGPT
  • tcp/udp 可视化 调试工具; tcp/udp 发送客户端;查看tcp连接;netassist;packet sender;tcp view;
  • 【JavaEE初阶】HTTP响应报文
  • 【C++STL详解(十三)】unordered系列容器的介绍与使用
  • linux驱动--中断等待队列