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();
}
我想在myClass类中使用一个函数,当单击QML按钮时,该函数会获取一个QString参数。。
当我编译&跑一切进展顺利。但是当我点击按钮时。。它在调试器中显示此错误:
qrc:///main.qml:80:ReferenceError:_myClass未定义
>>"QML文件中的第80行":
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: }
编辑:(至于编译错误引起的错误(
正如@Jairo所建议的,所有类都必须从QObject继承。
仍在寻找解决我主要问题的方法。
哦。这里有几处不对。(代码甚至可以编译吗?(
第一件事。当将某些内容传递给QML引擎的根属性时,您不能创建新的上下文——您必须直接使用根上下文,如下所示:
engine.rootContext()->setContextProperty("_myClass", &myClass);
接下来,类定义有一些问题。请参阅下面代码中的我的评论:
class MyClass : public QObject
{
// This macro is required for QObject support. You should get a compiler
// error if you don't include this.
Q_OBJECT
public:
// QObjects are expected to support a parent/child hierarchy. I've modified
// the constructor to match the standard.
explicit MyClass(QObject *parent = 0);
public slots:
// This method needs to take either a QString or a const reference to one.
// (QML doesn't support returning values via the parameter list.)
void buttonClicked(const QString& in);
};
构造函数的实现应该将父类传递给基类:
MyClass::MyClass(QObject *parent) :
QObject(parent)
{
}