Question 4: CPP中某个类的编译器自动调用的构造函数constructor和析构函数destructor都跑哪里去了? 太不方便了!
Answer: 每个qml对象都认为是一个组件Component,所以是通过附加属性attached attributes来实现的。
构造函数对应: Component.onCompleted:{}
析构函数对应:Component.onDestruction:{}
例子:
import QtQuick
Window {
id: mainWidget
width: 640
height: 480
visible: true
title: qsTr("Hello World")
Rectangle{
id: rect
width: 100
height: 100
color: "red"
}
//构造函数 Window();
Component.onCompleted: {
console.log (rect.color);
rect.color = "blue";
console.log (rect.color);
}
//析构函数 ~Window();
Component.onDestruction: {
console.log("program exited.");
}
}
1275

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



