Question

I've registered a c++ class (class_name) in main.cpp like so:

#include "class_header.hpp"
#include <QtQuick/QQuickView>
#include <QGuiApplication>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    qmlRegisterType<class_name>("ClassInstance", 1, 0, "ClassInstance");

    QQuickView view;
    view.setResizeMode(QQuickView::SizeRootObjectToView);
    view.setSource(QUrl("qml/main.qml"));
    view.show();
    return app.exec();
}

I've determined that registering this class creates an instance of the object, of which I require only one. The QML side can access this instance just fine. How can I access the same instance from the C++ side, for example, in the main.cpp shown above?

Thanks in advance!!

Was it helpful?

Solution

qmlRegisterType does not create an instance. It registers the type ClassInstance with qml engine, so that you can create instances of ClassInstance in your qml. When you said you could access this instance in qml side, you were actually creating a new instance in qml and it is not accessible from c++.

If your intention is to create a single instance which could be accessed from both qml and c++, then what you need is a context property.

ClassInstance obj;
view.rootContext()->setContextProperty("myInstance", &obj);

Now you can access the same instance as myInstance in qml and as obj in c++ code. Documentation here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top