官方推荐的方法是创建要给qml文件当组件,然后使用qml文件创建component,用component创建object
https://doc.qt.io/qt-5/qml-qtqml-component.html
var component = Qt.createComponent("Button.qml");
if (component.status == Component.Ready)
var obj = component.createObject(parent, {x: 100, y: 100});
销毁的方法是obj.destroy()
其实也可以再自己的qml文件里面创建component,然后往这个qml文件中添加新建出来的组件
import QtQuick 2.0
Item {
id: thisWidow
property var my_data: null
function refresh(data){
console.log('refresh data')
//销毁所有子组件
for(var i in my_column.children){
my_column.children[i].destroy()
}
my_data = data
//根据新数据重新创建组件
for(var j in my_data.file_items){
var item = item_in.createObject(my_column,{x:2,width:parent.width-4,height:parent.width*5/7})
item.setFileUrl(my_data.file_items[j].img_url)
}
}
Rectangle{
anchors.fill: parent
color: "#666666"
Flickable{
anchors.fill: parent
contentHeight: my_column.height
contentWidth: width
clip: true
Column{
id:my_column
spacing: 10
}
}
}
Component{
id:item_in
Rectangle{
function setFileUrl(img_url){
console.log("set img_url" + img_url)
file_item_image.source = img_url
}
Image {
anchors.fill:parent
id: file_item_image
source: ""
}
}
}
}
Flickable是一个滚动视图,里面采用Column布局,数据更新后动态调整Column中的数据,如果数据是一个数组的话,用ListView也足够了,但是如果ListView下面还有其他组件滚动区域就太多了,放在一个Flickable中是比较理想的操作