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?
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With