Python操作qml对象

1. 如何在python里获得qml里的对象?

1.1 获取根对象

QML:

import QtQuick 2.12
import QtQuick.Controls 2.12

ApplicationWindow {
    id: window
    width: 250
    height: 500
    visible: true

    // ...
}

Python:

使用QQmlApplicationEngine类的rootObjects方法,返回的是一个列表,取索引0即是根对象。

engine = QQmlApplicationEngine()
engine.load('qml-test.qml')
root_obj = engine.rootObjects()[0]

这样就会获得id为window的ApplicationWindow对象。

 

1.2 获取任意对象

需要在qml文件中加入objecName属性!
QML:

import QtQuick 2.12
import QtQuick.Controls 2.12

ApplicationWindow {
    id: window
    width: 250
    height: 500
    visible: true
    
    Text {
        id: txt
        objectName: "txt"
        text: "Click Me"
        font.pixelSize: 20
        anchors.centerIn: parent
    }
}

Python:

engine = QQmlApplicationEngine()
engine.load('qml-test.qml')
txt_obj = engine.rootObjects()[0].findChild(QObject, "txt")

 

2. 如何在python里读取和设置qml对象的属性和值?

2.1 读取对象的属性(如Text对象)

首先通过 findChild 获取Text对象(注意 txt 是qml文件里的 objectName):

txt_obj = engine.rootObjects()[0].findChild(QObject, "txt")

然后获取Text对象的text属性(使用 property):

txt_value = txt_obj.property("text")

2.2 设置对象的属性

使用setProperty方法可以更改对象的属性值。

txt_obj.setProperty("text", "Clicked!")

 

完整代码:

import sys

from PyQt5.QtCore import QObject
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine

app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
engine.load('qml-test.qml')

# 根对象
root_obj = engine.rootObjects()[0]
# Text对象 txt_obj = engine.rootObjects()[0].findChild(QObject, "txt")
# 读取属性值 txt_value = txt_obj.property("text")
# 设置属性值 txt_obj.setProperty("text", "Clicked!") sys.exit(app.exec())

 

-- END --

posted @ 2019-09-25 16:04  ibg  阅读(2306)  评论(0编辑  收藏  举报