简体   繁体   中英

`Unknown method parameter type` error while running QML

Consider the slightly modified birthday_party.h example from the standard QT example lists below.

In the code below, I have added a stub test() function which just prints the name of the person using the pointer passed to it.

#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

The definition for test() is

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

My QML file where I call test is

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])
        }
}

Now the above code compiles and runs just fine. However, if I add the const qualifier in front of Person* p in the argument list of test() I get errors from QML at run-time! (ie runtime barfs if the signature for test in both headers and .cpp is void test(const Person* p) )

The error I get at runtime is

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

It seems my error is identical to the one reported here on the bug-reports website. I am using Qt 5.10, the latest version of Qt.

EDIT

The Person and BirthdayParty types are being registered as follows

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

Ok, as I understand the last versions of Qt had changed object casting from QML to Qt and vice versa. Sometimes it was able to use pointers to object, references etc. It looks that now it's different and you have to specify the used type explicitly. In your case I guess you should add the following line to items registration:

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

Btw, I advice you to use references instead of pointers since it eliminates the ambiguity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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