Qt-点击QML按钮时如何运行C++函数?使用QQmlApplicationEngine
Qt - How to run a C++ function when QML button is clicked? Using QQmlApplicationEngine
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)
{
}
相关文章:
- 运行同一解决方案的另一个项目的项目
- CMake-按正确顺序将项目与C运行时对象文件链接
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- 代码在main()中运行,但在函数中出现错误
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何在运行中期切换GTK CSS style_context
- 如何在MS Visual Studio 2019中运行QT UI
- 如何通过cpp程序运行shell脚本
- IPC使用多个管道和分支进程来运行Python程序
- 删除指向指针的指针是运行时错误吗
- 如何用参数值调用函数(仅在运行时已知)
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- c++中的指针和运行时错误
- 在C应用程序中运行C++(带有STL)函数
- 运行程序时出现问题
- 控制允许动态运行c++的并发操作数
- 无法获取菜单选择以运行函数.C++