Home > OS >  C Signal is not received in QML slot
C Signal is not received in QML slot

Time:10-16

I have a C class that emits a signal. I want that signal to be delivered to QML. I set the object as a context property of qml application engine root context.

My C class

// Sample.h
class Sample : public QObject
{
    Q_OBJECT
public:
    explicit Sample(QObject *parent = nullptr);

public slots:
    void emitSomething();

signals:
    void emitted();

public slots:
};

And the implementation

// Sample.cpp
Sample::Sample(QObject *parent) : QObject(parent)
{
}

void Sample::emitSomething()
{
    emit emitted();
}

My main implementation. This is very similar to the code provided by qt creator.

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

    QGuiApplication app(argc, argv);

    Sample sample;
    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("obj", &sample);

    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    QTimer::singleShot(1000, &sample, &Sample::emitSomething);

    return app.exec();
}

The qml implementation is

import QtQuick 2.9
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Connections {
        target: obj
        onEmitted: function() {
            console.log("received")
        }
    }
}

When I run the code, emitSomething() slot is called, but I don't see emitted() signal in qml.

CodePudding user response:

I didn't have version 5.9, but I tried it with 5.10.1. In that case, the text did not get printed to the console. I fixed it by changing the syntax on the signal handler. (Just remove function().)

    Connections {
        target: obj
        onEmitted: {
            console.log("received")
        }
    }
  • Related