有一个qml控件,我需要在运行时动态去创建,可用一下方法:
控件River.qml, 里面就简单放个Image元素测试:
import QtQuick 2.15
Item {
property string imgsrc: ""
Image {
id: img1
source: imgsrc
}
}
main.qml
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 1.4
Window {
id: wnd
width: 1280
height: 720
visible: true
title: qsTr("Hello World")
property var instances: []
Row{
y: 400
spacing: 5
Button {
text: "add 1"
onClicked: {
var objc = { "x": 15, "y": 15, "imgsrc": "qrc:/tire_normal.png"};
addOrRemove(true, objc)
console.log("111")
}
}
Button {
text: "add 2"
onClicked: {
var objc = { "x": 100, "y": 100, "imgsrc": "qrc:/WarnDoorBg.png"};
addOrRemove(true, objc)
}
}
Button {
text: "remove 1"
onClicked: {
addOrRemove(false, null); //instances[0].destroy();
}
}
}
Rectangle{
id: rect
clip: true
color: "yellow"
width: 300
height: 300
}
function addOrRemove(add, objdata) {
if (add) {
var imgComponent = Qt.createComponent("qrc:/River.qml");
let instance = weirdShapeComponent.createObject(rect, objdata);
instances.push(instance);
} else {
let instance = instances.pop();
instance.destroy();
}
}
}