Qt World Summit: Register Today!

Connect QML signal to CPP slot, or method [SOLVED]

  • I want to establish a connection between CPP class methods and QML file, but i always get a strange errors, that i cant understand... Help me somebody !


    @#include <QApplication>
    #include <QQmlApplicationEngine>
    #include <QtDeclarative/QDeclarativeView>
    #include <QtDeclarative/QDeclarativeContext>
    #include <QGraphicsObject>
    #include <QDebug>

    class MyClass : public QObject
    public slots:
    void cppSlot(const QString &msg) {
    qDebug() << "Called the C++ slot with message:" << msg;

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

    //QQmlApplicationEngine engine;
    QDeclarativeView view(QUrl(QStringLiteral("main.qml")));
    QObject *item = view.rootObject();
    MyClass myClass;
    QObject::connect(item, SIGNAL(qmlSignal(QString)),
                          &myClass, SLOT(cppSlot(QString)));
    return app.exec&#40;&#41;;



    @import QtQuick 2.3
    import QtQuick.Controls 1.2

    ApplicationWindow {
    id: item
    visible: true
    width: 640
    height: 480
    color: "#ffffff"
    title: qsTr("Hello World")
    signal qmlSignal(string msg)

    Button {
        id: button1
        x: 27
        y: 37
        width: 97
        height: 61
        text: qsTr("Button")
        onClicked: item.cppSlot("Hello C++ from QML !!!")


    Trying to run this app, i get an errors like this:

    C:\Qt\PROJECTS\QML_with_C\main.cpp:24: error: undefined reference to `_imp___ZN16QDeclarativeViewC1ERK4QUrlP7QWidget'

    and this

    C:\Qt\PROJECTS\QML_with_C\main.cpp:8: error: undefined reference to `vtable for MyClass'

  • It looks like you're just experimenting and learning but I thought I would point out in case you don't know that: QML is automatically aware of Qt C++ slots so you could eliminate the QML signal, the QObject::connect statement (not to mention the curly braces in your onclicked handler). Your QML would just call the slot directly:

    @onClicked: myObj.cppSlot("Your message here.")@

Log in to reply