当前位置:   article > 正文

【python】软件开发——PyQt5、Qt Designer、信号与槽机制、计算器实现_python qt

python qt

PyQt5介绍

PyQt5 是一个基于 Python 的 GUI 框架,用于创建跨平台的桌面应用程序。它是 Qt 库的 Python 绑定,结合了 Python 的简洁和易用性以及 Qt 框架的强大功能。

Qt 是一个流行的 C++ 跨平台应用程序开发框架,提供了丰富的图形界面组件、网络通信、数据库访问、多线程等功能。PyQt5 允许开发者使用 Python 语言来创建 Qt 应用程序,从而可以轻松地利用 Qt 提供的功能,并且能够在多个操作系统上运行,包括 Windows、MacOS、Linux 等。

以下是 PyQt5 的一些特点和功能:

  1. 丰富的图形界面组件:PyQt5 提供了大量的预定义 UI 组件,如按钮、标签、文本框、列表框、表格等,可以用于构建直观、交互式的用户界面。
  2. 事件驱动编程:PyQt5 使用信号与槽(Signals & Slots)机制进行事件处理,通过连接信号与槽函数,可以实现对象之间的通信和事件处理。
  3. 多线程支持:PyQt5 提供了对多线程编程的支持,可以轻松地创建和管理多线程应用程序,充分利用多核处理器的优势。
  4. 数据库访问:PyQt5 集成了 Qt 的 SQL 模块,可以方便地连接和操作各种数据库,如 SQLite、MySQL、PostgreSQL 等。
  5. 绘图和动画:PyQt5 提供了强大的绘图功能,可以绘制各种图形、图表和实现动画效果。
  6. 自定义样式:通过使用 Qt 的样式表语言(QSS),可以轻松地自定义应用程序的外观和风格。
  7. 跨平台支持:由于 PyQt5 基于 Qt 库,因此可以在不同的操作系统上运行,并且保持一致的用户体验和行为。

安装PyQt5

pip install PyQt5 -i https://pypi.tuna.tsinghua.edu.cn/simple

PyQt5与Qt Designer

PyQt5 是基于 Python 的 Qt 框架的绑定库,它允许你使用 Python 编程语言来开发 Qt 应用程序。

Qt Designer 是 Qt 提供的一个可视化界面设计工具,用于创建和编辑 Qt 用户界面(UI)文件。

PyQt5 与 Qt Designer 可以很好地配合使用,以加快开发过程并实现界面和功能的分离。

使用Qt Designer

直接打开

不管在Windows,还是在MAC系统下,安装了anaconda后,Qt Designer都会被安装。

在Windows下,启动Qt Designer的路径是:

D:\anaconda3\Library\bin
在这里插入图片描述

PyCharm打开

打开PyCharm——>File——>Settings——>Tool——>External Tools——>创建工具

Name:Qtdesigner

Group:Qt

Program:D:\anaconda3\Library\bin\designer.exe

Working directory:$ProjectFileDir$
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

在这里插入图片描述
启动
在这里插入图片描述
QtDesigner界面
在这里插入图片描述

PyQt5 和 Qt Designer 的使用

使用 Qt Designer 设计界面

在QtDesigner里设计一个计算器ui,保存到项目文件夹
在这里插入图片描述

将 UI 文件转换为 Python 代码

  • 通过命令行转换

使用 PyQt5 提供的 pyuic 工具可以将 .ui 文件转换为相应的 Python 代码。

在项目文件夹路径下cmd命令行运行:

pyuic5 input.ui -o output.py
  • 1

input.ui:ui文件名
output.py:py文件名

  • PyCharm中配置ui文件自动转py文件

打开PyCharm——>File——>Settings——>Tool——>External Tools——>创建工具

Name:pyuic
Group:Qt
Program:D:\anaconda3\python.exe
Arguments:-m PyQt5.uic.pyuic $FileName$ -o $FileNameWithoutExtension$.py
Working directory:$FileDir$
  • 1
  • 2
  • 3
  • 4
  • 5

在这里插入图片描述
使用步骤
在这里插入图片描述

在这里插入图片描述
生成的py文件:计算器ui.py

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

