I have this class:
//main_model.hpp
#ifndef MAIN_MODEL_H
#define MAIN_MODEL_H
#include <QObject>
#include <QVariantMap>
class MainModel : public QObject
{
Q_OBJECT
Q_PROPERTY(QVariantMap map READ map NOTIFY mapChanged)
public:
MainModel();
const QVariantMap& map() const { return m_map; }
signals:
void mapChanged();
private:
QVariantMap m_map;
};
#endif // MAIN_MODEL_H
And in main_model.cpp:
#include "main_model.hpp"
MainModel::MainModel()
{
m_map.insert("KEY1", "VALUE1");
m_map.insert("KEY2", "VALUE2");
m_map.insert("KEY3", "VALUE3");
emit mapChanged();
}
I have registered the MainModel class as mainModel through the QML engine, then in main.qml
Window {
height: 640
width: 360
visible: true
ComboBox {
height: parent.height * 0.1
width: parent.width * 0.5
anchors.centerIn: parent
model: mainModel.map // This is not working
}
}
I would like to show in the ComboBox the values of the map -> ["VALUE1","VALUE2","VALUE3"], and when the ComboBox selection changes I would like to log which key was chosen. Is this possible?
ComboBoxreally needs something a list such asQQmlListProperty,QAbstractListModel(including QML ListModel), or aQList(e.g.QVariantList). Because you're using aQVariantMapit doesn't work because it is not list-like or array-like.QVariantMapbehaves like a JavaScript object, so a quick fix would be to convert the JavaScript object to an JavaScript array using one of the following:Object.values(),Object.keys()orObject.entries. For example:I know you're instantiating MainModel and assigning it directly to the context property, but, in general, the constructor of a QObject component should also support a QObject* parent property, e.g.
And the implementation, of course, should also do something with that parameter, e.g.
Another quick fix would be to replace
QVariantMapwithQVariantList. In the following example, I also updated theQ_PROPERTYto use the default getter by usingMEMBERinstead ofREADthus reducing the need to implement a custom getter.