Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an extra item to a QML ComboBox which is not in the model?

I have a QML ComboBox which has a QAbstractListModel attached to it. Something like this:

ComboBox {
    model: customListModel
}

And I would like it to display an extra item in the drop down list which is not in the model.

For example, let's say there are two items in the customListModel: Apple and Orange. And in the drop down list it should display the following options:

  • Select all
  • Apple
  • Orange

I can't add it to the model because it contains custom objects and I use this model a couple of other places in the program and it would screw up everything.

How can I add this "Select all" option to the ComboBox???

like image 622
Attila Fenyvesi Avatar asked Mar 02 '23 00:03

Attila Fenyvesi


1 Answers

One way to do it is to create a proxy model of some sort. Here's a couple ideas:

  1. You could derive your own QAbstractProxyModel that adds the "Select All" item to the data. This is probably the more complex option, but also the more efficient. An example of creating a proxy this way can be found here.

  2. You could also make your proxy in QML. It would look something like this:

Combobox {
    model: ListModel {
        id: proxyModel
        ListElement { modelData: "Select All" }

        Component.onCompleted: {
            for (var i = 0; i < customListModel.count; i++) {
                proxyModel.append(customModel.get(i);
            }
        }
    }
}
like image 54
JarMan Avatar answered Mar 04 '23 12:03

JarMan