After the hint from Andrej I decided to realize my goal of having both the qml representation and a C++ rendering class by creating a wrapper class which derives from QQuickPaintedItem and by this overriding the paint method. With this I can render into the item in code. The item is used in my main qml file.
It is a wrapper class because it loads the qml file I want to show through a QQmlComponent which creates the QuickItem I want to show, too. I do this by setting the parent of the loaded/created item to my wrapper class.
So in my QuickPaintedItem class (best done in classbegin, when engine is already initialized):
QQmlComponent component(engine,QUrl("qrc:/myqml.qml"));
QObject* object = component.create();
QQuickItem* quickItem = qobject_cast<QQuickItem*>(object);
quickItem->setParentItem(this);
Then myqml.qml is rendered and my paint method, too. And I have a central place where I can use both.
After the comments from Velkan, another way is to put the loading of the component in a Loader qml item:
Wrapper { Loader{ onQmlChanged: source = newQml } }
where onQmlChanged would be a slot which consumes a signal:
signal onQmlChanged(string newQml);
I cannot say which way is better performance wise. Defining the structure in qml seems easier and cleaner. A difference to the code version, is that it loads the item at creation time of the Wrapper, so during the creation of the main.qml and before it is shown.
MyPaintedItem { Rectangle{} }
and save it intoMyPaintedItemWithRectangle.qml
. Then use theMyPaintedItemWithRectangle
type. – Velkan