PDA

View Full Version : Calling QML functions from C++



neda
8th March 2016, 10:18
Hi,
I use this code in "main.cpp" and that is Ok.
But I do not know How can I use this code in another c++ class.
When I put this code in another class (for example myserialport.cpp), program does not work.



int main(int argc, char *argv[])
{
QApplication app(argc, argv);

QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

QObject * object = engine.rootObjects().value(0);

QVariant returnedValue;
QVariant msg = "Hello from C++";
QMetaObject::invokeMethod(object, "myQmlFunction",
Q_RETURN_ARG(QVariant, returnedValue),
Q_ARG(QVariant, msg));

return app.exec();
}

anda_skoa
8th March 2016, 10:35
It is usally a bad idea to call a QML function from C++.
Why do you want to do that?
Do you need the functions return value?

Cheers,
_

neda
8th March 2016, 10:58
It is usally a bad idea to call a QML function from C++.
Why do you want to do that?

_

Thank you,
I want to change source icon of toolbutton, show dialog with specific message , change value of several property and enable or disable controls (TextField,GroupBox , ....).



Do you need the functions return value?

_
No

anda_skoa
8th March 2016, 12:05
That all sounds like it would be better handled on the QML side, reacting to changes of C++ data.

But maybe you can post the function you are attempting to call?

Because needing the return value is basically the only use case where one would even consider a C++ -> QML dependency and even that often has better alternatives.

Cheers,
_

neda
9th March 2016, 05:03
Thank you,
I have this code in "MySerialPort" class:

void MySerialPort::readData()
{
QByteArray data = serial->readAll();
if(data[0]=='0') // For example
Show qml dialog
if(data[1]=='1') // For example
disable GroupBox

...
...
}

How can I handled this code on the QML side?

anda_skoa
9th March 2016, 10:01
The usual way is to have a property on a C++ object that is exposed to QML.
I think we've already discussed this before.

In this case maybe an int or enum property.

QML then reacts to changes of that property the usual way, e.g. via property bindings.

Or you emit signals and handle these in QML, e.g. using a Connection element

Cheers,
_