0

I'm trying to transfer some QString from c++ to QML. Here are the steps I've done so far.

  1. Created a class inherited from QObject and defined signal in it.
class exampleClass: public QObject {

Q_OBJECT

signals:
void mySignal (QString myStr);

}
  1. Somewhere in the class implementation, I emit the signal i.e.
void exampleClass::exampleFtn( . . . ){
.
.
qDebug("Before transmitting Signal");        // This gets triggered
emit mySignal ("Hello from CPP");

}
  1. In my main.cpp, I've initialized the class and expose it to QML i.e.
int main(...) {

.
.
exampleClass *exampleObj= new exampleClass(&app);
Engine.rootContext()->setContextProperty("exampleObj",  exampleObj);
}
  1. And finally, in QML i have connected the signal i.e.
Window {

.
.
Connections {
        target: exampleObj
        function mySignal(myStr) {
            console.log("signal from C++ recieved !")    // Doesn't get triggered
            console.log(myStr)                           //  Doesn't get triggered
        }
    }
}
noob_user
  • 87
  • 7
  • 1
    The signal on the QML side would be `onMySignal`. Where do you call `exampleClass::exampleFtn`? Are you sure you*re calling it? https://stackoverflow.com/a/66617238/525038 – iam_peter Aug 04 '23 at 07:13
  • function onMySignal(..) worked. One has to capitalize the first alphabet, I get it now. thanks – noob_user Aug 04 '23 at 07:25

1 Answers1

0

The syntax for connecting to a signal named foo in Connections is function onFoo() { ... }. In your case it would then be :

Connections {
    target: exampleObj
    function onMySignal(myStr : string) { // the type annotation doesn't hurt
        console.log("signal from C++ received !")
        console.log(myStr)
    }
}
GrecKo
  • 6,615
  • 19
  • 23