我想将对象动态添加到qml Column
布局中,但不知道如何做到这一点。
因此,对于简单的示例,让我们假设我们需要通过按第一个矩形将一些新对象添加到列中。另外两个只是为了买一些书。
下面是一些代码:
import QtQuick 2.9
import QtQuick.Window 2.2
ApplicationWindow {
width: 360
height: 360
visible: true
id: root
Item {
id: itemRef
width: 310; height: 170
Column {
id: columnRef
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
spacing: 5
Rectangle { color: "lightblue"; radius: 10.0
width: 300; height: 50
Text { anchors.centerIn: parent
font.pointSize: 24; text: "Press me" }
MouseArea{
anchors.fill: parent
onClicked: {
var component = Qt.createComponent("Sprite.qml");
if (component.status === Component.Ready){
sprite = component.createObject(columnRef);
}
}
}
}
Rectangle { color: "gold"; radius: 10.0
width: 300; height: 50
Text { anchors.centerIn: parent
font.pointSize: 24; text: "1" } }
Rectangle { color: "lightgreen"; radius: 10.0
width: 300; height: 50
Text { anchors.centerIn: parent
font.pointSize: 24; text: "2" } }
}
}
}
而Sprite.qml仅仅是:
import QtQuick 2.9
Item {
Rectangle { width: 300; height: 50; color: "red" }
}
我不想使用listmodel
和listview
来实现它。有没有简单的方法从qml文件中创建项目,然后将其添加到列中?
发布于 2018-06-03 03:52:10
您的代码中有几个问题:您使用sprite
作为变量,而它并未如此定义。它必须在java脚本中声明为var
。
其次,您的sprite.qml
正在创建一个Item
,它不应作为Column
布局中的子级。因此,您只需要在sprite.qml
中定义一个rectangle
,纠正这些问题将按预期呈现新的矩形
Bonus:如果你想在重复点击的同时正确渲染,你需要注意项目容器的高度,以确保它可以容纳新创建的矩形。因此,您可以向脚本添加类似以下内容的内容:itemRef.height = itemRef.height + sprite.height
正确的代码可能如下所示:
...
onClicked: {
var component;
var sprite;
component = Qt.createComponent("Sprite.qml");
if (component.status === Component.Ready){
sprite = component.createObject(columnRef);
itemRef.height = itemRef.height + sprite.height
}
}
...
和sprite.qml
import QtQuick 2.9
Rectangle { color: "red"; radius: 10.0
width: 300; height: 50
Text { anchors.centerIn: parent
font.pointSize: 24; text: "new" } }
结果:
https://stackoverflow.com/questions/50656746
复制相似问题