Changlin
Changlin

Reputation: 39

Fail To Connect Qml signal to C++ Slot

I have been trying to connect signal between Qml file and c++, but public slot in c++ doesn't seem to receive the signal. What might be wrong with my program?

main.qml

Item{
    id:item
    signal qml_signal
    Button{
        onClicked: {
            item.qml_signal();
        }
    }
}

main.cpp

QQuickView view(QUrl("qrc:/main.qml"));
QObject *item = view.rootObject();
Myclass myclass;
QObject::connect(item, SIGNAL(qml_signal()), &myclass,SLOT(cppSlot()));

myclass.h

void cppSlot() ;

myclass.cpp

void Myclass::cppSlot(){
    qDebug() << "Called the C++ slot with message:";
}

Upvotes: 0

Views: 429

Answers (1)

eyllanesc
eyllanesc

Reputation: 243965

When you want objects to interact between C++ and QML, you must do it on the QML side, since obtaining a QML object from C++ can cause you many problems, as in this case, the signal created in QML can not be handled in C++.

The solution is to export your object myclass to QML and make the connection there:

main.cpp

#include "myclass.h"

#include <QGuiApplication>
#include <QQuickView>
#include <QQmlContext>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    QQuickView view(QUrl("qrc:/main.qml"));
    Myclass myclass;
    view.rootContext()->setContextProperty("myclass", &myclass);

    view.show();
    return app.exec();
}

main.qml

import QtQuick 2.9
import QtQuick.Controls 1.4

Item{
    id:item
    signal qml_signal
    Button{
        onClicked: item.qml_signal()
    }
    onQml_signal: myclass.cppSlot()
}

Upvotes: 1

Related Questions