How to load a custom QQuickItem from inside a library so that it gets registered & updated like other QQuickItems in the application

759 Views Asked by At

I have a MyQuickItem class derived from QQuickItem as below

// MyQuickItem.hpp
class MyQuickItem : public QQuickItem {

Q_OBJECT

public:
  MyQuickItem();
  virtual ~ MyQuickItem();

protected:
  QSGNode* updatePaintNode(QSGNode *, UpdatePaintNodeData *) override;
};

Following is MyQuickItem.qml.

import QtQuick 2.0
import MyQuickItem 1.0

Item {
MyQuickItem {
    id: my_quick_item
    objectName: "MyQuickItemObject"
    visible: false
}
}

Point to be noted is that all of above C++ & qml code is in a separate static library. And the library has a qrc which has MyQuickItem.qml in it. This library has access to the global QQmlApplicationEngine object of the app as well.

My question: How can I load MyQuickItem from inside my library so that it gets registered with QML like the other QQuickItems in app's main.qml?

I am trying something around the following way from inside my library in a C++ method called after main.qml is loaded by the application:

MyQuickItem * myItem = new MyQuickItem();
myItem->setParent(m_qml_engine->parent());
myItem->setParentItem(qobject_cast<QQuickItem*>(m_qml_engine->parent()));
QQmlEngine::setObjectOwnership(myItem, QQmlEngine::JavaScriptOwnership);

myItem->setHeight(500);    // But myItem is NULL here !!!
myItem->setHeight(500);    // But myItem is NULL here !!!

Firstly, I don't know how to link QUrl(QStringLiteral("qrc:/qml/MyQuickItem.qml")) to myItem pointer.

Secondly, doing the above does not seem to load MyQuickItem correctly as I don't get a call to updatePaintNode which I have overridden. I need the Qt/QML window system to call my MyQuickItem::updatePaintNode as I have important logic there.

So, How can I correctly load MyQuickItem from inside my library so that it gets registered & updated like other QQuickItems?

0

There are 0 best solutions below