Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting a signal from QML to Qt 5.1

I would like to connect a qml signal to a qt slot with qt 5.1. I can't use DeclarativeView in this Version of qt. My qml element is a simple rectangle and on the onClicked event starts the signal.

Rectangle{
    id:test
    width:  200
    height: 50
    x: 10
    y: 10
    signal qmlSignal()
    MouseArea {
        hoverEnabled: false
        anchors.fill: parent
        onClicked: {

            console.log("geklickt")
            test.qmlSignal()


        }
}

I have a class SignalslotlistView with this header:

class SignalslotlistView: public QObject{
Q_OBJECT
public slots:
void cppSlot(const QString &msg);

};

and the .cpp

void SignalslotlistView::cppSlot(const QString &msg) {

qDebug() << "Called the C++ slot with message:" << msg;}

And in the MainWindow class i try to set the connection:

view->setSource(QUrl::fromLocalFile("main.qml"));
QObject *object = (QObject *)view->rootObject();
QObject *rect = object->findChild<QObject*>("test");

SignalslotlistView myClass;
    QObject::connect(rect, SIGNAL(qmlSignal()),
                     &myClass, SLOT(cppSlot()));

view is from type QQuickView.

But nothing is happened. Thank you.

like image 663
Claudia_letsdev Avatar asked Oct 20 '22 22:10

Claudia_letsdev


1 Answers

Claudia, your main problem is that QML signal type is incompatible with slot type. I have fixed it using signal qmlSignal(string msg) and in main.cpp:

QObject *rect = dynamic_cast<QObject*>(view->rootObject());
SignalslotlistView myClass;
QObject::connect(rect, SIGNAL(qmlSignal(QString)),
                 &myClass, SLOT(cppSlot(QString)));

Now I can receive QML signals in C++ side.

like image 151
Kakadu Avatar answered Oct 30 '22 13:10

Kakadu