1. How to get qml objects in python in there?
1.1 Gets the root object
QML:
import QtQuick 2.12
import QtQuick.Controls 2.12
ApplicationWindow {
id: window
width: 250
height: 500
visible: true
// ...
}
Python:
The method of using rootObjects QQmlApplicationEngine class.
engine = QQmlApplicationEngine() engine.load('qml-test.qml') root_obj = engine.rootObjects()[0]
This will get the window as ApplicationWindow object id.
1.2 acquire any object
ObjecName need to add properties in qml file!
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. how to read and set properties and values qml objects in python in?
2.1 reads the object's properties (such as Text Object)
Firstly findChild get Text object (note txt is qml documents in the objectName):
txt_obj = engine.rootObjects()[0].findChild(QObject, "txt")
Text object and then get the text attributes (using the Property ):
txt_value = txt_obj.property("text")
2.2 Setting attribute of the object
Use setProperty method can change the object's property value.
txt_obj.setProperty("text", "Clicked!")
Complete code:
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 --