zoukankan      html  css  js  c++  java
  • <pyqt5>学习pyqt5

    01.安装

    安装pyqt5(利用豆瓣镜像)

    pip install pyqt5 -i https://pypi.douban.com/simple

    安装pyqt5-tools(利用豆瓣镜像)

    pip3 install pyqt5-tools -i https://pypi.douban.com/simple 

    02.在pycharm中添加成外部工具

    添加QtDesigner

    file-->settings-->Tools-->External Tools-->(点加号)

    Name:QtDesigner

    Program:   E:softwareAnacondaLibsite-packagespyqt5_toolsQtindesigner.exe

    Arguments:  $FileDir$$FileName$ 

    working directory:$FileDir$   

    添加pyuic5,这个是把qt的UI文件转换成.py文件的工具

    再来一次

    Name:pyuic5

    Program:   E:softwareAnacondaScriptspyuic5.exe

    Arguments:  $FileName$ -o $FileNameWithoutExtension$.py 

    working directory:$FileDir$ 

    添加pyrcc的参数,这个是将资源文件如图片等转成python代码能识别的文件,这个参数基本和pyuic5的是一样的

    Name:pyrcc

    Program:   E:softwareAnacondaScriptspyrcc5.exe

    Arguments:  $FileName$ -o $FileNameWithoutExtension$.py 

    working directory:$FileDir$ 

    汉化

    https://pan.baidu.com/s/13yPGR1Gu4yOXuTyraFwZKw   提取码:0b12 

    将汉化文件放入:E:softwareAnacondaLibsite-packagesPyQt5Qt ranslations

    将汉化文件放入:E:softwareAnacondaLibsite-packagespyqt5_toolsQt ranslations

    添加系统变量

    变量名:QT_QPA_PLATFORM_PLUGIN_PATH

    变量值(以你的安装地址为准)E:softwareAnacondaLibsite-packagespyqt5_toolsQtplugins

    03.认识PyQt5

    • Qt是Trolltech开发的一个C++GUI应用程序,具备很强的跨平台特效,能够在Windows.linux,OS之间轻松移植
    • PyQt是一个用于创建图形化界面(GUI)应用程序的跨平台工具包,Python+Qt库
    • 特点
      • 基于高性能的Qt的控件集
      • 能够跨平台
      • 对Qt库的完全封装
      • 可以使用Qt成熟的IDE进行图形界面设计,并自动生成可执行python代码
      • 提供一整套种类繁多的窗口控件
    • 第一个代码:测试安装成功PyQt
      • import sys
        from PyQt5 import QtWidgets
        
        '''
        【简介】第一个PyQt例子  
        '''
        
        app = QtWidgets.QApplication(sys.argv)
        widget = QtWidgets.QWidget()
        widget.resize(360, 360)
        widget.setWindowTitle("hello, pyqt5")
        widget.show()
        sys.exit(app.exec_())  
      • 运行效果
      • 获取使用手册

        • # -*- coding: utf-8 -*- 
          '''
          【简介】保存PyQt5类的使用手册到本地
          '''
          
          import sys
          
          from PyQt5.QtWidgets import QWidget
          
          out = sys.stdout
          sys.stdout = open(r'QWidget.txt', 'w')
          help(QWidget)
          sys.stdout.close()
          sys.stdout = out
          

    04.Qt Designer的使用 

    ui的制作一般可以通过UI制作工具和纯代码两种方式来实现  

    • Qt Designer(Qt设计师):强大的可视化GUI设计工具,可以加快开发PyQt程序的速度
      • 结果:生成后缀.ui的文件(可以转化成.py格式的文件) 
      • MVC(模型-视图-控制器)设计模式,做到了显示和业务逻辑的分离
      • 优点
        • 使用简单
        • 转换python文件方便.ui文件其实就是XML格式的文本文件
      • 新建主窗口
        • 最常用:Widget(通用窗口)和Main Window(主窗口) 
        • 1.选择Main Window(主窗口)
          • 工具箱:常用的按钮、单选框、文本框等
          • 主窗口:
          • 对象查看器:主窗口中放置的对象列表
          • 属性编辑器:提供了对窗口、控件、布局的属性编辑功能
          • 信号/槽编辑器、动作编辑器和资源浏览器
      • Qt Designer打开一个ui文件
        • 用文本编辑器打开
          • <?xml version="1.0" encoding="UTF-8"?>
            <ui version="4.0">
             <class>MainWindow</class>
             <widget class="QMainWindow" name="MainWindow">
              <property name="geometry">
               <rect>
                <x>0</x>
                <y>0</y>
                <width>726</width>
                <height>592</height>
               </rect>
              </property>
              <property name="windowTitle">
               <string>MainWindow</string>
              </property>
              <widget class="QWidget" name="centralwidget">
               <widget class="QPushButton" name="pushButton">
                <property name="geometry">
                 <rect>
                  <x>490</x>
                  <y>110</y>
                  <width>93</width>
                  <height>28</height>
                 </rect>
                </property>
                <property name="text">
                 <string>按钮</string>
                </property>
               </widget>
              </widget>
              <widget class="QMenuBar" name="menubar">
               <property name="geometry">
                <rect>
                 <x>0</x>
                 <y>0</y>
                 <width>726</width>
                 <height>26</height>
                </rect>
               </property>
              </widget>
              <widget class="QStatusBar" name="statusbar"/>
             </widget>
             <resources/>
             <connections/>
            </ui>
      • 将UI文件转换成py文件

        • # -*- coding: utf-8 -*-
          
          '''
              【简介】ui转换成py的转换工具
          '''
          
          import os
          import os.path
          
          # UI文件所在的路径 
          dir = 'D:PyQtFile'
          
          
          # 列出目录下的所有ui文件
          def listUiFile():
              list = []
              files = os.listdir(dir)
              for filename in files:
                  # print( dir + os.sep + f  )
                  # print(filename)
                  if os.path.splitext(filename)[1] == '.ui':
                      list.append(filename)
          
              return list
          
          
          # 把后缀为ui的文件改成后缀为py的文件名
          def transPyFile(filename):
              return os.path.splitext(filename)[0] + '.py'
          
          
          # 调用系统命令把ui转换成py
          def runMain():
              list = listUiFile()
              for uifile in list:
                  pyfile = transPyFile(uifile)
                  cmd = 'pyuic5 -o {pyfile} {uifile}'.format(pyfile=pyfile, uifile=uifile)
                  # print(cmd)
                  os.system(cmd)
          
          
          ###### 程序的主入口
          if __name__ == "__main__":
              runMain()
      • 生成的py文件  firstMainWin.py

        • # -*- coding: utf-8 -*-
          
          # Form implementation generated from reading ui file 'firstMainWin.ui'
          #
          # Created by: PyQt5 UI code generator 5.15.0
          #
          # 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(726, 592)
                  self.centralwidget = QtWidgets.QWidget(MainWindow)
                  self.centralwidget.setObjectName("centralwidget")
                  self.pushButton = QtWidgets.QPushButton(self.centralwidget)
                  self.pushButton.setGeometry(QtCore.QRect(490, 110, 93, 28))
                  self.pushButton.setObjectName("pushButton")
                  MainWindow.setCentralWidget(self.centralwidget)
                  self.menubar = QtWidgets.QMenuBar(MainWindow)
                  self.menubar.setGeometry(QtCore.QRect(0, 0, 726, 26))
                  self.menubar.setObjectName("menubar")
                  MainWindow.setMenuBar(self.menubar)
                  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.setText(_translate("MainWindow", "按钮"))  
        • 增加运行部分,就可以重现原本的UI文件

          • if __name__ == "__main__":
                import sys
                app = QtWidgets.QApplication(sys.argv)
                MainWindow = QtWidgets.QMainWindow()
                ui = Ui_MainWindow()
                ui.setupUi(MainWindow)
                MainWindow.show()
                sys.exit(app.exec_())
        • .UI文件编译而来的.py文件称为界面文件.由于界面文件每次编译时都会初始化,所以需要新建一个PY文件调用界面文件,这个PY文件叫逻辑文件(业务文件)

          • 总结:界面文件和调用界面的逻辑文件分开,即显示也业务逻辑分离 

          • 逻辑文件  CallFirstMainWin.py

            • # -*- coding: utf-8 -*-
              
              import sys
              from PyQt5.QtWidgets import QApplication, QMainWindow
              from firstMainWin import *
              
              
              class MyMainWindow(QMainWindow, Ui_MainWindow):
                  def __init__(self, parent=None):
                      super(MyMainWindow, self).__init__(parent)
                      self.setupUi(self)
              
              
              if __name__ == "__main__":
                  app = QApplication(sys.argv)
                  myWin = MyMainWindow()
                  myWin.show()
                  sys.exit(app.exec_())
          • 以后更新界面,只需要UI文件进行更新,然后编译成py文件,逻辑文件一般不需要调整.     

      • 布局管理入门

        • 布局

          • Vertical Layout:垂直布局(控件默认从上到下添加) 

          • Horizontal Layout:水平布局(控件默认从左到右添加)

          • Grid Layout:栅格布局(将控件放入一个网格,每个单元合理划分控件)          

          • Form Layout:表单布局(控件以两列形式布局在表单中,左边包含标签,右列包含输入控件)

        • 小例子

          • 放入:文本框(lineEdit)和按钮(pushButton),选中这2个控件,然后指定该控件布局为水平布局          

            • 转换成PY文件为

              • # -*- coding: utf-8 -*-
                
                from PyQt5 import QtCore, QtGui, QtWidgets
                
                
                class Ui_MainWindow(object):
                    def setupUi(self, MainWindow):
                        MainWindow.setObjectName("MainWindow")
                        MainWindow.resize(800, 600)
                        self.centralwidget = QtWidgets.QWidget(MainWindow)
                        self.centralwidget.setObjectName("centralwidget")
                        self.widget = QtWidgets.QWidget(self.centralwidget)
                        self.widget.setGeometry(QtCore.QRect(180, 70, 216, 25))
                        self.widget.setObjectName("widget")
                        self.horizontalLayout = QtWidgets.QHBoxLayout(self.widget)
                        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
                        self.horizontalLayout.setObjectName("horizontalLayout")
                        self.lineEdit = QtWidgets.QLineEdit(self.widget)
                        self.lineEdit.setObjectName("lineEdit")
                        self.horizontalLayout.addWidget(self.lineEdit)
                        self.pushButton = QtWidgets.QPushButton(self.widget)
                        self.pushButton.setObjectName("pushButton")
                        self.horizontalLayout.addWidget(self.pushButton)
                        MainWindow.setCentralWidget(self.centralwidget)
                        self.menubar = QtWidgets.QMenuBar(MainWindow)
                        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))
                        self.menubar.setObjectName("menubar")
                        MainWindow.setMenuBar(self.menubar)
                        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.setText(_translate("MainWindow", "PushButton"))
          • 四种布局(步骤:Form -->控件--->右键--->选择布局)

            •          

      • 属性编辑器

        • geometry:绝对坐标和控件大小

          • X:距离主窗口左侧140px
          • Y:距离主窗口上侧10px
          • 控件宽度264px
          • height:控件高度23px  
        • sizePolicy:

          • Horizontal Policy:水平策略
          • Vertical Policy:垂直策略
          • Horizontal Stretch:水平伸展 
          • Vertical Stretch:垂直伸展 
        • minimumSize:设置控件在布局管理器中的最小尺寸  

        • maximumSize::设置控件在布局管理器中的最大尺寸

      • QT Designer布局的顺序

        1. 将一个窗口控件拖入窗口中并放置在大致正确的位置上,除了容器(container)窗口,一般不需要调整窗口尺寸

        2. 对于要用代码引用的窗口控件,应该指定一个名字;对需要微调的窗口控件,可以设置其对应的属性

        3. 重复步骤1.2,直到所需要的全部窗口控件都放到了窗口中.

        4. 如有需要,在窗口控件之间可以用Vertical Spacer,Horizontal spacer,Horizontal Line,Vertical Line隔开

        5. 选择需要布局的窗口控件,使用布局管理器或切分窗口(splitter)对它们布局

        6. 重复步骤5,直到所有的窗口控件和分隔符都布局好为止

        7. 点击窗口,并使用布局管理器对其进行布局

        8. 为窗口的标签设置伙伴关系  

        9. 如果按键次序有问题,则需要设置窗口的Tab键次序

        10. 在适当的地方为内置的信号和槽建立信号与槽连接

        11. 预览窗口,并检查所有的内容能否按照设想进行工作

        12. 设置窗口的对象名(在类中会用到这么名字),窗口的标题并进行保存.

        13. 使用编译器编译窗口,然后根据需要生成对话框代码

        14. 进行正常代码编写工作,即编写业务逻辑文件

    • Qt Designer实战应用

      • 1.新建主窗口(Main Window),然后拖入Push Button放入窗口,并重命名为"开始".

      • 2.添加Label控件,并从Input Widgets栏找到Double Spin Box控件,如图所示

        •    

      • 3.然后对Label和doubleSpinBox控件重命名,对DoubleSpinBox控件,依次命名为

        • doubleSpinBox_returns_min、doubleSpinBox_returns_max

        • doubleSpinBox_maxdrawdown_min、doubleSpinBox_maxdrawdown_max

        • doubleSpinBox_sharp_min、doubleSpinBox_sharp_max 

        •   

      • 4.左侧4个标签(垂直布局)、中间8个标签(网格布局) 

        •   

      • 5.水平布局

        • 从Spacers栏分别将Horizontal Spacer和Vertical Spacer窗口控件

        •   

        • 然后全部选中,设定为水平布局

        •    

        • 单击horizontalSpacer更改sizeType属性为preferred,更改sizeHint宽度为200,单击窗体-->预览

        •   

      • 6.开始按钮设定最小尺寸100*100,最大尺寸300*300, 将受益,最大回撤,sharp比这三个标签垂直伸展分别为1,3,1(放缩比例) 

      • 7.使用布局管理器对窗口进行布局,点击窗体空白处--->右键--->布局--->水平布局

        •       

        • 只是看看操作,撤销

      • 8.设置伙伴关系               

        • 将"sharp比"标签重命名为"&sharp比",然后点击菜单Edit--->编辑伙伴(edit buddies),用鼠标左键按住"sharp比"标签,向右拉动到"doubleSpinBox_sharp_min"
        • 预览快捷键(Ctrl+R) ,预览后按Alt+S快捷键会自动定位在 
      • 9.设定Tab键次序
        • Edit--->Edit Tab order(点击数字就可以设定次序)  
      • 10.测试代码
        • 同路径下layout_demo_LayoutManage.py
          • # -*- coding: utf-8 -*-
            
            """
            Module implementing LayoutDemo.
            """
            
            from PyQt5.QtCore import pyqtSlot
            from PyQt5.QtWidgets import QMainWindow, QApplication
            
            from test_002 import Ui_MainWindow
            
            
            class LayoutDemo(QMainWindow, Ui_MainWindow):
                """
                Class documentation goes here.
                """
            
                def __init__(self, parent=None):
                    """
                    Constructor
                    
                    @param parent reference to the parent widget
                    @type QWidget
                    """
                    super(LayoutDemo, self).__init__(parent)
                    self.setupUi(self)
            
                @pyqtSlot()
                def on_pushButton_clicked(self):
                    """
                    Slot documentation goes here.
                    """
                    print('收益_min:', self.doubleSpinBox_returns_min.text())
                    print('收益_max:', self.doubleSpinBox_returns_max.text())
                    print('最大回撤_min:', self.doubleSpinBox_maxdrawdown_min.text())
                    print('最大回撤_max:', self.doubleSpinBox_maxdrawdown_max.text())
                    print('sharp比_min:', self.doubleSpinBox_sharp_min.text())
                    print('sharp比_max:', self.doubleSpinBox_sharp_max.text())
            
            
            if __name__ == "__main__":
                import sys
            
                app = QApplication(sys.argv)
                ui = LayoutDemo()
                ui.show()
                sys.exit(app.exec_())  
          • 运行结果
            •   
      • 11.信号和槽关联
        • 创建事件循环后,通过建立信号和槽的连接就可以实现对象之间的通信.
        • Qt信号槽:对鼠标和键盘在界面上的操作进行响应处理
        • 绑定控件发射的信号指定对应的处理槽函数
          • 1.在窗口UI设计中添加信号和槽
          • 2.通过代码连接信号和槽
          • 3.通过eric中生成对话框代码功能产生信号和槽(书上写的,没试验) 
        • 简单入门
          • 功能1:单击关闭按钮,关闭窗口  
            • 建立主窗口--->创建一个关闭窗口按钮,将objectName属性改为"closeWinBtn" 
            • edit-->编辑信号/槽,按住鼠标左键,拖到接受者(Form窗口),这样就建立起了连接  
            • 选择clicked()信号,选择Form槽函数选择close()----->单击发射clicked信号就会被窗体的槽函数close()捕捉到,并触发close()函数
            •      
            • 生成py代码
            • # -*- coding: utf-8 -*-
              
              # Form implementation generated from reading ui file 'test_003.ui'
              #
              # Created by: PyQt5 UI code generator 5.15.0
              #
              # 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(800, 600)
                      self.centralwidget = QtWidgets.QWidget(MainWindow)
                      self.centralwidget.setObjectName("centralwidget")
                      self.closeWinBtn = QtWidgets.QPushButton(self.centralwidget)
                      self.closeWinBtn.setGeometry(QtCore.QRect(280, 180, 75, 23))
                      self.closeWinBtn.setObjectName("closeWinBtn")
                      MainWindow.setCentralWidget(self.centralwidget)
                      self.menubar = QtWidgets.QMenuBar(MainWindow)
                      self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))
                      self.menubar.setObjectName("menubar")
                      MainWindow.setMenuBar(self.menubar)
                      self.statusbar = QtWidgets.QStatusBar(MainWindow)
                      self.statusbar.setObjectName("statusbar")
                      MainWindow.setStatusBar(self.statusbar)
              
                      self.retranslateUi(MainWindow)
                      self.closeWinBtn.clicked.connect(MainWindow.close)
                      QtCore.QMetaObject.connectSlotsByName(MainWindow)
              
                  def retranslateUi(self, MainWindow):
                      _translate = QtCore.QCoreApplication.translate
                      MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
                      self.closeWinBtn.setText(_translate("MainWindow", "关闭窗口"))  
            • 通过前面逻辑文件运行,可以实现点击关闭窗体的功能
        • 快速进阶
          • PyQt默认有哪些信号和槽?
            • 1.用上面的方法,选择
            • 2.使用右下角的信号与槽编辑窗口来进行调整
              •     
          • 如何使用这些信号和槽. 
            • 将UI文件编译成PY文件然后找到相应的使用方法编辑py文件  
      • 常用控件
        • (1)显示控件
          • Lable:文本标签,显示文本,可以用来标记控件
          • Text Browser:显示文本控件.用来后台命令执行结果显示.
        • (2)输入控件,提供与用户输入交互
          • Line Edit:单行文本框,输入单行字符串.控件对象常用函数为Text()返回文本框内容,用于获取输入.setText()用于设置文本框显示.
          • Text Edit:多行文本框,输入多行字符串.控件对象常用函数同Line Edit控件
          • Combo Box:下拉框列表.用于输入指定枚举值.
        • (3)控件按钮,供用户选择与执行
          • Push Button:命令按钮,常见的确认、取消、关闭等按钮就是这个控件.clicked信号一定要记住.
          • Radio Button:单选框按钮
          • Check Box:多选框按钮.   
      • 应用:登录界面

        • Step1:打开主页面,选择Widget模板

          •          

        • Step2:从Widget Box工具箱中拖拽2个label、2个line Edit、2个Push Buttond以及1个Text Browser.拖拽后如下:
        • Step3:双击各个控件,修改控件名称以及对象名称.对象名称一定要记得修改.默认生成的label_1、label_2这种名称无法直接判断到底是对应哪个控件.

          •    
          • 点击菜单栏Form-Prview.预览界面效果(Ctrl + R)

            • 保存为login.ui

              • <?xml version="1.0" encoding="UTF-8"?>
                <ui version="4.0">
                 <class>Form</class>
                 <widget class="QWidget" name="Form">
                  <property name="geometry">
                   <rect>
                    <x>0</x>
                    <y>0</y>
                    <width>514</width>
                    <height>172</height>
                   </rect>
                  </property>
                  <property name="windowTitle">
                   <string>Form</string>
                  </property>
                  <widget class="QLineEdit" name="user_lineEdit">
                   <property name="geometry">
                    <rect>
                     <x>130</x>
                     <y>20</y>
                     <width>113</width>
                     <height>20</height>
                    </rect>
                   </property>
                  </widget>
                  <widget class="QLineEdit" name="pwd_lineEdit">
                   <property name="geometry">
                    <rect>
                     <x>130</x>
                     <y>50</y>
                     <width>113</width>
                     <height>20</height>
                    </rect>
                   </property>
                  </widget>
                  <widget class="QLabel" name="userlabel">
                   <property name="geometry">
                    <rect>
                     <x>40</x>
                     <y>20</y>
                     <width>54</width>
                     <height>12</height>
                    </rect>
                   </property>
                   <property name="text">
                    <string>用户名</string>
                   </property>
                  </widget>
                  <widget class="QLabel" name="pwd_label">
                   <property name="geometry">
                    <rect>
                     <x>40</x>
                     <y>60</y>
                     <width>54</width>
                     <height>12</height>
                    </rect>
                   </property>
                   <property name="text">
                    <string>密码</string>
                   </property>
                  </widget>
                  <widget class="QPushButton" name="login_Button">
                   <property name="geometry">
                    <rect>
                     <x>40</x>
                     <y>90</y>
                     <width>75</width>
                     <height>23</height>
                    </rect>
                   </property>
                   <property name="text">
                    <string>登录</string>
                   </property>
                  </widget>
                  <widget class="QPushButton" name="cancel_Button">
                   <property name="geometry">
                    <rect>
                     <x>160</x>
                     <y>90</y>
                     <width>75</width>
                     <height>23</height>
                    </rect>
                   </property>
                   <property name="text">
                    <string>退出</string>
                   </property>
                  </widget>
                  <widget class="QTextBrowser" name="user_textBrowser">
                   <property name="geometry">
                    <rect>
                     <x>260</x>
                     <y>10</y>
                     <width>256</width>
                     <height>101</height>
                    </rect>
                   </property>
                  </widget>
                 </widget>
                 <resources/>
                 <connections/>
                </ui>  
            • 转化成login.py文件

              • # -*- coding: utf-8 -*-
                
                
                from PyQt5 import QtCore, QtGui, QtWidgets
                
                
                class Ui_Form(object):
                    def setupUi(self, Form):
                        Form.setObjectName("Form")
                        Form.resize(514, 172)
                        self.user_lineEdit = QtWidgets.QLineEdit(Form)
                        self.user_lineEdit.setGeometry(QtCore.QRect(130, 20, 113, 20))
                        self.user_lineEdit.setObjectName("user_lineEdit")
                        self.pwd_lineEdit = QtWidgets.QLineEdit(Form)
                        self.pwd_lineEdit.setGeometry(QtCore.QRect(130, 50, 113, 20))
                        self.pwd_lineEdit.setObjectName("pwd_lineEdit")
                        self.userlabel = QtWidgets.QLabel(Form)
                        self.userlabel.setGeometry(QtCore.QRect(40, 20, 54, 12))
                        self.userlabel.setObjectName("userlabel")
                        self.pwd_label = QtWidgets.QLabel(Form)
                        self.pwd_label.setGeometry(QtCore.QRect(40, 60, 54, 12))
                        self.pwd_label.setObjectName("pwd_label")
                        self.login_Button = QtWidgets.QPushButton(Form)
                        self.login_Button.setGeometry(QtCore.QRect(40, 90, 75, 23))
                        self.login_Button.setObjectName("login_Button")
                        self.cancel_Button = QtWidgets.QPushButton(Form)
                        self.cancel_Button.setGeometry(QtCore.QRect(160, 90, 75, 23))
                        self.cancel_Button.setObjectName("cancel_Button")
                        self.user_textBrowser = QtWidgets.QTextBrowser(Form)
                        self.user_textBrowser.setGeometry(QtCore.QRect(260, 10, 256, 101))
                        self.user_textBrowser.setObjectName("user_textBrowser")
                
                        self.retranslateUi(Form)
                        QtCore.QMetaObject.connectSlotsByName(Form)
                
                    def retranslateUi(self, Form):
                        _translate = QtCore.QCoreApplication.translate
                        Form.setWindowTitle(_translate("Form", "Form"))
                        self.userlabel.setText(_translate("Form", "用户名"))
                        self.pwd_label.setText(_translate("Form", "密码"))
                        self.login_Button.setText(_translate("Form", "登录"))
                        self.cancel_Button.setText(_translate("Form", "退出"))  
              • 界面与业务逻辑分离实现

                • 这一步主要实现业务逻辑,也就是点击登录和退出按钮后程序要执行的操作。为了后续维护方便,采用界面与业务逻辑相分离来实现。也就是通过创建主程序调用界面文件方式实现。这有2个好处。第1就是实现逻辑清晰。第2就是后续如果界面或者逻辑需要变更,好维护。新建call_login.py文件程序,调用login.py文件。

                • # -*- coding: utf-8 -*-
                  
                  # 导入程序运行必须模块
                  import sys
                  # PyQt5中使用的基本控件都在PyQt5.QtWidgets模块中
                  from PyQt5.QtWidgets import QApplication, QMainWindow
                  # 导入designer工具生成的login模块
                  from login import Ui_Form
                  
                  
                  class MyMainForm(QMainWindow, Ui_Form):
                      def __init__(self, parent=None):
                          super(MyMainForm, self).__init__(parent)
                          self.setupUi(self)
                  
                  
                  if __name__ == "__main__":
                      # 固定的,PyQt5程序都需要QApplication对象。sys.argv是命令行参数列表,确保程序可以双击运行
                      app = QApplication(sys.argv)
                      # 初始化
                      myWin = MyMainForm()
                      # 将窗口控件显示在屏幕上
                      myWin.show()
                      # 程序运行,sys.exit方法确保程序完整退出。
                      sys.exit(app.exec_())
                • 运行此文件,就可以显示预览文件

        • Step4:添加信号和槽,实现业务逻辑

          • 代码实现逻辑

            • # -*- coding: utf-8 -*-
              
              
              # 导入程序运行必须模块
              import sys
              # PyQt5中使用的基本控件都在PyQt5.QtWidgets模块中
              from PyQt5.QtWidgets import QApplication, QMainWindow
              # 导入designer工具生成的login模块
              from login import Ui_Form
              
              
              class MyMainForm(QMainWindow, Ui_Form):
                  def __init__(self, parent=None):
                      super(MyMainForm, self).__init__(parent)
                      self.setupUi(self)
                      # 添加登录按钮信号和槽。注意display函数不加小括号()
                      self.login_Button.clicked.connect(self.display)
                      # 添加退出按钮信号和槽。调用close函数
                      self.cancel_Button.clicked.connect(self.close)
              
                  def display(self):
                      # 利用line Edit控件对象text()函数获取界面输入
                      username = self.user_lineEdit.text()
                      password = self.pwd_lineEdit.text()
                      # 利用text Browser控件对象setText()函数设置界面显示
                      self.user_textBrowser.setText("登录成功!
              " + "用户名是: " + username + ",密码是: " + password)
              
              
              if __name__ == "__main__":
                  # 固定的,PyQt5程序都需要QApplication对象。sys.argv是命令行参数列表,确保程序可以双击运行
                  app = QApplication(sys.argv)
                  # 初始化
                  myWin = MyMainForm()
                  # 将窗口控件显示在屏幕上
                  myWin.show()
                  # 程序运行,sys.exit方法确保程序完整退出。
                  sys.exit(app.exec_())
          • 效果

          • 在Qt Designer中实现信号和槽

        • Step5:解决拖动界面会变形的问题

          • 1.界面点击使用网格布局

            • 可以左边用网格布局,左右在用水平布局,布局完的可以 

          • 反过来,界面随着拉伸变化

            • 效果  

              •    

            • 预览效果

            • 还可以设定修改主界面最大属性中的长宽设定成最小属性一致.                    

              •                                  

        • Setp6:打包成exe文件
          • pyinstaller.exe -F call_login.py -w  
          • 运行效果

    • 总结步骤

      • 1.打开主页面,选择Widget模板

      • 2.从Widget Box工具箱中拖拽各种控件,如:label、line Edit、Push Buttond、Text Browser等

      • 3.双击各个控件,修改控件名称以及对象名称.对象名称一定要记得修改.默认生成的label_1、label_2这种名称无法直接判断到底是对应哪个控件.  

      • 4.生成相应的界面PY文件与业务逻辑PY文件

      • 5.添加信号和槽,实现业务逻辑(可以在设计的时候实现,也可以转化成PY文件后用代码实现)

      • 6.解决拖动界面会变形的问题

      • 7.打包成exe文件      

             
    • 点击+号 Sender控件选择"login_Button"、Signal信号选择"clicked",Receiver选择"Form",内置槽函数选择"showMsg()" 也可以实现同样的效果
    • PyQt5基本控件使用:单选按钮,复选框,下拉框,文本框
      • 复选框
        • # -*- coding: utf-8 -*-
          
          import sys
          from PyQt5 import QtCore, QtGui, QtWidgets
          from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox, QCheckBox
          
          
          class Ui_Form(object):
              def setupUi(self, Form):
                  Form.setObjectName("Form")
                  Form.resize(380, 154)
                  self.freshcheckBox = QtWidgets.QCheckBox(Form)
                  self.freshcheckBox.setGeometry(QtCore.QRect(50, 40, 71, 31))
                  font = QtGui.QFont()
                  font.setPointSize(14)
                  self.freshcheckBox.setFont(font)
                  self.freshcheckBox.setObjectName("freshcheckBox")
                  self.bearcheckBox = QtWidgets.QCheckBox(Form)
                  self.bearcheckBox.setGeometry(QtCore.QRect(140, 40, 71, 31))
                  font = QtGui.QFont()
                  font.setPointSize(14)
                  self.bearcheckBox.setFont(font)
                  self.bearcheckBox.setObjectName("bearcheckBox")
                  self.okButton = QtWidgets.QPushButton(Form)
                  self.okButton.setGeometry(QtCore.QRect(230, 40, 71, 31))
                  font = QtGui.QFont()
                  font.setPointSize(14)
                  self.okButton.setFont(font)
                  self.okButton.setObjectName("okButton")
          
                  self.retranslateUi(Form)
                  QtCore.QMetaObject.connectSlotsByName(Form)
          
              def retranslateUi(self, Form):
                  _translate = QtCore.QCoreApplication.translate
                  Form.setWindowTitle(_translate("Form", "CheckBox例子"))
                  self.freshcheckBox.setText(_translate("Form", "鱼"))
                  self.bearcheckBox.setText(_translate("Form", "熊掌"))
                  self.okButton.setText(_translate("Form", "确定"))
          
          
          class MyMainForm(QMainWindow, Ui_Form):
              def __init__(self, parent=None):
                  super(MyMainForm, self).__init__(parent)
                  self.setupUi(self)
                  self.okButton.clicked.connect(self.checkCheckBox)
          
              def checkCheckBox(self):
                  if self.freshcheckBox.isChecked() and self.bearcheckBox.isChecked():
                      QMessageBox.information(self, "消息框标题", "鱼和熊掌我要兼得!", QMessageBox.Yes | QMessageBox.No)
          
          
          
          if __name__ == "__main__":
              app = QApplication(sys.argv)
              myWin = MyMainForm()
              myWin.show()
              sys.exit(app.exec_())  
        • self.radioButton.isChecked()  --> 用于判断RadioButton控件是否被选中。返回值Trule表示按钮被选中,False表示按钮未选中。

      • 单选框

        • # -*- coding: utf-8 -*-
          
          import sys
          from PyQt5 import QtCore, QtGui, QtWidgets
          from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox, QRadioButton
          
          
          class Ui_Form(object):
              def setupUi(self, Form):
                  Form.setObjectName("Form")
                  Form.resize(309, 126)
                  self.radioButton = QtWidgets.QRadioButton(Form)
                  self.radioButton.setGeometry(QtCore.QRect(70, 40, 89, 16))
                  self.radioButton.setObjectName("radioButton")
                  self.okButton = QtWidgets.QPushButton(Form)
                  self.okButton.setGeometry(QtCore.QRect(70, 70, 75, 23))
                  self.okButton.setObjectName("okButton")
          
                  self.retranslateUi(Form)
                  QtCore.QMetaObject.connectSlotsByName(Form)
          
              def retranslateUi(self, Form):
                  _translate = QtCore.QCoreApplication.translate
                  Form.setWindowTitle(_translate("Form", "RadioButton单选按钮例子"))
                  self.radioButton.setText(_translate("Form", "单选按钮"))
                  self.okButton.setText(_translate("Form", "确定"))
          
          
          class MyMainForm(QMainWindow, Ui_Form):
              def __init__(self, parent=None):
                  super(MyMainForm, self).__init__(parent)
                  self.setupUi(self)
                  self.okButton.clicked.connect(self.checkRadioButton)
          
              def checkRadioButton(self):
                  if self.radioButton.isChecked():
                      QMessageBox.information(self, "消息框标题", "我RadioButton按钮被选中啦!", QMessageBox.Yes | QMessageBox.No)
          
          
          if __name__ == "__main__":
              app = QApplication(sys.argv)
              myWin = MyMainForm()
              myWin.show()
              sys.exit(app.exec_())
        • self.radioButton.isChecked()  --> 用于判断RadioButton控件是否被选中。返回值Trule表示按钮被选中,False表示按钮未选中。
      • QComboBox下拉列表框

        •     

        •  使用函数currentText() 返回选项中的文本进行获取
        • # -*- coding: utf-8 -*-
          
          import sys
          from PyQt5 import QtCore, QtGui, QtWidgets
          from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox, QComboBox
          
          
          class Ui_Form(object):
              def setupUi(self, Form):
                  Form.setObjectName("Form")
                  Form.resize(400, 130)
                  self.comboBox = QtWidgets.QComboBox(Form)
                  self.comboBox.setGeometry(QtCore.QRect(80, 50, 69, 22))
                  self.comboBox.setObjectName("comboBox")
                  self.comboBox.addItem("")
                  self.comboBox.addItem("")
                  self.comboBox.addItem("")
                  self.comboBox.addItem("")
                  self.comboBox.addItem("")
                  self.okButton = QtWidgets.QPushButton(Form)
                  self.okButton.setGeometry(QtCore.QRect(190, 50, 75, 23))
                  self.okButton.setObjectName("okButton")
          
                  self.retranslateUi(Form)
                  QtCore.QMetaObject.connectSlotsByName(Form)
          
              def retranslateUi(self, Form):
                  _translate = QtCore.QCoreApplication.translate
                  Form.setWindowTitle(_translate("Form", "ComboBox下拉框例子"))
                  self.comboBox.setItemText(0, _translate("Form", "Python"))
                  self.comboBox.setItemText(1, _translate("Form", "Java"))
                  self.comboBox.setItemText(2, _translate("Form", "C"))
                  self.comboBox.setItemText(3, _translate("Form", "C++"))
                  self.comboBox.setItemText(4, _translate("Form", "PHP"))
                  self.okButton.setText(_translate("Form", "确定"))
          
          
          class MyMainForm(QMainWindow, Ui_Form):
              def __init__(self, parent=None):
                  super(MyMainForm, self).__init__(parent)
                  self.setupUi(self)
                  self.okButton.clicked.connect(self.getComboxBoxValue)
          
              def getComboxBoxValue(self):
                  select_value = self.comboBox.currentText()
                  QMessageBox.information(self, "消息框标题", "你要学%s,为师给你说道说道!" % (select_value,), QMessageBox.Yes | QMessageBox.No)
          
          
          if __name__ == "__main__":
              app = QApplication(sys.argv)
              myWin = MyMainForm()
              myWin.show()
              sys.exit(app.exec_())
        •  select_value = self.comboBox.currentText() --> 使用currentText()函数获取下拉框中选择的值   
    • 文本框控件
      • 文本框  
        • # -*- coding: utf-8 -*-
          
          import sys
          from PyQt5 import QtCore, QtGui, QtWidgets
          from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox, QComboBox
          
          
          class Ui_Form(object):
              def setupUi(self, Form):
                  Form.setObjectName("Form")
                  Form.resize(411, 314)
                  self.lineEdit = QtWidgets.QLineEdit(Form)
                  self.lineEdit.setGeometry(QtCore.QRect(120, 50, 251, 41))
                  self.lineEdit.setObjectName("lineEdit")
                  self.lineedit_label = QtWidgets.QLabel(Form)
                  self.lineedit_label.setGeometry(QtCore.QRect(10, 60, 81, 20))
                  font = QtGui.QFont()
                  font.setPointSize(11)
                  font.setBold(True)
                  font.setWeight(75)
                  self.lineedit_label.setFont(font)
                  self.lineedit_label.setObjectName("lineedit_label")
                  self.textEdit = QtWidgets.QTextEdit(Form)
                  self.textEdit.setGeometry(QtCore.QRect(120, 120, 251, 141))
                  self.textEdit.setObjectName("textEdit")
                  self.textedit_label = QtWidgets.QLabel(Form)
                  self.textedit_label.setGeometry(QtCore.QRect(13, 180, 81, 31))
                  font = QtGui.QFont()
                  font.setPointSize(11)
                  font.setBold(True)
                  font.setWeight(75)
                  self.textedit_label.setFont(font)
                  self.textedit_label.setObjectName("textedit_label")
                  self.run_Button = QtWidgets.QPushButton(Form)
                  self.run_Button.setGeometry(QtCore.QRect(150, 280, 91, 31))
                  font = QtGui.QFont()
                  font.setPointSize(11)
                  font.setBold(True)
                  font.setWeight(75)
                  self.run_Button.setFont(font)
                  self.run_Button.setObjectName("run_Button")
          
                  self.retranslateUi(Form)
                  QtCore.QMetaObject.connectSlotsByName(Form)
          
              def retranslateUi(self, Form):
                  _translate = QtCore.QCoreApplication.translate
                  Form.setWindowTitle(_translate("Form", "TextEdit_Example"))
                  self.lineedit_label.setText(_translate("Form", "LineEdit"))
                  self.textedit_label.setText(_translate("Form", "TextEdit"))
                  self.run_Button.setText(_translate("Form", "Run"))
          
          
          class MyMainForm(QMainWindow, Ui_Form):
              def __init__(self, parent=None):
                  super(MyMainForm, self).__init__(parent)
                  self.setupUi(self)
                  self.run_Button.clicked.connect(self.set_display_edit)
          
              def set_display_edit(self):
                  # 设置前先清除文本内容
                  self.lineEdit.clear()
                  self.textEdit.clear()
          
                  # 设置文本框内容
                  self.lineEdit.setText("Lineedit contents")
                  self.textEdit.setPlainText("Textedit contents")
          
                  # 获取文本框内容,并弹框显示内容
                  str1 = self.lineEdit.text()
                  str2 = self.textEdit.toPlainText()
                  QMessageBox.information(self, "获取信息", "LineEdit文本框内容为:%s,TextEdit文本框内容为:%s" % (str1, str2))
          
          
          if __name__ == "__main__":
              app = QApplication(sys.argv)
              myWin = MyMainForm()
              myWin.show()
              sys.exit(app.exec_())  
        • 关健代码
          • def set_display_edit(self):
                    #设置前先清除文本内容
                    self.lineEdit.clear()
                    self.textEdit.clear()
            
                    #设置文本框内容
                    self.lineEdit.setText("Lineedit contents")
                    self.textEdit.setPlainText("Textedit contents")
            
                    #获取文本框内容,并弹框显示内容
                    str1 = self.lineEdit.text()
                    str2 = self.textEdit.toPlainText()
                    QMessageBox.information(self,"获取信息","LineEdit文本框内容为:%s,TextEdit文本框内容为:%s" %(str1,str2))
            

              

              
                   

     

       

                  

            

  • 相关阅读:
    ECNU 3288 成绩计算
    ECNU 3241 字母替换
    ECNU 3243 搜索联系人
    ECNU 2977 成绩排序
    ECNU 2974 统计单词个数
    ECNU 3092 GDP
    【Codeforces Round #693 (Div. 3) D】Even-Odd Game
    【Codeforces Round #693 (Div. 3) C】Long Jumps
    【Codeforces Round #693 (Div. 3) B】Fair Division
    【Codeforces Round #693 (Div. 3) A】Cards for Friends
  • 原文地址:https://www.cnblogs.com/shuimohei/p/13646830.html
Copyright © 2011-2022 走看看