【问题标题】:`Unknown method parameter type` error while running QML运行 QML 时出现“未知方法参数类型”错误
【发布时间】:2017-12-27 15:06:31
【问题描述】:

考虑下面标准 QT 示例列表中稍微修改的 birthday_party.h example

在下面的代码中,我添加了一个存根test() 函数,它使用传递给它的指针打印人的姓名。

#ifndef BIRTHDAYPARTY_H
#define BIRTHDAYPARTY_H

#include <QObject>
#include <QQmlListProperty>

#include "person.h"

class BirthdayParty : public QObject
{
    Q_OBJECT
    Q_PROPERTY(Person *host READ host WRITE setHost)
    Q_PROPERTY(QQmlListProperty<Person> guests READ guests)
public:
    BirthdayParty(QObject *parent = 0);

    Person *host() const;
    void setHost(Person *);

    QQmlListProperty<Person> guests();
    int guestCount() const;
    Person *guest(int) const;

    Q_INVOKABLE Person* invite(const QString &name);
    Q_INVOKABLE void test( Person* p);

private:
    Person *m_host;
    QList<Person *> m_guests;
};

#endif // BIRTHDAYPARTY_H

test() 的定义是

void BirthdayParty :: test(Person* p)
{
  QString qname = p->name();
  std::cout << qname.toUtf8().constData() << std::endl;
}

我调用 test 的 QML 文件是

import QtQuick 2.0
import People 1.0


BirthdayParty {
    host: Person { name: "Bob Jones" ; shoeSize: 12 }

    guests: [
        Person { name: "Leo Hodges" },
        Person { name: "Jack Smith" },
        Person { name: "Anne Brown" },
        Person { name : "Gaurish Telang"}
    ]

    Component.onCompleted:
       {
         test(guests[0])
        }
}

现在上面的代码编译并运行得很好。但是,如果我在 test() 的参数列表中的 Person* p 前面添加 const 限定符 我在运行时收到来自 QML 的错误! (即,如果标头和 .cpp 中的测试签名都是 void test(const Person* p),则运行时 barfs)

我在运行时得到的错误是

qrc:example.qml:17: Error: Unknown method parameter type: const Person*

看来我的错误与错误报告网站上报告的here 相同。我正在使用 Qt 5.10,这是 Qt 的最新版本。

编辑

PersonBirthdayParty 类型注册如下

 qmlRegisterType<BirthdayParty>("People", 1,0, "BirthdayParty");
 qmlRegisterType<Person>("People", 1,0, "Person");

【问题讨论】:

  • 您如何注册您的物品?
  • @folibis 请参阅编辑。在尝试添加上面的 const 限定符时,我没有更改注册类型的方式。这有什么不同吗?

标签: c++ qt qml


【解决方案1】:

好的,据我了解,Qt 的最新版本已将对象转换从 QML 更改为 Qt,反之亦然。有时它能够使用指向对象、引用等的指针。现在看起来它不同了,您必须明确指定使用的类型。 在您的情况下,我想您应该在项目注册中添加以下行:

qRegisterMetaType<Person*>("const Person*");

顺便说一句,我建议你使用引用而不是指针,因为它消除了歧义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-14
    • 1970-01-01
    • 2014-09-16
    • 2021-10-04
    • 1970-01-01
    • 2016-04-20
    • 2019-11-07
    • 1970-01-01
    相关资源
    最近更新 更多