【问题标题】:Can't call slot or Q_INVOKABLE from QML in subclass of QQmlPropertyMap无法从 QQmlPropertyMap 的子类中的 QML 调用 slot 或 Q_INVOKABLE
【发布时间】:2013-02-07 14:28:44
【问题描述】:

我正在尝试试驾QQmlPropertyMap 课程。如果我可以对它进行子类化,它似乎可以很好地满足我的需求。文档here 甚至提供了一些关于如何对其进行子类化的基本说明。所述文档还表明该类派生自QObject

不管怎样,我在 Qt 5.0.0 上使用 QtCreator 2.6.1 和 QtQuick 2.0。

我的 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 文件的 cmets 中指示的所有更改(并将 main.cpp 和 main.qml 保持原样),我会得到qDebug我期待的消息。

我不确定我是否应该使用 Q_DECLARE_METATYPE(我认为 2-arg 受保护的构造函数应该为我做这件事),但无论如何它都不起作用。

为了记录,我唯一需要改变才能让它工作的是:

1) 派生自 QObject 而不是 QQmlPropertyMap

2) 将构造函数改为:

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

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

【问题讨论】:

标签: c++ qt qml qt5 qtcore


【解决方案1】:

这已在 Qt 5.1.0 及更高版本中得到修复。详情见以下codereview url:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-07-17
  • 1970-01-01
  • 1970-01-01
  • 2019-11-16
  • 2021-03-16
  • 1970-01-01
  • 2023-03-08
  • 2017-10-21
相关资源
最近更新 更多