运行QML时出现“未知方法参数类型”错误

问题描述 投票:0回答:1

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

在下面的代码中,我添加了一个stub 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])
        }
}

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

我在运行时得到的错误是

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

似乎我的错误与bug报告网站上报告的here相同。我正在使用Qt的最新版Qt 5.10。

编辑

PersonBirthdayParty类型的注册如下

 qmlRegisterType<BirthdayParty>("People", 1,0, "BirthdayParty");
 qmlRegisterType<Person>("People", 1,0, "Person");
c++ qt qml
1个回答
0
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.