문제

Let there be a C++ class which contains signals and some functions accessible from QML. Now, in order to access the members of that class in QML, I write something like:

myClass
{
   id: abc

   x: 100    
   onXChanged: {console.log ("xx");}
}

Assuming x is a member of the actual C++ class, the above code does work.


Now, I have an object of the C++ class i.e. myClass created in a relevant C++ file.

Question:
Instead of creating a new object of the same class in QML, is it possible and sensible to access and use the already created C++ object in QML?

도움이 되었습니까?

해결책

You can use context properties for this. You would be writing something like this:

...

MyClass myClassObject;
QQuickView view;
view.rootContext()->setContextProperty("myClassContextProperty", &myClassObject);
view->setSource(QUrl::fromLocalFile("main.qml"));
view->show();

...

and then you could access it in qml as follows:

Button {
    onClicked: myClassContextProperty.x = 100
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top