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参数。
当我编译&amp;跑......一切顺利。 但是当我点击按钮时......它在调试器中显示了这个错误:
qrc:///main.qml:80:ReferenceError:未定义_myClass
〜&GT; &#34;我的QML文件中的第80行&#34;:
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继承。
仍在寻找解决我主要问题的方法。
答案 0 :(得分:8)
首先要做的事情。在将某些内容传递给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)
{
}