Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Connecting the index of a combobox to a model



  • Hi

    I'm trying out the model/view pattern in Qt and while it worked wonders for listviews, I can't seem to get it to work quite as I want with comboboxes.

    I set the combobox to use the model of a QStringListModel, which properly populated the combobox with values. But I want the selected option in the combobox to also be stored in the model, so that it can be changed from other parts of the gui/some internal functionality.

    I could make my model register all comboboxes when they're constructed and then later on update them manually with the setCurrentIndex method, but this feels like breaking the model/view pattern and missing out on core part of the built-in functionality.


  • Moderators

    @Mikkel said in Connecting the index of a combobox to a model:

    I could make my model register all comboboxes when they're constructed and then later on update them manually with the setCurrentIndex method, but this feels like breaking the model/view pattern and missing out on core part of the built-in functionality.

    You can subclass QStringListModel and add this information there.

    This is not breaking model/view pattern - by default the model does not know anything about any view(s), so it also can't know which index is selected. But if you need this information - sure you can add it to the model, it's not forbidden ;-)



  • @sierdzio
    Thank you for the response.
    So i set up a custom model and overload the data/rowCount methods.
    Would I then need to set up a delegate to make the indexChanged edit the value in my model and vice versa make my model set the index in the combobox?


  • Moderators

    @Mikkel said in Connecting the index of a combobox to a model:

    @sierdzio
    Thank you for the response.
    So i set up a custom model and overload the data/rowCount methods.
    Would I then need to set up a delegate to make the indexChanged edit the value in my model and vice versa make my model set the index in the combobox?

    Depends on how you want to do it, I don't have a "best practice" recommendation here.

    Either allow current index to be modified in setData() and read by data(), or make the index a property of the model and set it more automatically through your combobox (when current index is changed - set the property. When combo box is instantiated - read the property; etc.).



  • If you use the the same model instance in more than one place they will always have the same index. This may, or may not be what you want. FYI