0

I try to implement cpp variables to qml using Q_PROPERTY. First, I have created Q_PROPERTY of float numbers xValue, yValue, and zValue in the header file.

fileio.h
...
    Q_PROPERTY(int xValue
               MEMBER xValue
               NOTIFY xValueChanged)
    Q_PROPERTY(int yValue
               MEMBER yValue
               NOTIFY yValueChanged)
    Q_PROPERTY(int zValue
               MEMBER zValue
               NOTIFY zValueChanged)
...

Then I also make them private and created their signal functions.

signals:
    void xValueChanged();
    void yValueChanged();
    void zValueChanged();

private:
    float xValue,yValue,zValue;

After that, I have assigned a changeable variable to these float numbers in fileio.cpp file

...
       xValue = (line.split(',')[0]).toFloat();
       yValue = (line.split(',')[4]).toFloat();
       zValue = (line.split(',')[5]).toFloat();
...

Lastly, I tried to use them in QML

    FileIO{
        id: dataCSV
        source: "qrc:/data.csv"
    }

    Component.onCompleted: {
        console.log(FileIO.xValue)

    }

but qml returnsundefined.

Now I have 2 main questions. The first is should I define a function that updates values of variables, because (as I know) in cpp it is not needed to create an update function. And the second one is, if the return doesn't cause from the lack of update function, what should I do to use and read these variables' values in qml?

0

1 Answer 1

1

Two things:

You need to emit the change such that the QML can become aware of the property change after you set the local variable

xValue = (line.split(',')[0]).toFloat();
emit xValueChanged();

Further, your C++ class, which derives from QObject needs to be exposed up to the QML as a named object and connected to it.

Typically, you have a code path that looks like this when you create the QQuickView:

TheModel model;  // a C++ Class that derives from QObject

QQuickView view(QUrl(QStringLiteral("qrc:/main.qml")));
view.create();
view.rootContext()->setContextProperty("model", &model);  // projects the C++ class instance of "TheModel" to QML and Javascript as a an object named "model"

Then in QML you can say this:

Component.onCompleted: console.log(model.xValue)

I have some sample code on my github as a minimal example of how to setup a connection between the QML and C++ Class.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.