Qt文章链接https://doc.qt.io/qt-5/qtqml-javascript-dynamicobjectcreation.html
QML支持从JavaScript内部动态创建对象。可以做到需要时才实例化对象,从而缩短了应用程序的启动时间。它还允许根据用户输入或其他事件动态创建视觉对象并将其添加到场景。
动态创建对象
有两种方法可以从JavaScript动态创建对象。您可以调用Qt.createComponent()动态创建Component对象,也可以使用Qt.createQmlObject()根据QML字符串创建对象。如果您在QML文档中定义了现有组件,并且想要动态创建该组件的实例,则创建组件会更好。否则,当在运行时生成对象QML本身时,从QML字符串创建对象很有用。
动态创建组件
在一个文件中定义好了一个QML类型,可使用Qt.createComponent()
//Sprite.qml 定义了一个Sprite类型
import QtQuick 2.0
Rectangle { width: 80; height: 50; color: "red" }
//----------------------------------文件分隔main.qml-----------------------------------------
// main.qml,调用
import QtQuick 2.0
import "componentCreation.js" as MyScript
Rectangle {
id: appWindow
width: 300; height: 300
Component.onCompleted: MyScript.createSpriteObjects();
}
//-------------------------------文件分隔componentCreation.js--------------------------------------------
//componentCreation.js
var component;
var sprite;
//文件有可能在网络上,加载会出现延迟
function createSpriteObjects() {
component = Qt.createComponent("Sprite.qml"); //加载组件后,使用组件创建对象
if (component.status == Component.Ready) //如果加载完成,则加载组件
finishCreation();
else
component.statusChanged.connect(finishCreation); //没有完成等待完成后再加载
}
function finishCreation() {
if (component.status == Component.Ready) {
//appWindow是main.qml中的rect,sprite将显示在它的100,100的位置
sprite = component.createObject(appWindow, {x: 100, y: 100}); //创建对象
if (sprite == null) {
// Error Handling
console.log("Error creating object");
}
} else if (component.status == Component.Error) {
// Error Handling
console.log("Error loading component:", component.errorString());
}
}
要将信号连接到动态创建的对象(或从中接收信号),请使用信号connect()
方法。有关更多信息,请参见将信号连接到方法和信号。
也可以通过incubateObject()函数实例化组件而不会阻塞。
从QML字符串创建对象
如果直到运行时才定义QML,则可以使用Qt.createQmlObject()函数从QML字符串中创建QML对象,如以下示例所示:
//第一个参数是要创建的QML字符串。第二个参数是新对象的父对象
var newObject = Qt.createQmlObject('import QtQuick 2.0; Rectangle {color: "red"; width: 20; height: 20}',
parentItem,
"dynamicSnippet1");
动态删除对象
只有动态对象才能销毁
application.qml
import QtQuick 2.0
Item {
id: container
width: 500; height: 100
Component.onCompleted: {
//创建SelfDestroyingRect对象,它显示完动画后会把自己销毁
var component = Qt.createComponent("SelfDestroyingRect.qml");
for (var i=0; i<5; i++) {
var object = component.createObject(container);
object.x = (object.width + 10) * i;
}
}
}
SelfDestroyingRect.qml
import QtQuick 2.0
Rectangle {
id: rect
width: 80; height: 80
color: "red"
NumberAnimation on opacity {
to: 0
duration: 1000
onRunningChanged: {
if (!running) {
console.log("Destroying...")
rect.destroy(); //当动画结束时销毁对象
}
}
}
}