c++qtqmlqquickitem

How to get a C++ object instance of a QQuickItem on C++ side


I have QtApp & a pure C++ library. The C++ library exposes a one simple class called MyCppLibApiClass. The QtApp has a class which is embedded on main.qml. Following is the class:

class MyQuickItem : public QQuickItem {
  MyQuickItem();
}

Following the qml code for the quick item:

import MyQuickItem 1.0

MyQuickItem {
  id: myQuickItemID
  visible: true
  objectName: "myQuickItem"
}

Following is my main.cpp showing I load the qml item:

qmlRegisterType<MyQuickItem>("MyQuickItem", 1, 0, "MyQuickItem");
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml")));
return app.exec();

MyQuickItem needs access to MyCppLibApiClass instance. How do a I get a valid instance to MyQuickItem in main.cpp ? I need to set an object of MyCppLibApiClass as member in MyQuickItem. I can do this using a setter method. But, first of all I need to get a valid instance to MyQuickItem. So How to get access to MyQuickItem in main.cpp ?

EDIT:
I have searched quite a before asking this question. I read through this link. Also, This question posted by me, did not get me an accurate answer. Hence, rephrasing my question more clearly to try get an answer. Appreciate suggestions to this..


Solution

  • If you have a single instance of your library object, there are two ways you can go about it depending on what kind of access you need:

    If it is not a singleton object, you have two courses of action:

    However, as one of the answers of the questions you have liked suggests, this is not really considered recommended practice. There is probably a better way to do that, you shouldn't be doing setting QML object properties in main.cpp, it should be either in the constructor or public interface of MyQuickItem.