我有QML文件,它描述了button(moduleButton.qml):
import QtQuick 2.0
Rectangle {
id: button;
width: 100; height: 20
Text {
id: buttonText;
text: "Hello World";
}
}
Run Code Online (Sandbox Code Playgroud)
从其他QML表单我通过Qt.createComponent方法加载此按钮:
var moduleButton = Qt.createComponent("moduleButton.qml");
moduleButton.createObject(mainRect);
Run Code Online (Sandbox Code Playgroud)
我试着设置/获取moduleButton的宽度:
moduleButton.width = 30;
Run Code Online (Sandbox Code Playgroud)
但收到以下错误: Cannot assign to non-existent property "width"
如何访问动态对象属性和子元素?
PS Qt.createQmlObject方法完美有效,但我需要从文件加载QML,而不是从字符串加载.
createObject()返回新对象.您的代码应如下所示:
var moduleButton = Qt.createComponent("moduleButton.qml");
var myButton = moduleButton.createObject(mainRect);
myButton.width = 40
Run Code Online (Sandbox Code Playgroud)
moduleButton是一个组件(工厂),用于实例化项目.
文档:http: //qt-project.org/doc/qt-5/qtqml-javascript-dynamicobjectcreation.html