Qml存在一个神秘附加属性(default)却是很少用,少用却是很好用。看看我这是怎么用的吧。
{}
内)仅此一个default标记。MyText.qml组件内部引用外部对象的两种方法。
import QtQuick 2.0
Text {
default property variant textObject
text: textObject.text
}
方法一:
MyText
的Text控件被引用到textObject中使用。MyText {
Text { text: "xxxxx" } // 默认传递给textObject值。
}
方法二:
MyLabel {
textObject: Text { text: "xxxxx" } // 等同于默认传递给textObject值。
}
看似很没用的属性却说有用,还说好用。第一个例子看起来和常规做法差不多。那么我们看看第二个例子使用起来是如何好用的。 Group.qml组件:
import QtQuick 2.0
FocusScope {
property alias title: title.text
default property alias items: colume.children
Text { id: title }
Column {
id: colume
anchors.top: title.bottom
}
}
Group的使用:
Group {
title: "title"
Rectangle {
width: 100; height: 50;
color: "red"
}
Rectangle {
width: 100; height: 50;
color: "lightblue"
}
}
如果不使用该特性则需要这样做: 如需要多个地方使用则需要重复操作,管理不方便,且理解不直观。
Column {
Text {
text: "title"
}
Column {
Rectangle {
width: 100; height: 50;
color: "red"
}
Rectangle {
width: 100; height: 50;
color: "lightblue"
}
}
}
效果:
从上面例子可以看到Group组件具备Column控件的布局功能,并扩展出类似于 GroupBox
控件的功能。原因在于colume.children引用了Group的子控件触发自动布局。
对于上面例子我们还可以内部操控items
对象列表来操作Group上的子控件属性,如item[0].visible = false
来隐藏红色矩形控件。
这样做我们就可以增强组件的功能,降低代码量,特别是那些具备标题栏或某些附属栏的组合框。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有