# Form implementation generated from reading ui file '计算器ui.ui'
#
# Created by: PyQt5 UI code generator 5.15.7
#
# 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


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(588, 568)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayoutWidget = QtWidgets.QWidget(self.centralwidget)
        self.gridLayoutWidget.setGeometry(QtCore.QRect(0, 120, 581, 411))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.gridLayoutWidget.sizePolicy().hasHeightForWidth())
        self.gridLayoutWidget.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei")
        font.setPointSize(24)
        self.gridLayoutWidget.setFont(font)
        self.gridLayoutWidget.setObjectName("gridLayoutWidget")
        self.gridLayout = QtWidgets.QGridLayout(self.gridLayoutWidget)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setObjectName("gridLayout")
        self.pushButton_9 = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_9.sizePolicy().hasHeightForWidth())
        self.pushButton_9.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei")
        font.setPointSize(24)
        self.pushButton_9.setFont(font)
        self.pushButton_9.setStyleSheet("color: rgb(85, 170, 255);")
        self.pushButton_9.setFlat(False)
        self.pushButton_9.setObjectName("pushButton_9")
        self.gridLayout.addWidget(self.pushButton_9, 1, 2, 1, 1)
        self.pushButton_eq = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_eq.sizePolicy().hasHeightForWidth())
        self.pushButton_eq.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei")
        font.setPointSize(24)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_eq.setFont(font)
        self.pushButton_eq.setFlat(False)
        self.pushButton_eq.setObjectName("pushButton_eq")
        self.gridLayout.addWidget(self.pushButton_eq, 4, 2, 1, 2)
        self.pushButton_sub = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_sub.sizePolicy().hasHeightForWidth())
        self.pushButton_sub.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei")
        font.setPointSize(24)
        self.pushButton_sub.setFont(font)
        self.pushButton_sub.setFlat(False)
        self.pushButton_sub.setObjectName("pushButton_sub")
        self.gridLayout.addWidget(self.pushButton_sub, 2, 3, 1, 1)
        self.pushButton_5 = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_5.sizePolicy().hasHeightForWidth())
        self.pushButton_5.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei")
        font.setPointSize(24)
        self.pushButton_5.setFont(font)
        self.pushButton_5.setStyleSheet("color: rgb(85, 170, 255);")
        self.pushButton_5.setFlat(False)
        self.pushButton_5.setObjectName("pushButton_5")
        self.gridLayout.addWidget(self.pushButton_5, 2, 1, 1, 1)
        self.pushButton_RE = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_RE.sizePolicy().hasHeightForWidth())
        self.pushButton_RE.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei")
        font.setPointSize(24)
        self.pushButton_RE.setFont(font)
        self.pushButton_RE.setStyleSheet("color: rgb(255, 0, 0);")
        self.pushButton_RE.setFlat(False)
        self.pushButton_RE.setObjectName("pushButton_RE")
        self.gridLayout.addWidget(self.pushButton_RE, 0, 0, 1, 1)
        self.pushButton_prec = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_prec.sizePolicy().hasHeightForWidth())
        self.pushButton_prec.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei")
        font.setPointSize(24)
        self.pushButton_prec.setFont(font)
        self.pushButton_prec.setFlat(False)
        self.pushButton_prec.setObjectName("pushButton_prec")
        self.gridLayout.addWidget(self.pushButton_prec, 4, 1, 1, 1)
        self.pushButton_div = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_div.sizePolicy().hasHeightForWidth())
        self.pushButton_div.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei")
        font.setPointSize(24)
        self.pushButton_div.setFont(font)
        self.pushButton_div.setFlat(False)
        self.pushButton_div.setObjectName("pushButton_div")
        self.gridLayout.addWidget(self.pushButton_div, 0, 3, 1, 1)
        self.pushButton_8 = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_8.sizePolicy().hasHeightForWidth())
        self.pushButton_8.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei")
        font.setPointSize(24)
        self.pushButton_8.setFont(font)
        self.pushButton_8.setStyleSheet("color: rgb(85, 170, 255);")
        self.pushButton_8.setFlat(False)
        self.pushButton_8.setObjectName("pushButton_8")
        self.gridLayout.addWidget(self.pushButton_8, 1, 1, 1, 1)
        self.pushButton_4 = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_4.sizePolicy().hasHeightForWidth())
        self.pushButton_4.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei")
        font.setPointSize(24)
        self.pushButton_4.setFont(font)
        self.pushButton_4.setStyleSheet("color: rgb(85, 170, 255);")
        self.pushButton_4.setFlat(False)
        self.pushButton_4.setObjectName("pushButton_4")
        self.gridLayout.addWidget(self.pushButton_4, 2, 0, 1, 1)
        self.pushButton_0 = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_0.sizePolicy().hasHeightForWidth())
        self.pushButton_0.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei")
        font.setPointSize(24)
        self.pushButton_0.setFont(font)
        self.pushButton_0.setStyleSheet("color: rgb(85, 170, 255);")
        self.pushButton_0.setFlat(False)
        self.pushButton_0.setObjectName("pushButton_0")
        self.gridLayout.addWidget(self.pushButton_0, 4, 0, 1, 1)
        self.pushButton_6 = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_6.sizePolicy().hasHeightForWidth())
        self.pushButton_6.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei")
        font.setPointSize(24)
        self.pushButton_6.setFont(font)
        self.pushButton_6.setStyleSheet("color: rgb(85, 170, 255);")
        self.pushButton_6.setFlat(False)
        self.pushButton_6.setObjectName("pushButton_6")
        self.gridLayout.addWidget(self.pushButton_6, 2, 2, 1, 1)
        self.pushButton_M = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_M.sizePolicy().hasHeightForWidth())
        self.pushButton_M.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei")
        font.setPointSize(24)
        self.pushButton_M.setFont(font)
        self.pushButton_M.setStyleSheet("color: rgb(255, 85, 0);")
        self.pushButton_M.setFlat(False)
        self.pushButton_M.setObjectName("pushButton_M")
        self.gridLayout.addWidget(self.pushButton_M, 0, 1, 1, 1)
        self.pushButton_mul = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_mul.sizePolicy().hasHeightForWidth())
        self.pushButton_mul.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei")
        font.setPointSize(24)
        self.pushButton_mul.setFont(font)
        self.pushButton_mul.setFlat(False)
        self.pushButton_mul.setObjectName("pushButton_mul")
        self.gridLayout.addWidget(self.pushButton_mul, 1, 3, 1, 1)
        self.pushButton_MR = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_MR.sizePolicy().hasHeightForWidth())
        self.pushButton_MR.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei")
        font.setPointSize(24)
        self.pushButton_MR.setFont(font)
        self.pushButton_MR.setStyleSheet("color: rgb(255, 85, 0);")
        self.pushButton_MR.setFlat(False)
        self.pushButton_MR.setObjectName("pushButton_MR")
        self.gridLayout.addWidget(self.pushButton_MR, 0, 2, 1, 1)
        self.pushButton_7 = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_7.sizePolicy().hasHeightForWidth())
        self.pushButton_7.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei")
        font.setPointSize(24)
        self.pushButton_7.setFont(font)
        self.pushButton_7.setStyleSheet("color: rgb(85, 170, 255);")
        self.pushButton_7.setFlat(False)
        self.pushButton_7.setObjectName("pushButton_7")
        self.gridLayout.addWidget(self.pushButton_7, 1, 0, 1, 1)
        self.pushButton_1 = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_1.sizePolicy().hasHeightForWidth())
        self.pushButton_1.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei")
        font.setPointSize(24)
        self.pushButton_1.setFont(font)
        self.pushButton_1.setStyleSheet("color: rgb(85, 170, 255);")
        self.pushButton_1.setObjectName("pushButton_1")
        self.gridLayout.addWidget(self.pushButton_1, 3, 0, 1, 1)
        self.pushButton_2 = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_2.sizePolicy().hasHeightForWidth())
        self.pushButton_2.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei")
        font.setPointSize(24)
        self.pushButton_2.setFont(font)
        self.pushButton_2.setStyleSheet("color: rgb(85, 170, 255);")
        self.pushButton_2.setObjectName("pushButton_2")
        self.gridLayout.addWidget(self.pushButton_2, 3, 1, 1, 1)
        self.pushButton_3 = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_3.sizePolicy().hasHeightForWidth())
        self.pushButton_3.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei")
        font.setPointSize(24)
        self.pushButton_3.setFont(font)
        self.pushButton_3.setStyleSheet("color: rgb(85, 170, 255);")
        self.pushButton_3.setObjectName("pushButton_3")
        self.gridLayout.addWidget(self.pushButton_3, 3, 2, 1, 1)
        self.pushButton_add = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_add.sizePolicy().hasHeightForWidth())
        self.pushButton_add.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei")
        font.setPointSize(24)
        self.pushButton_add.setFont(font)
        self.pushButton_add.setObjectName("pushButton_add")
        self.gridLayout.addWidget(self.pushButton_add, 3, 3, 1, 1)
        self.lcdNumber = QtWidgets.QLCDNumber(self.centralwidget)
        self.lcdNumber.setGeometry(QtCore.QRect(0, 22, 581, 91))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.lcdNumber.sizePolicy().hasHeightForWidth())
        self.lcdNumber.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei")
        font.setPointSize(24)
        self.lcdNumber.setFont(font)
        self.lcdNumber.setDigitCount(18)
        self.lcdNumber.setObjectName("lcdNumber")
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

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

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton_9.setText(_translate("MainWindow", "9"))
        self.pushButton_eq.setText(_translate("MainWindow", "="))
        self.pushButton_sub.setText(_translate("MainWindow", "-"))
        self.pushButton_5.setText(_translate("MainWindow", "5"))
        self.pushButton_RE.setText(_translate("MainWindow", "RE"))
        self.pushButton_prec.setText(_translate("MainWindow", "/100"))
        self.pushButton_div.setText(_translate("MainWindow", "/"))
        self.pushButton_8.setText(_translate("MainWindow", "8"))
        self.pushButton_4.setText(_translate("MainWindow", "4"))
        self.pushButton_0.setText(_translate("MainWindow", "0"))
        self.pushButton_6.setText(_translate("MainWindow", "6"))
        self.pushButton_M.setText(_translate("MainWindow", "M"))
        self.pushButton_mul.setText(_translate("MainWindow", "*"))
        self.pushButton_MR.setText(_translate("MainWindow", "MR"))
        self.pushButton_7.setText(_translate("MainWindow", "7"))
        self.pushButton_1.setText(_translate("MainWindow", "1"))
        self.pushButton_2.setText(_translate("MainWindow", "2"))
        self.pushButton_3.setText(_translate("MainWindow", "3"))
        self.pushButton_add.setText(_translate("MainWindow", "+"))

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
  • 333
  • 334
  • 335
  • 336

