C++ signal to QML slot in Qt

alex picture alex · Jan 12, 2012 · Viewed 77.9k times · Source

I want to send a Signal from C++ to a Slot in my QML File. I already got it working without and primitive type parameters, although if I want to send a QString to my QML Slot I get an error whilst connecting.

I connect in main.cpp

QObject *contentView = rootObject->findChild<QObject*>(QString("contentView"));
QObject::connect(&myObj,      SIGNAL(finishedGatheringDataForItem(QString)), 
                 contentView, SLOT(updateViewWithItem(QString)));

the relavant part of my qml File

Rectangle {
        objectName: "contentView"
        function updateViewWithItem(string) { console.log('got some Items'); }  // slot
}

Error:

Object::connect: No such slot QDeclarativeRectangle_QML_2::updateViewWithItem(QString)

Answer

Ken picture Ken · Mar 23, 2015

You should use Connections in this case (maybe it's the only way to connect).

  1. Put your object myObj to QML file by setContextProperty

    qmlVectorForm->rootContext()->setContextProperty("YourObject", myOb);
    
  2. Your signal is

    finishedGatheringDataForItem(QString signalString)
    
  3. In QML file, add Connectios likes below:

    Connections {
        target: YourObject 
        onFinishedGatheringDataForItem: {
            qmlString = signalString
        }
    }