Assigning QObject pointer works via assignment but not binding
-
wrote on 26 Oct 2022, 20:31 last edited by
I have something similar to the following code snippets. I am simplifying the code here for attempted brevity.
First, a subclass of QAbstractListModel with the following data() implementation, and Q_INVOKABLE get_thing() method, which returns a pointer to a QObject subclass, QML_thing
QVariant data(QModelIndex& index, int role) { const auto& thing = m_data.at(index.row()); // shared pointer to QML_thing switch(role) { case Qt::DisplayRole: return thing->name(); // this works case WholeThingRole: return QVariant::fromValue(QML_thing*>(thing.get()); } } QML_thing* getThing(int index) const { const thing = m_data.at(index); // shared pointer return thing.get(); }
Next, I have a Repeater in a QML file that has this code:
Repeater { id: repeater model: thingModel ThingDelegate { thing: wholeThing // This calls the role, but ends up being null } onItemAdded { item.thing = model.getThing(index) // this correctly assigns the QObject } }
My question is: why doesn't the "thing:" binding in QML work, but the "thing =" version does?
-
Example is not complete. Few things are not very clear what you are trying to achieve. If you can provide complete example it will help to see what is the issue.
I will try to answer your qn if this is what u r asking for.QVariant::fromValue(QML_thing*>(thing.get());
Above statement returns the copy of the object to QML. So after this there are two instance of 'thing' object.In case of get_thing(..) return the reference to object. Hence works.
-
wrote on 27 Oct 2022, 18:53 last edited by
Thank you for the response. What I am trying to accomplish is to set a property within ThingDelegate that corresponds to a QML_thing pointer, because that appears to be the only way to pass a QObject along with its properties into a piece of QML that calls those properties. ThingDelegate calls individual properties of the QML_thing, which is a C++ defined QObject.
I didn't think that QObjects allowed copies, but are you saying it is getting a copy of that pointer? If so, is there a way to pass the actual pointer via the data() call?
-
wrote on 28 Oct 2022, 20:10 last edited by
QVariant::fromValue<QObject*>(thing.get());
If your object is QObject based then return QObject. QML can still call slots, properties, and signals on the object just fine.
1/4