How to set value to model property in Qt Quick QComboBox in c++ during run-time
-
I want to populate the list of Dropdown box (QComboBox) from the Http response during run-time. Most of the internet resources suggests to use setInitialProperties() method in main() method.
This is my attempt: I have created my own model by sub-classing QAbstractListModel and I believe I've implemented all the required methods correctly. And then I set the model to the QComboBox QObject using setProperty() method.
class DataObject { private: QString m_text, m_value; public: DataObject(QString text, QString value); const QString& getText() const; const QString& getValue() const; };
class DataObjectModel : public QAbstractListModel { Q_OBJECT public: explicit DataObjectModel(QObject *parent = nullptr); // Basic functionality: int rowCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; QHash<int, QByteArray> roleNames() const; enum DataObjectRoles { TextRole = Qt::UserRole + 1, ValueRole }; Q_INVOKABLE void push(const QString &text, const QString &value); Q_INVOKABLE void print(); private: QList<DataObject> m_dataObjects; };
During run-time, a slot is invoked after Http response is received and data is parsed and added to User-defined model. Then I'm trying to set that user-defined model to QComboBox like this :
DataObjectModel model; foreach(...){ ... model.push(text,value); } QObject* snapshotsDropdown = screen01RootQObject->findChild<QObject*>("snapshotDropdown",Qt::FindChildrenRecursively); if(snapshotsDropdown != nullptr){ snapshotsDropdown->setProperty("model", QVariant::fromValue(&model)); }
Problem : But the QComboBox shows empty list to select from. The drop-down list is not updated.