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 is not defined
〜> “我的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引擎的root属性时,无法创建新的上下文 – 您必须直接使用根上下文,如下所示:
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)
{
}