I would like to connect a qml signal to a qt slot with qt 5.1. I can't use DeclarativeView in this Version of qt. My qml element is a simple rectangle and on the onClicked event starts the signal.
Rectangle{
id:test
width: 200
height: 50
x: 10
y: 10
signal qmlSignal()
MouseArea {
hoverEnabled: false
anchors.fill: parent
onClicked: {
console.log("geklickt")
test.qmlSignal()
}
}
I have a class SignalslotlistView with this header:
class SignalslotlistView: public QObject{
Q_OBJECT
public slots:
void cppSlot(const QString &msg);
};
and the .cpp
void SignalslotlistView::cppSlot(const QString &msg) {
qDebug() << "Called the C++ slot with message:" << msg;}
And in the MainWindow class i try to set the connection:
view->setSource(QUrl::fromLocalFile("main.qml"));
QObject *object = (QObject *)view->rootObject();
QObject *rect = object->findChild<QObject*>("test");
SignalslotlistView myClass;
QObject::connect(rect, SIGNAL(qmlSignal()),
&myClass, SLOT(cppSlot()));
view is from type QQuickView.
But nothing is happened. Thank you.
Claudia, your main problem is that QML signal type is incompatible with slot type. I have fixed it using signal qmlSignal(string msg)
and in main.cpp
:
QObject *rect = dynamic_cast<QObject*>(view->rootObject());
SignalslotlistView myClass;
QObject::connect(rect, SIGNAL(qmlSignal(QString)),
&myClass, SLOT(cppSlot(QString)));
Now I can receive QML signals in C++ side.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With