문제

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

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top