Can't use a c++ signal in QML



  • I have tried to receive a signal from a c++ class to QML, without any success. I have followed the tutorial provided by QT
    [http://doc.qt.io/qt-5/qtqml-cppintegration-exposecppattributes.html](link url).

    My code:
    The main class (c++)
    int main(int argc, char *argv[])
    {
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    Manager manager;
    QQmlApplicationEngine engine;
    
    qmlRegisterType<Manager>("costa.manager", 1, 0, "Manager");
    
    engine.rootContext()->setContextProperty("manager",&manager);
    engine.load(QUrl(QLatin1String("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;
    
    return app.exec();
    

    }

    Class Manager .h with the signal:

    class Manager : public QObject
    {
    Q_OBJECT

    public:
    explicit Manager(QObject *parent = nullptr);

    signals:
    void isVechicleConnected(const bool &b);

    ...
    }

    Class Manager .cpp

    void Manager::isConnected(const bool &b)
    {
    qDebug() << "signal"; //to check if i'm sendding the signal
    emit isVechicleConnected(b);
    }

    QML main:

    import QtQuick 2.7
    import QtQuick.Controls 2.0
    import QtQuick.Layouts 1.3
    import QtQuick.Controls.Material 2.0
    import costa.manager 1.0

    ApplicationWindow {

    ...
    Manager{
    onIsVechicleConnected: {
    console.log("Connected!!!" + b)
    }
    }
    ...
    }

    How to fix it ?

    thanks !



  • @JorgeCosta87 Now you create a new object of type Manager in main.qml. Remove that. You don't need to register the type. Instead, the object named 'manager' is a context property and is globally available in your QML code. You need to use Connections to catch the signal:

    Connections: {
    target: manager
    onIsVehicleConnected: {}
    }
    

    BTW, the signal is weirdly named. E.g. QGamepad has the "connected" property and "connectedChanged" signal, and "onConnectedChanged" would be the event handler in QML. "isConnected", judged by its name, should be a query method which doesn't send a signal. I recommend making "connected" a real property. I have something like this in a project:

    ...
    Q_OBJECT
    Q_PROPERTY(bool connectedStatus MEMBER m_connected NOTIFY connectedStatusChanged)
    ...
    private: bool m_connected;
    ...
    signals: void connectedStatusChanged(bool connected);
    


  • @Eeli-K said in Can't use a c++ signal in QML:

    onConnectedChanged

    Thanks a lot!
    True, makes much more sense that name.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.