[SOLVED] C++ signal to QML slot in Qt


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


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


I think it would be best if you check this tutorial:


especially this section:


I think your mistake in this case might either be that you didn’t declare it as a slot or you didn’t make it invocable. Both options are explained in the Qt Tutorial.

Also, you need to use a QVariant in order to exchange data between C++ and QML.
You can also register types, e.g. Widgets and stuff, so that you can use them in QML as a “native” type like a rectangle. In most cases this is not recommended, except if you need some certain extern class or some data that you cannot display otherwise in your QML Interface.

The reason for the QVariant is the Script based approach of QML. The QVariant basically contains your data and a desription of the data type, so that the QML knows how to handle it properly. That’s why you have to specify the parameter in QML with String, int etc.. But the original data exchange with C++ remains a QVariant

I have used the qmlRegisterType before, but it is a very inconvenient Solution for simple data types. It is rather used for more complex data, such as custom Widgets, Canvas or Video elements that QML does not natively support or extended QStandardItemModels . It is a more convenient way to exchange data between QML and C++ and does not need Signals or Slots in first instance, because the QStandardItemModel updates the GUI automatically. For using the QStandardItemModel you need to register the Type with qmlRegisterType.. . The Model can then be used in Model based Views such as the ListView etc.

I attached a tutorial for this topic, it describes how to use the QListModel.


Answered By – mmoment

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *