QML文件定义信号和python定义槽绑定

QML文件

QML文件命名为Main.qml

import QtQuick 2.12
import QtQuick.Window 2.12

Window {
    
    
    visible: true	//此属性必须要定义
    width: 640
    height: 480
    title: qsTr("Hello World")
    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函数
            }
        }
    }
}

python代码

from PyQt5.QtQuick import QQuickView
from PyQt5 import  QtGui, QtWidgets, QtCore
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5 import QtQml,QtQuick
import sys

class MyClass(QObject):
    @pyqtSlot(str)    # 输入参数为str类型
    def outputString(self, string):
        print(string)
if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    engine = QtQml.QQmlApplicationEngine(QUrl('Main.qml'))
    con = MyClass()
    context = engine.rootContext()
    context.setContextProperty("con", con) # 信号和槽进行绑定
    sys.exit(app.exec_())

运行结果
在这里插入图片描述

Quick View和QML绑定

如果QML的跟元素还是window的话,那么用quick view调用会多出一个python的窗口,解决这个问题的办法就是将QML文件里的根元素改成Rectangle或者用上面的方法。

python代码

from PyQt5.QtQuick import QQuickView
from PyQt5 import  QtGui, QtWidgets, QtCore
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5 import QtQml,QtQuick
import sys

class MyClass(QObject):
    @pyqtSlot(str)    # 输入参数为str类型
    def outputString(self, string):
        print(string)
if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    path = 'Main.qml'   # 加载的QML文件
    view = QQuickView()
    con = MyClass()
    context = view.rootContext()
    context.setContextProperty("con", con) # 信号和槽进行绑定
    view.setTitle('main')
    view.engine().quit.connect(app.quit)
    view.setSource(QUrl(path))
    view.show()
    sys.exit(app.exec_())

运行结果(此解决是未将QML的根元素改成Rectangle)
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/youngdianfeng/article/details/107443799