PyCharm运行main.py得到计算器软件窗口

main.py

from PyQt5.QtWidgets import *
from 计算器ui import Ui_MainWindow

# QMainWindow:主窗口类
# Ui_MainWindow:自动生成py文件里的类
class MyMainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self,*args,**kwargs):
        super(MyMainWindow,self).__init__(*args,**kwargs)
        # Ui_MainWindow类里的方法:将ui构造出来
        self.setupUi(self)

if __name__ == "__main__":
    # QApplication实例是 PyQt5应用程序的主要对象
    app = QApplication([])
    # QMainWindow子类实例表示我们的窗口界面
    window = MyMainWindow()
    window.setWindowTitle("计算器")
    window.show()
    # 启动主循环,开始监测并响应用户输入和其他事件。
    app.exec_()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

在这里插入图片描述

信号与槽(Signals & Slots)机制

  1. 定义了一个自定义对象 MyObject,它包含一个整数参数的信号 my_signal 和一个槽函数 handle_signal
  2. 创建了 MyObject 的一个实例 obj
  3. 通过 obj.my_signal.connect(obj.handle_signal) 将信号 my_signal 连接到槽函数 handle_signal 上。这样,当信号被发射时,与之连接的槽函数会被自动调用。
  4. 使用 obj.my_signal.emit(42) 发射信号,并传递整数参数 42。结果就是输出 “Received signal: 42”。
