PyQT5基础(学习笔记)

目录

一、使用Qt Designer

二、使用QML


PyQt5借助Python的大量的函数库,对数据的获取和处理功能,补充C++这方面的不足

一、使用Qt Designer

  • 我的第一个PyQt5程序

    1. PyChram配置:

      • QtDesigner

        C:\Users\20582\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\pyqt5_tools\designer.exe
        
        
        
           $FileDir$
        ​
         - PyUic
        ​
           C:\Users\20582\AppData\Local\Programs\Python\Python36-32\python.exe
        ​
           -m PyQt5.uic.pyuic $FileName$ -o ui_$FileNameWithoutExtension$.py
        ​
           $FileDir$
        ​
         - PyRcc
        ​
           C:\Users\20582\AppData\Local\Programs\Python\Python36-32\Scripts\pyrcc5.exe
        ​
           $FileName$ -o $FileNameWithoutExtension$_rc.py
        ​
           $FileDir$

         

  • 使用Python构建程序的核心模块——使用槽函数

    1. UI和代码分离

      import sys
      from PyQt5.QtWidgets import QApplication
      from firstMainWin import *
      ​
      class MyMainWindow(QMainWindow,UI_MainWindow):
          def __init__(self,parent=None):
              super().__init__(parent)
              self.setupUi(self)
      ​
      if __name__ == '__main__':
          app = QApplication(sys.argv)
          myWin = MyMainWindow()
          myWin.show()
          sys.exit(app.exec_())

       

    2. 使用槽函数

       

      • 先使用界面设计师连接槽函数

      • 然后生成代码

      • 实现新建的槽函数

  • PyQt5程序模块化

    1. 引用自己定义的模块

      from 文件名 import *

       

    2. 引用Qt模块

      from PyQt5.QtWidgets import QApplication

       

    3. 引用Python模块(查询相关文档)

      import sys

       

