Qt/QML - How to apply the same background to all DelegateChioces in DelegateChooser?

352 views Asked by At

Hi I have a DelegateChooser for a TableView with 10-20 different DelegateChoices. How can I apply the same background to all the choices? I want to avoid having to add the same background to all choices as that is a lot of repeater code and a maintenance headache:

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

There are 1 answers

2
fallerd On BEST ANSWER

First, the Items in your example do not serve a purpose - Rectangles are Items, only colored instead of transparent, making the top level Item a duplicate. Secondly, I would just make a new file MyBackground.qml as such:

import QtQuick 2.0

Rectangle {
    color: "blue"
    // any other necessary background properties here
}

Then you make your ChoiceN files inherit from MyBackground, for example:

// ChoiceN.qml file
import QtQuick 2.0

MyBackground  {
    // ChoiceN.qml contents here as normal
}

And your example code becomes:

DelegateChoice: {
    Choice1 {}
    ...
    Choice20 {}
}

Alternately, if you do not have access to your ChoiceN file contents, you can encapsulate them from outside as well:

DelegateChoice: {
    MyBackground {
        Choice1 {}
    }
    ...
    MyBackground {
        Choice20 {}
    }
}