2
votes

On C++ side, I had this method:

class MyClass : public QObject
{
    Q_OBJECT

    Q_INVOKABLE QVariant getFamily_byParentName(QString &parentName) const;

    // ...
}

I was calling the C++ method on QML:

onButtonClicked: {
    myClass.getFamily_byParentName(items3D.model[0]) // items3D.model[0] is a string
}

The above code was throwing this error at the QML line myClass.getFamily_byParentName(items3D.model[0]):

Error: Unknown method parameter type: QString&


Solution

The above error got resolved by declaring QString argument as const:

Q_INVOKABLE QVariant getFamily_byParentName(const QString &parentName) const;

The question is: why?

1
omitting the const means you might want to be able to change the QString from where the function was called (since you get a reference to the object), however since there is a conversion from javascript to C++ this makes no sense (at least to me ;-) ) - Amfasis
What's the exact type of items3D.model[0]? If items3D is const in that context it will likely be const QString &, i.e. exactly the type your method needs to accept. You can always add const to a value's type, i.e. going from QString & to const QString & is OK, but you can't take it away (otherwise what's the point, you promise in one place that you won't modify it, but can hand it off to somewhere else that does) - Caleth
@Caleth items3D.model[0] is QML string. QML is like JavaScript, so it might be JavaScript string like "First item". The scenario you suggested makes sense: QML string might be considered unmodifiable (at least when communicating with C++), therefore when passing it to C++, I need to use const reference! It makes sense :) - user3405291

1 Answers

4
votes

The QML engine converts the appropriate data types by copying the values.

In your case QString & is a reference to a QString that can not be copied, instead const QString & can be copied. For this reason you can not have a QObject as an argument since it is not copyable and instead you must use QObject * since a pointer is copyable.

It's the same principle as the Q_SIGNALs.