Nelson P Nelson P - 1 month ago 17
C++ Question

How to set a pure C++ object instance in a QQuickItem

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
?


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..

Answer

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:

  • have the instance as a static member of the MyQuickItem class, initialize it in main.cpp before you create the QML application, then you can access it from inside MyQuickItem in C++.

  • have the instance inherit QObject and expose it as a context property, this way it can be accessed from QML.

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.

Comments