myclass.h
#ifndef MYCLASS_H
#define MYCLASS_H
#include <QDebug>
#include <QObject>
class MyClass : public QObject
{
public:
MyClass();
public slots:
void buttonClicked();
void buttonClicked(QString &in);
};
#endif // MYCLASS_H
myclass.cpp
#include "myclass.h"
MyClass::MyClass()
{
}
void MyClass::buttonClicked()
{
// Do Something
}
void MyClass::buttonClicked(QString &in)
{
qDebug() << in;
}
main.cpp
#include <QApplication>
#include <QQmlApplicationEngine>
#include <myclass.h>
#include <QQmlContext>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:///main.qml")));
MyClass myClass; // A class containing my functions
// Trying to "SetContextProperty" as I saw people do it to achieve C++/QML connection
QQmlContext * context = new QQmlContext(engine.rootContext());
context->setContextProperty("_myClass", &myClass);
return app.exec();
}
I want to use a function in myClass class which takes a QString parameter when a QML button is clicked ..
When I compile & run .. it all goes smoothly. But when I click on the button .. it shows this error in the debugger:
qrc:///main.qml:80: ReferenceError: _myClass is not defined
~> "Line 80 in my QML file":
74: MouseArea {
75: id: mouseArea1
76: anchors.fill: parent
77: hoverEnabled: true;
78: onEntered: { rectangle1.border.width = 2 }
79: onExited: { rectangle1.border.width = 1 }
80: onClicked: _myClass.buttonClicked("Worked?")
81: }
EDIT: ( As for the error caused the compiling error )
As @Jairo suggested, all classes must be inherited from QObject.
Still looking for a solution to my main problem.
myClass.buttonClicked(QString)
) from QML like: [_myClass.buttonClicked("JJJ")
]? Thanks :) – Alaa Elrifaie