Converting code to new Qt5 syntax of connect
Unsolved
QML and Qt Quick
-
Hi,
here is a piece of my code:
QGuiApplication app(argc, argv); QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml"))); QmltoCpp *qmltocpp = new QmltoCpp(); // my C++/QML interface QObject *rootObject = engine.rootObjects().first(); QObject::connect(qmltocpp, SIGNAL(showMessage(QVariant)), rootObject, SLOT(showMessage(QVariant))); return app.exec();
I would like to update this to the new Signal/Slot syntax. But I have no idea how.
This doesn't work:
QObject::connect(qmltocpp, &QmltoCpp::showMessage, rootObject, &QObject::showMessage);
Do I need to subclass a QObject and create new class for my rootObject? Would it help at all?
-
@vlada said in Converting code to new Qt5 syntax of connect:
QObject::connect(qmltocpp, &QmltoCpp::showMessage, rootObject, &QObject::showMessage);
it doesn't work because the QObject class doesn't have a method with the signature
showMessage(QVariant)
You could cast the QObject to your class if you are sure that its of a certain type, if not it will crash.So the code might look like this:
MyType* rootObject = qobject_cast<MyType*>(engine.rootObjects().first()); QObject::connect(qmltocpp, &QmltoCpp::showMessage, rootObject, &MyType::showMessage);
alternatively (but with actually no benefit to the "old" syntax):
MyType* rootObject = qobject_cast<MyType*>(engine.rootObjects().first()); QObject::connect(qmltocpp, &QmltoCpp::showMessage, [rootObject](const QVariant & v) { QMetaObject::invokeMethod( rootObject, "showMessage", Qt::DirectConnection, Q_ARG(QVariant,v) ); });