问题描述
嗨,我有一个 DelegateChooser
用于 TableView
,其中包含 10-20 个不同的 DelegateChoice
。如何将相同背景应用于所有选择?我想避免必须为所有选择添加相同的背景,因为这是大量的中继器代码和维护问题:
DelegateChoice: {
Item {
Rectangle { id: background; anchors.fill: parent; color: "blue" }
Choice1 {}
}
...
Item {
Rectangle { id: background; anchors.fill: parent; color: "blue" }
Choice20 {}
}
}
解决方法
首先,您示例中的 Item
没有任何用途 - Rectangle
是 Item
,仅着色而不是透明,使顶级 Item
一个副本。其次,我会创建一个新文件 MyBackground.qml
如下:
import QtQuick 2.0
Rectangle {
color: "blue"
// any other necessary background properties here
}
然后让您的 ChoiceN
文件继承自 MyBackground
,例如:
// ChoiceN.qml file
import QtQuick 2.0
MyBackground {
// ChoiceN.qml contents here as normal
}
您的示例代码变为:
DelegateChoice: {
Choice1 {}
...
Choice20 {}
}
或者,如果您无权访问您的 ChoiceN 文件内容,您也可以从外部封装它们:
DelegateChoice: {
MyBackground {
Choice1 {}
}
...
MyBackground {
Choice20 {}
}
}