Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters from C++ to QML

I want to pass some parameters from C++ to QML, so that QML can do something with them.

Somewhat like this:

void MyClass::myCplusplusFunction(int i, int j)
{
    emit mySignal(i, j);
}

In QML, every time that mySignal(i, j) is emitted, I want to call a QML function and do stuff with i and j.

Connections {
    target: myClass
    // mySignal(i, j) is emitted, call myQmlFunction(i,j)
}

How would I go about doing that?

like image 917
Don Joe Avatar asked Oct 30 '22 03:10

Don Joe


1 Answers

Let's say you have a signal in cpp side:

void yourSignal(int i, QString t)

You have two options:

  • register your class as a qml type and use it as a qml object. The object will be initialized from QML side. reference:

    qmlRegisterType<ClassNameCPP>("com.mycompany.qmlName", 1, 0, "ClassNameQml");

Then, in qml:

import QtQuick 2.9
import com.mycompany.qmlName 1.0

Item{
    ClassNameQml{
        id: myQmlClass
        onYourSignal: {
            console.log(i,t); // Do whatever in qml side
        }
    }
}
  • add your class as a qml variable. This option is preferred when you need reuse your object several times. reference:

    view.rootContext()->setContextProperty("varName", &cppObject);

Then, in qml:

import QtQuick 2.9
Item{
    Connections{
        target: varName
        // In QML for each signal you have a handler in the form "onSignalName"
        onYourSignal:{
            // the arguments passed are implicitly available, named as defined in the signal
            // If you don't know the names, you can access them with "arguments[index]"
            console.log(i,t); // Do whatever in qml side
        }
    }
}
like image 60
albertTaberner Avatar answered Nov 15 '22 07:11

albertTaberner