Beginner Question: Connecting to QML Signals
-
Hey,
i try to connect cpp with QML and had a build Error that i can't resolve.
I copyed the code based on website (doc-snapshot.qt-project.org/5.0/qtqml/qtqml-cppintegration-interactqmlfromcpp.html)
Subtopic "Connecting to QML Signals"@// MyItem.qml
import QtQuick 2.0Item {
id: item
width: 100; height: 100signal qmlSignal(string msg) MouseArea { anchors.fill: parent onClicked: item.qmlSignal("Hello from QML") }
}@
@class MyClass : public QObject
{
Q_OBJECT
public slots:
void cppSlot(const QString &msg) {
qDebug() << "Called the C++ slot with message:" << msg;
}
};int main(int argc, char *argv[]) {
QGuiApplication app(argc, argv);QQuickView view(QUrl::fromLocalFile("MyItem.qml")); QObject *item = view.rootObject(); MyClass myClass; QObject::connect(item, SIGNAL(qmlSignal(QString)), &myClass, SLOT(cppSlot(QString))); view.show(); return app.exec();
}@
If i try to run it i get the error:
Error:C2440: 'Initialition': 'QQuickView' can not in 'QObject *' convert ***(i translate the error from german to english)Have any one a good tip to solve this ?
I try some variants with dynamic cast i found on stack overflow but without any success :(
Thank you for your help !
-
Signal does not belong to rootObject, but to "item" child.
Add this to QML:
@
id: item
objectName: "item"
@And this to c++:
@
// to get the object that defines the signal:
QObject *item = view.rootObject().findChild<QObject *>("item");
@ -
This is because view.rootObject() return QQuickItem * insted of QObject *. Unless you using sierdzio's suggestion.
-
Hello,
I am returning to this question to ask if the solution presented is the best way to connect qml signals to C++ slots.
Say, If in my code I load the main qml window, I will have to find each qml instance by name and connect to a slot?
Thank You
-
I have been trying to use the Qml-grid view in my code. I am on a mission to couple it with my C++ code which I have been in vain so far. I think my problem occurs when I try to generate the signal from the qml rectangle. I will definitely update you with the results once I have done with it.
"super-beta-prostate.com":http://www.super-beta-prostate.com