[Interest] QML ObjectOwnership for List of QObjects

Oleg Evseev ev.mipt at gmail.com
Sun Dec 10 23:12:18 CET 2017


For now I stopped at this solution:

Create QObjectListModel class (QObject) that can setList(QList<QObject*>)
saving list to private variable and doing parent all objects to *this*, and
also getList() for QML. And in QML:

ComboBoxCheck {
       property QObjectListModel listModel: MainClass.workers()
       model: listModel.list()
}

Property is needed to maintain pointer to QObjectListModel (QObject) so it
will not be deleted until destruction of Item (ComboBox).
So in this case QML is control lifetime of QObjects in list. And this what
I needed for now in fact.

But maybe there are other more pretty solutions?

2017-12-10 18:05 GMT+03:00 Oleg Evseev <ev.mipt at gmail.com>:

> Hi all,
>
> Could someone explain QObject ownershiping aspects, please.
>
> According to http://doc-snapshots.qt.io/qt5-dev/qtqml-cppintegration-data
> .html when data is transferred from C++ to QML, the ownership of the data
> always remains with C++. The exception to this rule is when a QObject is
> returned from an explicit C++ method call.
>
> And it works for c++ functions that return "single" QObject*.
>
> But what to do with QObjectList-based models (
> https://doc-snapshots.qt.io/qt5-5.9/qtquick-modelviewsdata-cppmodels.html)?
> Let say in c++ application creates list of new objects:
> Q_INVOKABLE QList<QObject *> workers();
> and qml set this as the model for ListView or Combobox.
>
> But these objects will never be destroyed. How to force qml own this
> objects properly?
>
> I did try QQmlEngine::setObjectOwnership(list[i],
> QQmlEngine::JavaScriptOwnership) in loop before returning list, but qml
> can destroy them immediately despite that Combobox is still displayed.
>
> --
> With regards, Oleg.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20171211/7bfbc10d/attachment.html>


More information about the Interest mailing list