Call C++ function from QML



  • Hi

    I followed this example (http://qt-project.org/doc/qt-5.0/qtqml/qtqml-cppintegration-exposecppattributes.html) but I can't make it run.

    Can someone provide me a complete example of how call a c++ function from qml 2 (source code: cpp, qml, pro ).

    Thanks in advance.


  • Moderators

    Hi,

    Although there are lot of example's related to this, here's a super simple example which call cpp function from QML on mouse click.

    hellocpp.h

    @
    #ifndef HELLOCPP_H
    #define HELLOCPP_H

    #include <QObject>

    class HelloCpp : public QObject
    {
    Q_OBJECT
    public:
    explicit HelloCpp(QObject *parent = 0);
    Q_INVOKABLE void printMessage(QString txt);

    signals:

    public slots:

    };

    #endif // HELLOCPP_H
    @

    hellocpp.cpp

    @
    #include "hellocpp.h"
    #include <QDebug>

    HelloCpp::HelloCpp(QObject *parent) :
    QObject(parent)
    {
    }

    void HelloCpp::printMessage(QString txt)
    {
    qDebug() << "Message from QML: " << txt;
    }
    @

    main.qml

    @
    import QtQuick 2.0
    import HelloCpp 1.0

    Rectangle {
    width: 360
    height: 360

    HelloCpp {
        id: demo
    }
    
    Text {
        text: qsTr("Hello World")
        anchors.centerIn: parent
    }
    MouseArea {
        anchors.fill: parent
        onClicked: {
            demo.printMessage("Hello Cpp. Nice to see you");
        }
    }
    

    }
    @

    main.cpp

    @
    #include <QtGui/QGuiApplication>
    #include <QtQuick>
    #include "qtquick2applicationviewer.h"
    #include "hellocpp.h"

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

    qmlRegisterType<HelloCpp>("HelloCpp", 1, 0, "HelloCpp");
    
    QtQuick2ApplicationViewer viewer;
    viewer.setMainQmlFile&#40;QStringLiteral("qml/QMLTest/main.qml"&#41;);
    viewer.showExpanded();
    
    return app.exec();
    

    }
    @

    Just go through the code starting from main.cpp. Create a default QtQuick example from QtCreator and copy the above code to it.

    The explanation for the functions like qmlRegisterType and Q_INVOKABLE are already nicely documented. Please refer docs for more details.



  • Thanks p3c0, your example runs like a charm.

    :D


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.