PyQt5 + QtDesigner 复刻 Windows 计算器 (一)

目的

尝试用 PyQt5 以及 QtDesigner 复刻一个 Windows 计算器,加强对 PyQt5 的学习与理解。

目标

尽可能还原 Win11 自带计算器,计划实现 以及 两种功能。

PyQt5 + QtDesigner 复刻 Windows 计算器 (一)_第1张图片 PyQt5 + QtDesigner 复刻 Windows 计算器 (一)_第2张图片

环境搭建

安装 PyQt5以及 QtDesigner

# 使用清华镜像源
pip install PyQt5 -i https://pypi.tuna.tsinghua.edu.cn/simple

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

检查是否安装成功:

 运行 QtDesigner。可以在路径下双击 designer.exe 打开,或者在 terminal 中直接通过命令行打开

# python Script 文件夹需要添加到环境变量 PATH 中
designer.exe

 QtDesigner 可以正常打开

PyQt5 + QtDesigner 复刻 Windows 计算器 (一)_第3张图片

 创建一个可以运行的空窗口

QtDesigner 新建 UI

打开界面后选择 Main Window 并创建文件,然后 Ctrl+S 保存 UI 文件为 calculator.ui

PyQt5 + QtDesigner 复刻 Windows 计算器 (一)_第4张图片

 将 UI 文件生成为对应的 python 文件

这里仿照 QtCreator 的风格,将 UI 文件生成为 python 文件,这样方便之后 coding 的时候 IDE 索引窗口中的组件。

在 terminal 中进入工程目录,然后通过 pyuic5 生成 窗口对应 python class

# 假设工程目录为 C:\your\path\to\ui\file

cd C:\your\path\to\ui\file

pyuic5.exe -o ui_calculator.py calculator.ui

本机示例:

 检查 ui_calculator.py 是否生成

PyQt5 + QtDesigner 复刻 Windows 计算器 (一)_第5张图片

创建 calcMain.py 加载并运行空窗口

from PyQt5 import QtWidgets
from ui_calculator import Ui_MainWindow
import sys

class calcMainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        # init UI
        QtWidgets.QMainWindow.__init__(self)
        self.setupUi(self)



if __name__ == '__main__':
    # launch the window
    app = QtWidgets.QApplication(sys.argv)
    win = calcMainWindow()
    win.show()
    sys.exit(app.exec_())
python ./calcMain.py

运行结果:

PyQt5 + QtDesigner 复刻 Windows 计算器 (一)_第6张图片

 下一篇计划开始复刻 Standard 版计算器

你可能感兴趣的:(PyQt5,学习笔记,qt,python,开发语言)