Qt - How to run a C++ function when QML button is clicked? Using QQmlApplicationEngine

旧巷老猫 提交于 2019-12-01 10:57:55

Uh oh. There's several things wrong here. (Does the code even compile?)

First things first. When passing something to the QML engine's root property, you can't create a new context -- you have to use the root context directly, like so:

engine.rootContext()->setContextProperty("_myClass", &myClass);

Next, the class definition has some problems. See my comments in the code below:

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);
};

The constructor's implementation should pass the parent on to the base class:

MyClass::MyClass(QObject *parent) :
    QObject(parent)
{
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!