From QList<MyCLass> by property value to QML property
-
Is it possible in QML to get a reference to a object inside QList, which is first populated in C++?
Can the reference to C++ class instace inside QList be kept in QML property variable?
For example, QList has 100+ Person class instances, and I want to create a button, of which text is set by Person.name and button click value writes something into some Person property. I want to refer only to some certain instance inside QList, not by it's id but by the instance property value (or find it's id first then get it).
What I would like to do is something like this: (see the "referenceexamples" "valuesource" example.Button { id: jack_button property Person boy: BirthdayParty.getGuestByName("Jack Smith") text: boy.shoe.color? boy.name + ": " + boy.shoe.color : "Waiting for Jack..." onClicked: { // Toggle shoe.color black/red boy.shoe.color = boy.shoe.color=="back"? "red" : "black"; } }
Button then has either text "Waiting Jack..." or "Jack Smith: red" or "Jack Smith: black"
In all examples the QList is populated from QML but in real life app it would probably be populated in C++ from Web API data for example.
The QList might not have Boy or Person instance with name="Jack Smith" which should affect the Button state accordingly (disable it or something)https://code.qt.io/cgit/qt/qtdeclarative.git/tree/examples/qml/referenceexamples/valuesource/birthdayparty.h?h=5.12
https://code.qt.io/cgit/qt/qtdeclarative.git/tree/examples/qml/referenceexamples/valuesource?h=5.12 -
Ah, seems it is working fine with Q_INVOKABLE added to the getter method, and using engine.rootContext()->setContextProperty
public: Q_INVOKABLE Person* getGuestByName(QVariant name); ..... Person* BirthdayParty::getGuestByName(QVariant name) { QList<Person*>::iterator i; for (i = this->m_guests.begin(); i != this->m_guests.end(); ++i) { if ((*i)->name() == name) { return *i; } } return nullptr; } //main.cpp BirthdayParty parties; QQmlApplicationEngine engine; engine.rootContext()->setContextProperty("parties", &parties); //example.qml Button { id: jack_button property Person boy: parties.getGuestByName("Jack Smith") }