← Back to team overview

ubuntu-phone team mailing list archive

Re: Create QML view for C++ object (not class)

 

Can I set only one object as context property that contains other objects
(and this objects contain objects too) and get this deep objects in QML?

For i.e. I have object of class Engine that has object of class Game, Game
contains object of Ship and Ship contains object of Reactor. So, I set
object of Engine as context property and in QML write:

engine.game.ship.reactor

Can I use it?


2013/9/30 Николай Шатохин <n.shatokhin@xxxxxxxxx>

> I've already found this solution:
> http://qt-project.org/doc/qt-5.0/qtqml/qtqml-cppintegration-contextproperties.html It
> helps. Thanks.
>
>
> 2013/9/30 Michael Zanetti <michael.zanetti@xxxxxxxxxxxxx>
>
>> On Sunday 29 September 2013 13:45:01 Vladimir M. wrote:
>> > Sounds like a "context property" use case (you plain set a QObject as a
>> > context property for a view's root scope, w/o even registering the
>> object's
>> > type, and all its properties and invokables become available).
>>
>> I don't recommend using context properties. While they are useful for some
>> cases, this one doesn't seem to be one of those. Using too many global
>> context
>> properties can make the code very ugly to work with.
>>
>> You probably want to create something like this:
>>
>> class ViewController: public QObject
>> {
>>   Q_PROPERTY(QList<MyClass> viewObjects READ viewObjects NOTIFY
>> viewObjectsChanged)
>> ...
>> QList<MyClass> viewObjects() const {
>>   return objectList;
>> }
>> ...
>> };
>>
>> qmlRegisterType<ViewController>(uri, 0, 1, "ViewController");
>>
>> Then in QML you can do something like this:
>>
>> ViewController {
>>   id: viewController
>> }
>>
>> Repeater {
>>   model: viewController.viewObjects
>>   MyView {
>>     property var viewObject: viewController.viewObjects[index]
>>   }
>> }
>>
>>
>> Note that if you want your code to adjust more flexible (i.e. the
>> viewObjects
>> change a lot), consider using a QAbstractListModel (or some other model)
>> instead of a QList.
>>
>> Hope this helps,
>> Michael
>>
>> >
>> > On Sun, Sep 29, 2013 at 6:38 AM, Николай Шатохин
>> <n.shatokhin@xxxxxxxxx>wrote:
>> > > Hello.
>> > >
>> > > When I create a class in C++, I can register it for QML and can create
>> > > view for it. It's very convenient. But, if I need many objects of the
>> same
>> > > type, and need to show few views on screen, I got problems.
>> > > Is it possible to register QML type for object, not for class?
>> > > If I change some object, I need to see only its view changed.
>> > >
>> > > Best regard,
>> > > Nick
>> > >
>> > > --
>> > > Mailing list: https://launchpad.net/~ubuntu-phone
>> > > Post to     : ubuntu-phone@xxxxxxxxxxxxxxxxxxx
>> > > Unsubscribe : https://launchpad.net/~ubuntu-phone
>> > > More help   : https://help.launchpad.net/ListHelp
>>
>>
>

Follow ups

References