Integrating C++ struct in struct to QML
-
Hello, suppose that I have these struct in C++
enum CMOP_TYPE{ SOMETHINK, }; struct COMPONENTS{ CMOP_TYPE type;; int count; QString name; } struct MACHINE{ COMPONENTS a; QString name; };
Struct MACHINE is global struct in program. Now I would like to show data in qml.
I use this:
enum CMOP_TYPE{ SOMETHINK, }; struct COMPONENTS:public QObject{ Q_OBJECT public: Q_PROPERTY(int count MEMBER count NOTIFY valChanged) Q_PROPERTY(int type MEMBER type NOTIFY valChanged) Q_PROPERTY(QString name MEMBER name NOTIFY valChanged) CMOP_TYPE type; int count; QString name; signals: void valChanged(); } struct MACHINE:public QObject{ Q_OBJECT public: Q_PROPERTY(COMPONENTS * component MEMBER Get_component NOTIFY valChanged) Q_PROPERTY(QString name MEMBER name NOTIFY valChanged) COMPONENTS component; QString name; COMPONENTS * Get_component(){return &component}; signals: void valChanged(); }; /////////main.c FILE: QGuiApplication app(argc, argv); MACHINE data; QQmlApplicationEngine engine; const QUrl url(QStringLiteral("qrc:/main.qml")); engine.rootContext()->setContextProperty("global_data",&MACHINE); engine.load(url); return app.exec();
In this code I can access data from both struct. But I don't know if I did it the best way.
In QML file automatic complementation from second struct doesn't work ( I mean global_data.component.count ).I would like ask you, if exist some other approach to access nested structures. Imagine that COMPONENTS struct have 20 items (some of items is other struct).
Thank you
-
QtCreator will have a hard time giving you good auto-completion if you use setContextProperty. However, if you register your classes with
qmlRegisterType
(or one of the other qmlRegister functions), Creator's code model should learn about the types properties. Also, instead of using setContextProperty, consider using qmlRegisterSingletonInstance, or make the types creatable (normal qmlRegisterType function), and just set their values.