[Qt-qml] Accessing QML objects from C++

Alan Alpert alan.alpert at nokia.com
Thu May 27 13:36:43 CEST 2010


 Torsdag 27. mai 2010 16:38:42 skrev ext John Vilburn :
> If I create a QML object from C++ using the following code:
> 
> 	QDeclarativeEngine *engine = new QDeclarativeEngine( this );
> 	QDeclarativeComponent mainComponent(engine, QUrl("Main.qml"));
> 	QDeclarativeItem *mainQml = 0;
> 	if ( mainComponent.isReady() )
> 	{
> 		mainQml = qobject_cast<QDeclarativeItem
> *>(mainComponent.create(engine->rootContext())); }
> 
> and Main.qml creates a child QML object from the component in Toolbar.qml,
> is it possible for the C++ code to get a pointer to a QDeclarativeItem for
> the toolbar object and access values from that object? Or is there some
> other way for the C++ code to access values from the toolbar object?
> 
> Thanks,
> John
> 

If you set the objectName property (from QObject) on any of your objects in 
QML you can then access that object using the findChild method on the root 
object (also via QObject). This is the easiest way. In general though we 
recommend that you not make your C++ layer use knowledge of the internals of 
the QML files, so that you have more flexibility in rewriting the UI.

Note that it is not possible to make ids and objectNames match up 
automatically, they are conceptually different since ids are only valid in QML 
and objectNames are only valid on C++ instances.

-- 
Alan Alpert
Software Engineer
Nokia, Qt Development Frameworks



More information about the Qt-qml mailing list