Search code examples
c++qmlsignals-slotsqt5.4

C++ Signal QML Slot on registered type


I'm trying to call a QML slot on a registered type by raising the signal in my C++ code. The slot never gets called.

in main.cpp I register the type:

qmlRegisterType<MsgController>("MyStuff",1,0,"MsgController");

in msgcontroller.h I declare the signal:

class MsgController : public QObject
{
    Q_OBJECT    
public:
...
signals:
    void msgReceived(const QString& msg);

in msgcontroller.cpp I raise the signal

void MsgController::setMsg(const QString &msg)
{    
    emit msgReceived(msg);
}

and in my main.qml file I've got the slot for msgReceived:

import MyStuff 1.0
MsgController {            
            onMsgReceived: {
                console.log("message received:"+msg);
            }          
        }

The onMsgReceived slot never gets called. Is there anything I've missed?


Solution

  • I hadn't realized that I had connected to the wrong instance of MsgController in my code. One instance was created by the C++ code, but I really wanted to call the slot on the instance created by the Qml Engine. Once I connected to the correct instance, the code above worked fine.