1

I have my C++/QT code

// .hpp
Q_PROPERTY(int Index READ Index WRITE setIndex NOTIFY IndexChanged)

public:

int Index() const;
int Index(int n) const;
void setIndex(int index):

//.cpp
setContextProperty(QStringLiteral("target"), this)

On the QML side i can access the index using target.Index. What is the syntax for using the taget.Index(int n) for example target.Index(8) gives me errors. Any examples for overloaded read function ?

2 Answers2

2

What you are trying to do is sadly not really possible;

To begin with you'd need to add Q_INVOKABLE to the overloaded method (or make it a slot) in order to make it available to the QML engine:

Q_INVOKABLE int Index(int n) const;

That would mean that target.index is both a function and an int though, and that's of course not possible (isn't in QML/JavaScript and neither in C++). Qt seems to give priority to the property in this case, so you'll still get the "...is not a function" error.

You'll probably have to rename the overloaded function.

Note: The QML engine does handle function overloads (just make sure they are all either slots or marked with Q_INVOKABLE), just not having a function and a property of the same name. So you could have both target.Index() and target.Index(4), but you can't notify of changes that way.

Jan
  • 993
  • 1
  • 13
  • 28
1

There are two possible approaches:

You should:

  1. Disambiguate the names exposed to QML.
  2. Expose the method not given in Q_PROPERTY as invokable.

E.g.:

class Foo : public QObject {
  Q_OBJECT
  Q_PROPERTY(int Index READ Index WRITE setIndex NOTIFY IndexChanged)
  // QML Interface
  Q_INVOKABLE int Index1(int n) const { return Index(n); }
public:
  // C++ interface
  int Index() const;
  int Index(int n) const;
  void setIndex(int index);
  Q_SIGNAL void IndexChanged();
};

Alternatively, if you're OK with using function interface from JavaScript in place of property interface, you need to take an optional argument via a QVariant. See this question for further details about overloading in QML. E.g.:

class Foo : public QObject {
  Q_OBJECT
  Q_PROPERTY(int IndexProp READ Index WRITE setIndex NOTIFY IndexChanged)
  // QML interface
  Q_INVOKABLE int Index(const QVariant & n) const {
    if (n.isValid())
      return Index(n.toInt());
    return Index();
  }
public:
  // C++ interface
  int Index() const;
  int Index(int n) const;
  void setIndex(int index);
  Q_SIGNAL void IndexChanged();
};

The following are all valid then:

target.IndexProp = 5
foo = target.IndexProp
foo = target.Index()
foo = target.Index(2)
Community
  • 1
  • 1
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313