3

My aim is to show angle and length values at ui. However I am not even able to reach that variable from qml file and forward it to the console. I have implemented this topic but no hope. I need help!

controller.h

#ifndef CONTROLLER_H
#define CONTROLLER_H

#include <QObject>

struct MyStruct {
    float angle;
    uint16_t length;
};


class Controller : public QObject
{
    Q_OBJECT
public:

     explicit Controller(QObject *parent = nullptr);
     MyStruct plate;

};

#endif // CONTROLLER_H


main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <controller.h>
#include <QtQml>
#include <qquickview.h>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    Controller ctrl;
    QQmlContext *ctx=engine.rootContext();
    ctx->setContextProperty("controller", &ctrl);
    engine.load(url);

    return app.exec();
}


main.qml

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.0

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Button{
        onClicked: {
            console.log(controller.plate.length)
        }
    }


}


Yunus Temurlenk
  • 4,085
  • 4
  • 18
  • 39
neutri
  • 47
  • 1
  • 9

1 Answers1

3

Since your Controller class inherits from QObject, it should be accessible from QML. But the MyStruct type will not as is, be because it is not derived from QObject. For lightweight objects (which don't need signals/slots) you can use the Q_GADGET macro instead, which will provide the support required for participating in the runtime system and support reflection.

struct MyStruct {
    Q_GADGET
    public:
        float angle;
        uint16_t length;
};

This will enable you to access MyStruct members in QML. Though if you want to create new instances, you would need to make it derive from Object and register it with qRegisterMetaType as described in How to create new instance of a Q_GADGET struct in QML?

gavinb
  • 19,278
  • 3
  • 45
  • 60