qt - 如何设置动态创建的对象的一个或多个属性?
问题描述
我的问题很简单。如果我动态创建了一个 qml 组件,我该如何设置它的属性?
在这个我的示例中,我想在单击按钮元素时更改颜色
Window {
id:win
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Component.onCompleted: {
var comp=Qt.createComponent("MyRectangle.qml")
comp.createObject(page,{"id":"pippo","color":"yellow","width":50})
}
Page{
id: page
anchors.fill: parent
Button{
x:200
height: 50
width: 50
onClicked:{
// i want to set color of the rectangle tha i have created
}
}
}
}
MyRectangle 是我的自定义 qml 对象。
Rectangle {
id:pippo
color:"red"
width:30
height: 30
}
解决方案
您必须使用创建的对象来执行此操作,并且您可以获得createObject()
返回的内容:
Window {
id:win
visible: true
width: 640
height: 480
title: qsTr("Hello World")
property var pippo_object: null
Component.onCompleted: {
var comp=Qt.createComponent("MyRectangle.qml")
pippo_object = comp.createObject(page, {
"id":"pippo",
"color":"yellow",
"width":50
})
}
Page{
id: page
anchors.fill: parent
Button{
x:200
height: 50
width: 50
onClicked:{
if(pippo_object!==null)
pippo_object.color = Qt.rgba(Math.random(),
Math.random(),
Math.random(),
1)
}
}
}
}
推荐阅读
- arrays - 代码片段有什么区别?
- python - 在 python 中设置随机种子会干扰多处理
- ios - 如何在 IOS 中使用 cedar 测试 http 请求块
- c# - 自动化“然后”步骤 BDD C# Specflow 的问题
- java - 无效的 LOC 标头(错误的签名)
- javascript - 将 JavaScript 代码转换为 React 组件类格式
- python - angularjs在来自flask服务器的变量中将&转换为&
- tableau-api - NOT NULL 条件的合理方法?
- testing - 赛普拉斯测试中是否支持 ES2018?(对象扩展运算符)
- regex - 使用公式更改列的格式