Nominate our 2022 Qt Champions!

Calling QML functions from C++

  • 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;
        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();

    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 , ....) on the QML side from C++.
    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	

    Is there any solution to handling this code on the QML side?

  • From the C++ code, emit a signal based on what you've read from the serial port. The QML code catches the signals and does whatever is appropriate.

Log in to reply