Not able to connect c++ signal to qml slot using QML connections
-
I am unable to connect C++ signal to QML slot using QML Connections
Below are the code snippets.
I have created my class like below.
i.e. connection.h
@
#ifndef CONNECTION_H
#define CONNECTION_H#include <QObject>
class connection : public QObject
{
Q_OBJECT
public:
explicit connection(QObject *parent = 0);signals:
void mySignal();public slots:
Q_INVOKABLE void mySlot();};
@connection.cpp
@
#include "connection.h"
#include<QDebug>connection::connection(QObject *parent) :
QObject(parent)
{
}void connection::mySlot()
{
qDebug() << "I have got the Signal" <<'\n';
emit mySignal();
}
@main.cpp is below.
@
#include <QtGui/QGuiApplication>
#include <QQmlContext>
#include "qtquick2applicationviewer.h"
#include "connection.h"int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);QtQuick2ApplicationViewer viewer; connection obj; viewer.setMainQmlFile(QStringLiteral("qml/stateTransistion/main.qml")); viewer.rootContext()->setContextProperty("connectionHandler", &obj); viewer.showExpanded(); return app.exec();
}
@main.qml is as below
@
import QtQuick 2.0Rectangle {
id: signal
width: 200; height: 200
border.color: "black"MouseArea { anchors.fill: parent onClicked: { connectionHandler.mySlot() } } Connections { target: connectionHandler onMySignal:console.log("I have got the signal emitted from C++") }
}
@Whenever I ran my application, I will get below error
QML Connections: Cannot assign to non-existent property "onMySignal"
ReferenceError: connectionHandler is not definedIf I have commented the Connections in main.qml then I am able to call mySlot() (i.e. Line number 11 in main.qml) using connectionHandler.
But when I uncommented Connections then i am getting below errorQML Connections: Cannot assign to non-existent property "onMySignal"
ReferenceError: connectionHandler is not definedI very novice in Qt.
Please help me to resolve these errors[edit: added missing coding tags @ SGaist]
-
Load the QmL file after exposing the object. Also get engine from viewer and get context. Set your variables in this context.
-
Ok. You are using your registered object inside QmL. When you load QmL it looks for this object. How does it know about your object ?. You need to register before loading.