2
votes

I have this code.

class Pet
{
  public:
   Pet(const QString& nm)
    : name(nm)
   {}

   const QString& name() const { return nm; }

   private:
    QString nm;
}

class Dog : public QObject, public Pet
{
    Q_OBJECT
  public:
    Dog(QObject* prnt)
     : QBject(prnt),
       Pet("Tommy")
    {}
}

Exposing this to QML

QQmlApplicationEngine engine;
engine.rootContext()->setProperty("petDog", new Dog(&engine));

// QML Item

console.log(petDog.name()) // TypeError: Property 'name' of object Dog(0x0XXXXX) is not a function

What is the solution to expose all the methods of a C++ class to QML? Thanks

1

1 Answers

4
votes

The methods must be known to the meta-object system in order to be invokable from QML. This means a method must be either:

  1. a signal (Q_SIGNAL), or
  2. a slot (Q_SLOT), or
  3. invokable (Q_INVOKABLE).

In Qt 5 the difference between a slot and an invokable method is only that of whether the method is listed as among the slots when you iterate its metaobject data. Other than that, slots and invokable methods are equivalent.

In Qt 5 you can connect from C++ to any method, even if it's not a slot/invokable, but such methods are only known to the C++ compiler, not to QML.