gpt4 book ai didi

c++ - Qt - 单击 QML 按钮时如何运行 C++ 函数?使用 QQmlApplicationEngine

转载 作者:太空狗 更新时间:2023-10-29 23:50:59 25 4
gpt4 key购买 nike

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 引擎的根属性时,您无法创建新的上下文——您必须直接使用根上下文,如下所示:

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

关于c++ - Qt - 单击 QML 按钮时如何运行 C++ 函数?使用 QQmlApplicationEngine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24871237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com