二、使用QML

  • QML Designer的语法规范

    1. 界面文件中不可以定义Json

    2. 使用Conncet来连接信号和Json代码

      Connect{
          target: id
          onClicked:{
              ...
          }
      }

       

  • Python和QML的数据交换

    • QML和Python的5中交互方式

      1. QML显式的调用Python函数

        from PyQt5.QtCore import QUrl, QObject, pyqtSlot
        from PyQt5.QtGui import QGuiApplication
        from PyQt5.QtQuick import QQuickView
        ​
        class MyClass(QObject):
            @pyqtSlot(str)    # 输入参数为str类型
            def outputString(self, string):
                print(string)
        ​
        if __name__ == '__main__':
            path = 'test.qml'   # 加载的QML文件
            app = QGuiApplication([])
            view = QQuickView()
            con = MyClass()
            context = view.rootContext()
            context.setContextProperty("con", con)
            view.engine().quit.connect(app.quit)
            view.setSource(QUrl(path))
            view.show()
            app.exec_()
         
        import QtQuick 2.0
        ​
        Rectangle {
            width: 320; height: 240
            color: "lightblue"
            Text {
                id: txt
                text: "Clicked me"
                font.pixelSize: 20
                anchors.centerIn: parent
            }
            MouseArea {
                id: mouse_area
                anchors.fill: parent  // 有效区域
                onClicked: {
                   con.outputString("Hello, Python3") //QML显式的调用Python函数   
                }
            }
        }

         

      2. QML调用Python函数,并返回

        from PyQt5.QtCore import QUrl, QObject, pyqtSlot
        from PyQt5.QtGui import QGuiApplication
        from PyQt5.QtQuick import QQuickView
        
        class MyClass(QObject):
            @pyqtSlot(int, result=str)    # 声明为槽,输入参数为int类型,返回值为str类型
            def returnValue(self, value):
                return str(value+10)
        
        if __name__ == '__main__':
            path = 'test2.qml'   # 加载的QML文件
            app = QGuiApplication([])
            view = QQuickView()
            con = MyClass()
            context = view.rootContext()
            context.setContextProperty("con", con)
            view.engine().quit.connect(app.quit)
            view.setSource(QUrl(path))
            view.show()
            app.exec_()
        import QtQuick 2.0
        
        Rectangle {
            id: root
            width: 320; height: 240
            color: "lightgray"
            Text {
                id: txt
                text: "Clicked me"
                font.pixelSize: 20
                anchors.centerIn: parent
            }
            Text {
                id: txt1
                text: "..."
                font.pixelSize: 20
            }
            MouseArea {
                id: mouse_area
                anchors.fill: parent  // 有效区域
                onClicked: {
                    console.log("test...")  // 控制台打印信息
                    txt1.text = con.returnValue(20) //QML显式的调用Python函数    
                }
            }
        }

         

      3. QML连接信号到Python

        from PyQt5.QtCore import QUrl
        from PyQt5.QtGui import QGuiApplication
        from PyQt5.QtQuick import QQuickView
        
        def outputString(string):
            print(string)
        
        
        
        if __name__ == '__main__':
            path = 'test3.qml'   # 加载的QML文件
            app = QGuiApplication([])
            view = QQuickView()
            view.engine().quit.connect(app.quit)
            view.setSource(QUrl(path))
            view.show()
            context = view.rootObject()
            context.sendClicked.connect(outputString)   # 连接QML信号sendCLicked
            app.exec_()
        import QtQuick 2.0
         
        Rectangle {
            id: root
            width: 320; height: 240
            color: "lightgray"
            signal sendClicked(string str) // 定义信号
         
            Text {
                id: txt
                text: "Clicked me"
                font.pixelSize: 20
                anchors.centerIn: parent
            }
            MouseArea {
                id: mouse_area
                anchors.fill: parent  //有效区域
                onClicked: {
                    root.sendClicked("Hello, Python3")//发射信号到Python        
                }
            }
        }

         

      4. Python调用QML函数

        from PyQt5.QtCore import QUrl, QTimer
        from PyQt5.QtGui import QGuiApplication
        from PyQt5.QtQuick import QQuickView
         
        if __name__ == '__main__':
            path = 'test4.qml'   # 加载的QML文件
         
            app = QGuiApplication([])
            view = QQuickView()
            view.engine().quit.connect(app.quit)
            view.setSource(QUrl(path))
            view.show()
         
            timer = QTimer()
            timer.start(2000)
            root = view.rootObject()
            timer.timeout.connect(root.updateRotater) # 调用QML函数                 
         
            app.exec_()
        import QtQuick 2.0
         
        Rectangle {
            id: page
            width: 500; height: 200
            color: "lightgray"
         
            function updateRotater() {// 定义函数                             
                rotater.angle += 5
            }
         
            Rectangle {
                id: rotater
                property real angle : 0
                x: 240; y: 95
                width: 100; height: 5
                color: "black"
         
                transform: Rotation {
                    origin.x: 10; origin.y: 5
                    angle: rotater.angle
                }
            }
        }

         

      5. 信号/槽 机制

        from PyQt5.QtCore import pyqtProperty, pyqtSignal, pyqtSlot, QRectF, Qt, QUrl
        from PyQt5.QtGui import QColor, QGuiApplication, QPainter, QPen
        from PyQt5.QtQml import qmlRegisterType
        from PyQt5.QtQuick import QQuickPaintedItem, QQuickView
        
        
        class PieChart(QQuickPaintedItem):
        
            chartCleared = pyqtSignal() # 定义信号
        
            @pyqtProperty(str)
            def name(self):
                return self._name
        
            @name.setter
            def name(self, name):
                self._name = name
        
            @pyqtProperty(QColor)
            def color(self):
                return self._color
        
            @color.setter
            def color(self, color):
                self._color = QColor(color)
        
            def __init__(self, parent=None):
                super(PieChart, self).__init__(parent)
        
                self._name = ''
                self._color = QColor()
        
            def paint(self, painter):
                painter.setPen(QPen(self._color, 2))
                painter.setRenderHints(QPainter.Antialiasing, True)
        
                rect = QRectF(0, 0, self.width(), self.height()).adjusted(1, 1, -1, -1)
                painter.drawPie(rect, 90 * 16, 290 * 16)
        
            @pyqtSlot()
            def clearChart(self):
                self.color = QColor(Qt.transparent)
                self.update()
        
                self.chartCleared.emit() # 发射信号
        
        
        if __name__ == '__main__':
            import os
            import sys
        
            app = QGuiApplication(sys.argv)
        
            qmlRegisterType(PieChart, "Charts", 1, 0, "PieChart")
        
            view = QQuickView()
            view.setResizeMode(QQuickView.SizeRootObjectToView)
            view.setSource(
                    QUrl.fromLocalFile(
                            os.path.join(os.path.dirname(__file__),'tes5.qml')))
            view.show()
        
            sys.exit(app.exec_())
        import Charts 1.0
        import QtQuick 2.0
        
        Item {
            width: 300; height: 200
        
            PieChart {
                id: aPieChart
                anchors.centerIn: parent
                width: 100; height: 100
                color: "red"
        
                onChartCleared: console.log("The chart has been cleared") //槽
            }
        
            MouseArea {
                anchors.fill: parent
                onClicked: aPieChart.clearChart()
            }
        
            Text {
                anchors { bottom: parent.bottom; horizontalCenter: parent.horizontalCenter; bottomMargin: 20 }
                text: "Click anywhere to clear the chart"
            }
        }

         

      6. https://www.cnblogs.com/hhh5460/p/4237863.htmlhttps://www.cnblogs.com/hhh5460/p/4237863.html

    • 访问QML属性和函数

      import QtQuick 2.5
      
      Rectangle {
          id: page
          objectName: page
          width: 500;
          height: 200;
          property int someNumber: 100
          function setText(t) {
              _txt.text = t
          }
      
          Text{
              objectName: 'txt1'
              id: _txt
              text: ''
          }
          
      }
      
      import sys
      from PyQt5.QtCore import QUrl, QTimer,QObject
      from PyQt5.QtWidgets import QApplication
      from PyQt5.QtQuick import QQuickView,QQuickItem
      
      if __name__ == '__main__':
          path = '../main.qml'   # 加载的QML文件
      
          app = QApplication([])
          view = QQuickView()
          view.setSource(QUrl(path))
          view.show()
      
          root = view.rootObject()
          root.setText('你好')
          print(root.property('someNumber'))
          w = root.findChild(QObject, 'txt1').property('width')
          print(w)
          sys.exit(app.exec_())
      1. https://blog.csdn.net/liang19890820/article/details/64923805(将 C++ 对象嵌入到带有上下文属性的 QML 中)

      2. https://blog.csdn.net/baidu_33850454/article/details/81941675(QML 与 C++交互 - 03 C++访问QML属性与函数)

      3. https://blog.csdn.net/esonpo/article/details/36175555(Python和C++混合使用QML开发GUI)

  • 数据驱动的方式编写QML

    1. 用Vue的观点处理QML编程

    2. 需要外部修改的数据需要将属性导出

    3. 外部通过proporty()和setProperty()来修改QML属性

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值