无法从 QQmlPropertyMap 子类中的 QML 调用槽或Q_INVOKABLE
Can't call slot or Q_INVOKABLE from QML in subclass of QQmlPropertyMap
我正在尝试测试驱动QQmlPropertyMap
类。如果我能对它进行子类化,它似乎可以很好地满足我的需求。这里的文档甚至给出了一些关于如何对它进行个子类化的基本说明。所述文档还表明这个类派生自QObject
。
值得一提的是,我在Qt 5.0.0和QtQuick 2.0上使用了QtCreator 2.6.1。
我的main.qml:
import QtQuick 2.0
Rectangle {
width: 360
height: 360
Text {
text: owner.field
anchors.centerIn: parent
}
MouseArea {
anchors.fill: parent
onClicked: {
owner.testFunc();
}
}
}
我的主.cpp:
#include <QtGui/QGuiApplication>
#include "qtquick2applicationviewer.h"
#include "TestMap.h"
#include <QQmlContext>
int main(int argc, char *argv[])
{
TestMap* map = new TestMap();
QGuiApplication app(argc, argv);
QtQuick2ApplicationViewer viewer;
QQmlContext* ctxt = viewer.rootContext();
ctxt->setContextProperty("owner", map);
viewer.setMainQmlFile(QStringLiteral("qml/TestMap/main.qml"));
viewer.showExpanded();
return app.exec();
}
我的TestMap.h
#ifndef TESTMAP_H
#define TESTMAP_H
#include <QObject>
#include <QQmlPropertyMap>
#include <QDebug>
class TestMap: public QQmlPropertyMap // QObject
{
Q_OBJECT
public:
TestMap(QObject* parent = 0): QQmlPropertyMap(this, parent) // QObject(parent)
{
insert("field", "value"); // Comment this out
}
TestMap(const TestMap& value) { }
virtual ~TestMap() {}
public slots:
void testFunc()
{
qDebug() << "Success!";
}
};
Q_DECLARE_METATYPE(TestMap)
#endif
当我跑步时,我会得到一个窗口,上面写着"值",正如我所期望的那样。但当我点击窗口时,我会得到一个控制台输出,上面写着
TypeError: Property 'testFunc' of object TestMap(0xaaa0b8) is not a function
我已经查找过类似的问题,但所有的搜索结果都是关于忘记包含Q_OBJECT
宏的人的。这一定是我在代码中做错了什么,因为如果我做了TestMap文件注释中指示的所有更改(并保持main.cpp和main.qml完全不变),我就会得到我期望的qDebug
消息。
我不确定我是否应该Q_DECLARE_METATYPE
(我认为2-arg保护的构造函数应该为我做这件事),但这两种方式都不起作用。
为了记录在案,我唯一需要改变的就是:
1) 从QObject
而不是QQmlPropertyMap
派生。
2) 将构造函数更改为:
TestMap(QObject* parent = 0): QObject(parent) {}
就是这样。因为当我不更改main.cpp、main.qml或插槽本身的任何内容时,它都是有效的,所以我不得不得出结论,这些都没有错。有人能告诉我我做错了什么吗?
这在Qt 5.1.0及以后的版本中已经修复。有关详细信息,请参阅以下代码审查url:
https://codereview.qt-project.org/#change,57418
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 函数调用中参数的顺序重要吗
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在c++类上调用void函数
- 为什么 std::unique 不调用 std::sort?
- 调用专用模板时出错"no matching function for call to [...]"
- 选择要调用的构造函数
- C++为什么尽管我调用了void函数,它却不起作用
- 构造函数正在调用一个使用当前类类型的函数
- 变量没有改变?通过向量的函数调用
- 没有为自己的结构调用列表推回方法
- 调用'begin(int [n])'没有匹配函数
- 什么时候调用析构函数
- 如何用参数值调用函数(仅在运行时已知)
- std::cout.imbue()多重调用
- 函数何时会在c++中包含stack_Unwind_Resume调用