QML属性值设置(初始化)方式有很多种,下面列出四种(常量、表达式、变量或者函数方式赋值)方式:
第一种方式–常量:
//常量方式赋值
Rectangle{
id: rect1
x:0
y:0
width:10
height:30
}
第二种方式–变量:
//变量方式赋值,变量可以来自他上层(上司)的。
Rectangle{
id: rect2
x: rect1.width
y: rect1.height
width: rect1.width*2
height: rect1.width*2
}
第三种方式–表达式:
//表达式方式赋值,可以是算术表达式、判断表达式、三目运算符等等,根据不同类型运用不同的表达式,这样就可以做到任意控制了。
Rectangle{
id: rect3
x: rect1.x + rect2.x
y: rect1.y + rect2.y
width: rect1.width > rect2.width ? rect1.width : rect2.width
height: rect1.height> rect2.height? rect1.height: rect2.height
visible: rect1.width + rect2.width === 30
}
第四种方式–函数:
//函数方式赋值。书写格式{ 代码块; return 返回值;}。
/*这种方式就可以用在当你需要某个变量改变的时候,然后根据变量值去改变他的行为的时就可以用这种方式了*/
Rectangle{
id: rect4
x: {
if(rect3.visible)
return 0;
else
return rect3.x;
}
y: {
if(rect3.visible)
return 0;
else
return rect3.y;
}
width: {
if(rect3.visible)
return rect3.x + rect3.width
else
return rect3.width;
}
height: {
if(rect3.visible)
return rect3.y + rect3.height
else
return rect3.height;
}
color:{
if(rect3.visible)
return "#80808080";
else
return "#000000";
}
}