from PyQt5.QtCore import pyqtSignal, QObject

# 定义一个自定义对象,包含一个信号和一个槽函数
class MyObject(QObject):
    # 定义一个带有一个整数参数的信号
    my_signal = pyqtSignal(int)

    def __init__(self):
        super().__init__()

    # 定义一个槽函数,用于接收信号并处理
    def handle_signal(self, data):
        print("Received signal:", data)

# 创建一个 MyObject 的实例
obj = MyObject()

# 连接信号与槽函数
obj.my_signal.connect(obj.handle_signal)

# 发射信号,槽函数会被调用
obj.my_signal.emit(42)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

输出结果:

Received signal: 42
  • 1

实现计算器功能

logic.py

from PyQt5 import QtWidgets

class CalState:
    READY = 0
    INPUT = 1

class CalLogic:
    def __init__(self, lcd_widget: QtWidgets.QLCDNumber):
        # lcd_widget : QLCDNumber 控件的变量名
        self.lcd_widget = lcd_widget
        # 计算器的状态:ready/input
        self.state = None
        # 存储计算器按下的健
        self.stack = None  # list

        self.last_operation = None
        # 存储当前的操作健
        self.current_operator = None
        # RE、M、MR相关
        self.memory = None

    def init_cal(self):
        """初始化计算器状态"""
        self.state = CalState.READY
        self.stack = [0]
        self.last_operation = None
        self.current_operator = None
        self._display()

    def _display(self):
        """计算器数字显示屏显示"""
        self.lcd_widget.display(self.stack[-1])

    def number_slot(self, num_val):
        """数字0到9显示的槽函数"""
        if self.state == CalState.READY:
            self.stack[-1] = num_val
            self.state = CalState.INPUT
        else:
            self.stack[-1] = self.stack[-1] * 10 + num_val
        self._display()

    def operation_slot(self, oper):
        """+-*/四个按键的槽函数"""
        self.current_operator = oper
        self.state = CalState.INPUT
        self.stack.append(0)  # 每按一次操作健就往stack列表中加入一个元素0

    def perc_slot(self):
        """实现1/100按键的槽函数"""
        self.stack[-1] *= 0.01
        self._display()
        self.state = CalState.INPUT

    def eq_slot(self):
        if self.current_operator:
            try:
                result = self._do_operator(self.stack[0], self.stack[1])
            except Exception:
                self.lcd_widget.display("error")
                self.state = [0]
                return
        self.stack = [result]
        self.current_operator = None
        self.state = CalState.READY
        self._display()     # 显示计算后的结果

    def _do_operator(self, operand1, operand2):
        """执⾏+-*/操作逻辑"""
        if self.current_operator == "+":
            result = operand1 + operand2
        elif self.current_operator == "-":
            result = operand1 - operand2
        elif self.current_operator == "*":
            result = operand1 * operand2
        else:
            result = operand1 / operand2
        return result

    def re_slot(self):
        self.init_cal()

    def m_slot(self):
        #lcd_widget.value()是PyQt5中QLCDNumber 控件的一个方法,用于获取该控件的当前值
        self.memory = self.lcd_widget.value()

    def mr_slot(self):
        self.stack[-1] = self.memory
        self.state = CalState.INPUT
        self._display()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90

