如何通过JavaScript在QML中动态创建QML对象
有时候我们在QML中需要根据用户的操作或者其他一些条件,在运行时动态地添加一些QML组件,这时候我们可以使用JavaScript来实现。
首先,我们需要定义一个空的Item作为容器,然后通过JavaScript在该容器中动态地添加组件。
具体代码如下:
import QtQuick 2.0
Rectangle {
id: root
width: 640
height: 480
// 容器
Item {
id: container
anchors.fill: parent
}
// 按钮,点击后动态添加Text组件
Button {
text: "添加组件"
onClicked: {
var dynamicText = Qt.createQmlObject("import QtQuick 2.0; Text { text: '动态生成的文本' }", container);
dynamicText.x = Math.random() * (container.width - dynamicText.width);
dynamicText.y = Math.random() * (container.height - dynamicText.height);
}
}
}
在这段代码中,我们定义了一个Rectangle作为根
订阅专栏 解锁全文
3924



被折叠的 条评论
为什么被折叠?



