[Interest] Dynamic QML menu from C++ data?
Murphy, Sean
smurphy at walbro.com
Mon Aug 28 19:17:33 CEST 2017
> Example copied from a random project
>
> https://gist.github.com/anonymous/2f803e7b49760b509d6a23c43901f52e
Thanks, can you show me what "modelData" is in your example, or how the .cpp side is laid out? I am using an Instantiator (and had been before I posted, based on something I stumbled across while searching for this), but I'm still missing some connection I need to make it work.
Alternatively, this is my current code:
In main.cpp, I add three test items to the menu:
QQmlEngine engine;
QQmlComponent component(&engine, QUrl("qrc:/qml/dashboard.qml"));
QObject* o = component.create();
settingsModel *model = o->findChild<settingsModel *>("model");
if (model)
{
qDebug() << "Adding items to model";
model->insertRow(0, new QStandardItem("one"));
model->insertRow(1, new QStandardItem("two"));
model->insertRow(2, new QStandardItem("three"));
} else {
qDebug() << "Invalid data model";
}
My settingsModel.cpp:
class settingsModel : public QStandardItemModel
{
Q_OBJECT
public:
explicit settingsModel(QObject *parent = 0);
private:
QStringList mPorts;
};
And then in my dashboard.qml:
SettingsModel {
id: settingsModel
objectName: "model"
}
Menu {
id: settingsMenu
Instantiator {
model: settingsModel
onObjectAdded: {
settingsMenu.insertItem(index, object)
console.log("QML: object added: " + object.text + ", index= " + index);
}
onObjectRemoved: {
settingsMenu.removeItem(object)
console.log("QML: object removed: " + object.text);
}
delegate: MenuItem {
text: "test"
}
}
}
When I used your example verbatim, I got the error:
qrc:///qml/dashboard.qml:93: ReferenceError: modelData is not defined
and I didn't get any menu items in the menu. When I run what I've attached, I do get a menu that has three entries, all labeled "test". Which makes sense based on what I have in there. So at least it seems like the calls to the model's insertRow() are triggering the Qml side to add items to the menu, but I just don't know what I'm supposed to change the text line below
delegate: MenuItem {
text: "test"
}
To get the menu to pick up the model item's string for that item?
Sean
More information about the Interest
mailing list