如何在QML中重用代码 [英] How to reuse code at QML
本文介绍了如何在QML中重用代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这段QML代码:
Column {
spacing: units.gu(2)
anchors {
fill: parent
centerIn: parent
}
Row {
spacing: units.gu(4)
...
}
Row {
spacing: units.gu(4)
...
}
Row {
spacing: units.gu(4)
...
}
Row {
spacing: units.gu(4)
...
}
}
关于QML编程的最佳实践,如何重用代码以避免公共元素的重复属性?例如,在上面的示例中,避免行"space:units.gu(4)"。
Qml
将代码放在单独的推荐答案文件中,并将该文件名用作元素。例如
//文件MyCustomRow.qml
Row {
spacing: units.gu(4)
...
}
然后在您的其他QML文件中:
Column {
spacing: units.gu(2)
anchors {
fill: parent
centerIn: parent
}
MyCustomRow{
}
MyCustomRow{
}
MyCustomRow{
}
MyCustomRow{
}
}
事实上,您可以使用中继器:
Column
{
spacing: units.gu(2)
anchors
{
fill: parent
centerIn: parent
}
Repeater
{
model : 5
MyCustomRow
{
}
}
}
编辑:
要在单个文件中完成此操作(如注释中所述),您可以使用QMLComponent元素和Loader元素:
Column {
spacing: units.gu(2)
anchors {
fill: parent
centerIn: parent
}
Component
{
id : myCustomRow
Row
{
spacing: units.gu(4)
...
}
}
Loader {
sourceComponent : myCustomRow
}
Loader {
sourceComponent : myCustomRow
}
Loader {
sourceComponent : myCustomRow
}
Loader {
sourceComponent : myCustomRow
}
}
这篇关于如何在QML中重用代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文