main.py

from PyQt5.QtWidgets import *
from 计算器ui import Ui_MainWindow
from logic import CalLogic

# QMainWindow:主窗口类
# Ui_MainWindow:自动生成py文件里的类
class MyMainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self,*args,**kwargs):
        super(MyMainWindow,self).__init__(*args,**kwargs)
        # Ui_MainWindow类里的方法:将ui构造出来
        self.setupUi(self)
        self.cl:CalLogic = CalLogic(self.lcdNumber)
        self.do_signal_slot()
        self.cl.init_cal()

    def do_signal_slot(self):
        """给数字0到9按键建⽴clicked信号和槽函数"""
        self.pushButton_0.clicked.connect(lambda: self.cl.number_slot(0))
        self.pushButton_1.clicked.connect(lambda: self.cl.number_slot(1))
        self.pushButton_2.clicked.connect(lambda: self.cl.number_slot(2))
        self.pushButton_3.clicked.connect(lambda: self.cl.number_slot(3))
        self.pushButton_4.clicked.connect(lambda: self.cl.number_slot(4))
        self.pushButton_5.clicked.connect(lambda: self.cl.number_slot(5))
        self.pushButton_6.clicked.connect(lambda: self.cl.number_slot(6))
        self.pushButton_7.clicked.connect(lambda: self.cl.number_slot(7))
        self.pushButton_8.clicked.connect(lambda: self.cl.number_slot(8))
        self.pushButton_9.clicked.connect(lambda: self.cl.number_slot(9))

        """给+-*/按键建⽴clicked信号和槽函数"""
        self.pushButton_add.clicked.connect(lambda: self.cl.operation_slot("+"))
        self.pushButton_sub.clicked.connect(lambda: self.cl.operation_slot("-"))
        self.pushButton_mul.clicked.connect(lambda: self.cl.operation_slot("*"))
        self.pushButton_div.clicked.connect(lambda: self.cl.operation_slot("/"))

        """1/100按键建⽴clicked信号和槽函数"""
        self.pushButton_prec.clicked.connect(self.cl.perc_slot)

        """RE,M,MR按键建⽴clicked信号和槽函数"""
        self.pushButton_RE.clicked.connect(self.cl.re_slot)
        self.pushButton_M.clicked.connect(self.cl.m_slot)
        self.pushButton_MR.clicked.connect(self.cl.mr_slot)

        """=按键建⽴clicked信号和槽函数"""
        self.pushButton_eq.clicked.connect(self.cl.eq_slot)

if __name__ == "__main__":
    # QApplication实例是 PyQt5应用程序的主要对象
    app = QApplication([])
    # QMainWindow子类实例表示我们的窗口界面
    window = MyMainWindow()
    window.setWindowTitle("计算器")
    window.show()
    # 启动主循环,开始监测并响应用户输入和其他事件。
    app.exec_()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54

运行main.py
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/100648
推荐阅读
相关标签
  

闽ICP备14008679号