Qt6 topics merged with General

QtScript call functions with & arguments

  • i have a class that has a method with reference arguments:

    bool myMethod(QString arg1, int & someRefArg);

    how do i make this function callable from QtScript?

    if i try it like:

    var a = 123;
    myObj['myMethod(QString, int&)']("test",a);
    TypeError: cannot call myMethod(): argument 2 has unknown type `int&' (register the type with qScriptRegisterMetaType())

    I tryed to register the type :

    QScriptValue toScriptValue(QScriptEngine *engine, const int &&s)
      QScriptValue obj = engine->newObject();
      obj = s;
      return obj;
    void fromScriptValue(const QScriptValue &obj, int &&s)
      s = obj.toInt();

    but this has no effect.
    what do i need to do to pass a reference to the method?

  • Lifetime Qt Champion


    Is it a typo or are your function signature really:

    QScriptValue toScriptValue(QScriptEngine *engine, const int &&s) << one & too much
    void fromScriptValue(const QScriptValue &obj, int &&s)  << one & too much

    Hope it helps

  • @SGaist

    no not relay the && was intended.

    the standard devinition of a fromScriptValue uses one & so it can access the value and does not get a copy. My intention by using 2 && was to actually be able to pass a int& and not just an int . Perhaps this makes it clearer what i want to do:

    QScriptValue toScriptValue(QScriptEngine *engine, const (int&) &s)
    void fromScriptValue(const QScriptValue &obj, (int&) &s)

    also now I see in the documentation that I need to register the type with Q_DECLARE_METATYPE. But


    does not compile. :(

  • Lifetime Qt Champion

    I see what you want to do but why ?

  • because:
    I want to script some parts the code
    and the methods in the library i need to use are defined like this: bool getMyValue(QString, ValueType&)
    and i can not change that library
    and i do not want to write a wrapper

  • Lifetime Qt Champion

    AFAIK, you can't use reference to types to create metatypes

  • hmm ok :( still thank you for the help