Qt/QML-如何将相同的背景应用于DelegateChooser中的所有DelegateChioCE?

Qt/QML-如何将相同的背景应用于DelegateChooser中的所有DelegateChioCE?,qt,qml,qtquick2,qtquickcontrols2,qtdeclarative,Qt,Qml,Qtquick2,Qtquickcontrols2,Qtdeclarative,嗨,我有一个DelegateChooser用于TableView,有10-20个不同的delegatechooses。如何将相同的背景应用于所有选择?我希望避免在所有选择中添加相同的背景,因为这会导致大量转发器代码和维护难题: DelegateChoice: { Item { Rectangle { id: background; anchors.fill: parent; color: "blue" } Choice1 {}

嗨,我有一个
DelegateChooser
用于
TableView
,有10-20个不同的
delegatechoose
s。如何将相同的背景应用于所有选择?我希望避免在所有选择中添加相同的背景,因为这会导致大量转发器代码和维护难题:

DelegateChoice: {
   Item {
         Rectangle { id: background; anchors.fill: parent; color: "blue" }
         Choice1 {}
    }
    ...
   Item {
         Rectangle { id: background; anchors.fill: parent; color: "blue" }
         Choice20 {}
    }
}

首先,示例中的
s不起作用-
矩形
s为
s,仅着色而非透明,使顶层
重复。其次,我只需要创建一个新文件
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 {}
    }
}

非常感谢。我唯一不喜欢这个答案的地方是它使我的选择不可重用。我更愿意将我的委托保存为自包含的可重用文件,而可重用组件设置后台是没有意义的。但考虑到DelegateChooser的局限性,这似乎是最好的解决方案。我更愿意以某种方式一次为每个代表添加背景。