ramtheconqueror
ramtheconqueror

Reputation: 1964

expose C++ class to QML

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

Upvotes: 2

Views: 1671

Answers (1)

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.

Upvotes: 4

Related Questions