繁体   English   中英

无法从QQmlPropertyMap的子类中的QML调用slot或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();
        }
    }
}

我的main.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收到qDebug消息期望。

我不确定是否应该使用Q_DECLARE_METATYPE (我认为应该使用2-arg受保护的构造函数为我做这件事),但这两种方法均无效。

记录下来,我要做的唯一更改就是:

1)从QObject而不是QQmlPropertyMap派生。

2)将构造函数更改为:

TestMap(QObject* parent = 0): QObject(parent) {}

就是这样。 由于当我不更改main.cpp,main.qml或插槽本身的任何内容时,它都可以工作,因此我必须得出结论,这些都没错。 谁能告诉我我在做什么错?

现在,此问题已在Qt 5.1.0及更高版本中修复。 有关详细信息,请参见以下codereview URL:

https://codereview.qt-project.org/#change,57418

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM