【问题标题】:Qt/QML - How to apply the same background to all DelegateChioces in DelegateChooser?Qt/QML - 如何对 DelegateChooser 中的所有 DelegateChioces 应用相同的背景?
【发布时间】:2021-04-27 16:53:30
【问题描述】:

您好,我有一个 DelegateChooser 对应一个 TableView 和 10-20 个不同的 DelegateChoices。如何将相同的背景应用于所有选项?我想避免必须为所有选项添加相同的背景,因为这是大量的重复代码和令人头疼的维护问题:

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

【问题讨论】:

    标签: qt qml qtquick2 qtquickcontrols2 qtdeclarative


    【解决方案1】:

    首先,您示例中的 Items 没有任何用途 - Rectangles 是 Items,只有彩色而不是透明的,从而使顶级 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 {}
        }
    }
    

    【讨论】:

    • 谢谢。我唯一不喜欢这个答案的是它使我的选择不可重用。我宁愿将我的代表保留为自包含的可重用文件,并且为可重用组件设置背景没有意义。
    • 但是考虑到 DelegateChooser 的限制,这似乎是最好的解决方案。我宁愿以某种方式一次为每个代表添加背景。
    猜你喜欢
    • 1970-01-01
    • 2014-07-21
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多