5 string qt components qml qtquick2
可以使用以下文件从文件创建 QML 组件 Qt.createComponent(filename)
可以使用字符串从字符串创建 QML 对象 Qt.createQmlObject(string)
可以通过代码从代码创建 QML 组件 Component {...}
但是是否可以从字符串创建 QML 组件?我的意思是没有为了使用而努力将其保存为临时文件Qt.createComponent(filename)?
编辑:只是为了澄清,我已经有了这个示例表单中的组件:
import QtQuick 2.0
Rectangle {
width: 100
height: 100
color: "red"
}
Run Code Online (Sandbox Code Playgroud)
所以我需要从该字符串创建一个组件而不实例化它。我不能简单地将字符串包装在 a 中,"Component {" + string + "}"因为无法在组件内声明导入。一个解决方案是使用复杂的解析在第一个元素之前和导入之后插入组件,但我认为它并不是最优雅的解决方案。
使用Qt.createQmlObject(string)。它创建一个对象,而不是原型。
Window {
id: mainWindow
visible: true
width: 600
height: 400
Component.onCompleted: {
var str = '
import QtQuick 2.3;
Component {
Text {
text: "Hello, world!";
anchors.fill: parent;
horizontalAlignment: Text.AlignHCenter;
verticalAlignment: Text.AlignVCenter;
}
}';
var component = Qt.createQmlObject(str,mainWindow);
var object = component.createObject(mainWindow);
}
}
Run Code Online (Sandbox Code Playgroud)