5

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.

Claudia_letsdev
  • 273
  • 4
  • 9

1 Answers1

3

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.

Kakadu
  • 2,837
  • 19
  • 29
  • 1
    Oh sorry that was a mistake as I tried something. In the original version the transfer parameters are the same. Also in this way is no message. The cppSlot fuction is not executed. If a cast with dynamic_cast there is a error:: error: cannot dynamic_cast '((MainWindow*)this)->MainWindow::view->QQuickView::rootObject()' (of type 'class QQuickItem*') to type 'class QObject*' (source is a pointer to incomplete type) QObject *rect = dynamic_cast(view->rootObject()); Do you have another idea? – Claudia_letsdev Oct 28 '13 at 08:29
  • @Claudia_letsdev I had the same error due to missing `#include ` – Alex44 Jun 19 '18 at 08:31