-1

I want to populate a QComboBox defined in QML from my C++ code. I have seen two possible ways to do this:

  1. Define a list (as a QStringList for example) from the C++ code, and expose it as Q_ELEMENT. Then access that list from the C++, by saying model: backend.qlist assuming the list is defined in backend. Or
  2. Find the QComboBox in the C++ code by using view.rootObject()->findChild(). Then use addItem() to populate the list.

What is best practice?

zara
  • 109
  • 1
  • 5

2 Answers2

2

By far the first option!

QML stands for Qt Modeling Language, following the model-view architecture, in which the model (here C++) should not know anything about the view (QML).

Amfasis
  • 3,932
  • 2
  • 18
  • 27
  • _What is best practice?_ is clearly an opinion based question. The [tag wiki](https://stackoverflow.com/tags/qt/info) says: _Please, do not answer poor questions that will likely get closed or even deleted later. We are aiming for high-quality in this tag, thus we do not wish to encourage poor questions by feeding them with answers._ – scopchanov Nov 27 '20 at 15:32
  • 1
    @scopchanov you certainly have a point, but I think I also have a point in answering this as the second option is of the category "it is possible, why not use it", while it will certainly lead to bad, unmaintainable code. But in retrospect, I might have better put a comment – Amfasis Nov 30 '20 at 10:47
1

The first option works very well. The implementation is easy. From C++ side create a method to return a list:

QVariantList getList()
{
    QVariantList list;
    
    list << "Op1";
    list << "Op2";
    list << "Op3";
           
    return list;
}

And then call the method by QML like this:

comboBoxReader.model = backend.getList()
Adriano Campos
  • 1,121
  • 7
  • 14