[Development] On QML, ownership, QObject-trees and QSharedPointer
mardy at users.sourceforge.net
Wed May 23 13:16:12 CEST 2012
I don't have real answers for your questions, but just a piece of
On 05/23/2012 01:25 PM, Rene Jensen wrote:
> Question: How can we expose objects governed by QSharedPointer to QML
> safely? I *can* guarantee the lifecycle beyond the life of my
As neither of us knows exactly how QML handles QSharedPointer (my guess
is that it simply doesn't; QSharedPointer is a template class which can
be used with many other types than QObject, so I don't think that
exposing it in QML is trivial), I would simply recommend you not to use it.
I actually mentioned QSharedPointer in a recent blog post of mine ,
which you might find interesting especially if your use of
QSharedPointer is suggested by your previous experience with other toolkits.
If you really think that QSharedPointer is absolutely necessary in your
case (I still doubt), then just expose its QObject data to QML, since
you also claim that you can make sure its lifetime will survive the engine.
> These are the ways to transfer values/references from C++ to QML
> (let's ignore the other way around for now):
> A) By calling QDeclarative::setRootContext (ownership not transferred:
Note that you don't need to call setRootContext(); you can just get the
existing context (with QDeclarative::rootContext()) and call
setContextProperty() on it (maybe that's exactly the same you meant?).
> B) By calling QObject::setProperty on the instantiated component (ownership?)
> C) By QML calling a method on a C++ object and getting a response
> (ownership IS transferred to QML. In the docs somewhere.)
Sure? That would seem a bit weird to me: how can QML know whether the
object you return is a newly created one, or some object owned by some
other object (and what if the object is "const"?)?
> D) By QML accessing a Q_PROPERTY on a C++ object (ownership?).
E) Implement your own QDeclarative component in C++, which could wrap
your hard-to-expose-to-QML object, and let it implement properties and
methods which expose only data types that are safe and easy to use in QML.
As I said, I don't have the knowledge to reply to your other questions;
but my gut feeling is that if you need to know the answers, you have
already lost. :-) The key, IMHO, is to find a way to design your
software so that you use the toolkit to the extent that you rely only on
its well-documented properties. Refactoring your code and making it
simple will not only help you to make it work with QML, but also make it
easier for you to maintain it.
IMHO, whatever the answers to your questions, you should try to forget
them immediately or at least not rely on them. It will make your life
easier on the long run. :-)
http://blog.mardy.it <- geek in un lingua international!
More information about the Development