关于PyQt5响应QML发送信号的方法?

QML是一个解释型的语言,语法像CSS,可以嵌入JavaScript,这正好符合我使用Python的风格,简单,好用。


    以下的例子是基于Python3.3+PyQt5.1+QML的例子,通过点击鼠标,然后QML响应事件后发送一个信号到PyQt5,然后调用指定的函数。


以下是源代码:

Python3.3的代码

from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQuick import QQuickView

def outputString(string):
    print(string)


if __name__ == '__main__':
    # path = r'test\main.qml'
    path = 'main.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_()
QML部分的代码:
import QtQuick 2.0

Rectangle {
    id: root
    width: 320; height: 240
    color: "lightgray"

    signal sendClicked(string str1) // 定义信号

    Rectangle {
        id: rect
        width: 200; height: 100; border.width: 1
        anchors.centerIn: parent

        Text {
            id: txt
            text: "Clicked me"
            font.pixelSize: 20
            anchors.centerIn: rect
        }
    }

    MouseArea {
        id: mouse_area
        anchors.fill: rect  // 有效区域
        onClicked: {
           parent.sendClicked("Hello, Python3")    // 发射信号到Python
        }
    }
}

运行效果如下:

关于PyQt5响应QML发送信号的方法?

QML文件需要保存为main.qml,否则会出现找不到*.qml文件的问题。

通过点击运行效果图的白色区域,就可以在控制台打印"Hello, Python3"的字符串。

以上代码如有不明白的,欢迎评论。


另外,如果有哪位知道如何使用PyQt5发送信号到QML的,可以告诉我一下,谢谢!!

你可能感兴趣的:(python3,qml,PyQt5)