无法从 QQmlPropertyMap 子类中的 QML 调用槽或Q_INVOKABLE

Can't call slot or Q_INVOKABLE from QML in subclass of QQmlPropertyMap

本文关键字:调用 INVOKABLE QML QQmlPropertyMap 子类      更新时间:2023-10-16

我正在尝试测试驱动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