Daniel Burnham Daniel Burnham -4 years ago 187
C++ Question

Accessing instances of a class from qml context

I am new both QT and QML. I have a class, which instantiates subclasses. I would like to expose the methods within these subclasses to my UI with some qml binding.

For example

class MainClass: QObject
{
Q_OBJECT
Subclass subclass;
MainClass();

}

class Subclass:QObject
{
Q_Object
Subclass();

public slots:
void someMethod();
}


Main.C

int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQuickView *view = new QQuickView;
MainClass mainclass;
view->rootContext()->setContextProperty("MainClass", &mainClass);
view->setSource(QUrl("qrc:/main.qml"));
view->show();
}


In this case I would like to access mainclass.subclass.someMethod() from within the QML UI.

Is there a good way to do this? Should I provide wrapper methods in MainClass for each function/property I would like to access.

Answer Source

It is possible by making SubClass a property of MainClass. For example:

class MainClass : public QObject
{
    Q_OBJECT
    Q_PROPERTY(SubClass *subClass MEMBER subClass CONSTANT)

public:
    MainClass();

private:
    SubClass *subclass;
};

These are called "grouped properties" in QML.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download