1.PyQt5程序基本框架

1.PyQt5程序基本框架

1.1开发环境

  • Python请读者自行安装Python3.7以上;
  • Qt使用Qt Creator
  • PyQt5pip3 install PyQt5
  • PyCharm开发工具,请自行安装;
  • 1.2PyQt5 GUI程序开发基本步骤

    1.使用Qt Creator可视化设计窗体

    2.将设计好的窗体文件(.ui文件)转换为python文件(pyuic5)

    3.使用转换后的Python文件构建GUI应用程序

    示例:Hello world

    第1步:使用PyCharm创建项目qt0101

    第2步:使用QtCreator设计如下窗体并将文件保存为hello_form.ui,保存位置为项目文件夹,其中窗体及组件的主要属性如下:

    objectName

    类名称

    属性设置

    备注

    helloForm

    QWidget

    windowTitle=”Demo0101″

    设置窗体的标题栏文字

    helloLabel

    QLable

    text=“Hello world”

    设置标签的显示文本及字体

    font.PointSize=16

    font.bold=True

    效果如下:

    第3步:将.ui文件编译为python文件

    pyuic5 -o ui_helloform.py hello_form.ui

    ui_helloform.py文件中定义了一个类Ui_helloForm,其中包含一个setupUi()方法用于设置界面。

    第4步:编写主程序,显示界面。

    # coding: utf-8import sysfrom PyQt5.QtWidgets import QWidget, QApplicationfrom ui_helloform import Ui_helloFormclass QHelloWidget(QWidget):    def __init__(self, parent=None):        super().__init__(parent)        self.__ui = Ui_helloForm()        self.__ui.setupUi(self)        if __name__ == '__main__':    app = QApplication(sys.argv)    helloWidget = QHelloWidget()    helloWidget.show()    sys.exit(app.exec_())

    代码分析:

    1.窗体类QHelloWidget只有一个基类QWidget,其构造函数中,首先调用父类的构造函数,然后显示创建Ui_helloForm类的私有属性self.__ui。

    2.通过调用Ui_helloForm的setupUi方法将QHelloWidget实例作为完整的窗体。

    3.在主程序中,通过QApplication创建应用,然后实例化QHelloWidget并显示,最后,运行应用程序。

    声明:本站部分文章及图片源自用户投稿,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!

    上一篇 2022年1月4日
    下一篇 2022年1月4日

    相关推荐