[Qt-qml] How to create/display items in a QDeclarativeView

Alan Alpert alan.alpert at nokia.com
Tue Jul 20 04:33:10 CEST 2010


On Mon, 19 Jul 2010 18:21:46 ext Simon Pasch wrote:
> Hello,
> 
> I'm currently trying to create and display qml-objects from C++ (As
> you stated on
> http://doc.qt.nokia.com/4.7-snapshot/qdeclarativedynamicobjects.html this
> is the preferred method for hybrid qml/c++ applications)
> 
> Therefore I create a QDeclarativeView from a base-qml-file (containing
> the items displayed all the time. The base item is a rectangle).
> 
> QDeclarativeView *m_view  = new QDeclarativeView();
> m_view->setSource(QUrl::fromLocalFile("Base.qml"));
> m_view->show();
> 
> On specific events (on the c++ side) I want to display a dialog within
> this view. Currently I'm using the following code:
> 
> QDeclarativeComponent component(m_view->engine(),
> QUrl::fromLocalFile("Dialog.qml"));
> QDeclarativeItem *myItem =
> qobject_cast<QDeclarativeItem*>(component.create());
> myItem->setParentItem(qobject_cast<QDeclarativeItem*>(m_view->rootObject()
> ));
> 
> Is this the best approach to create dynamic objects from c++?

Yes.

You can possibly make it a little easier by having a parent item inside the 
base scene, to add the dynamic objects to (so that this item can be moved and 
animated and such separate from the root item). You can then access that item 
with m_view->rootObject()->findChild<QDeclarativeItem*>("dynamicParent") if you 
set the objectName property of that item to "dynamicParent".

Also note that you probably don't have to create dynamic objects from C++ in 
this case. You can just emit a signal in C++, and react to it in QML (for 
example having a loader load Dialog.qml). If you expose a QObject to the root 
context you can use the Connections element to react to any signals it emits.

-- 
Alan Alpert
Software Engineer
Nokia, Qt Development Frameworks



More information about the Qt-qml mailing list