Nominate our 2022 Qt Champions!

Porting class constructor to a script

  • Hi, everybody! I have a QtScript problem.
    I have a following class to be imported to QtScript:
    class CPos : public QObject, public QScriptable
    Q_PROPERTY(float x WRITE setX READ x)
    Q_PROPERTY(float y WRITE setY READ y)
    Q_PROPERTY(float z WRITE setZ READ z)

    CPos(QObject* parent = 0) : QObject(parent) {}
    void setX(float value) {f_x = value;}
    void setY(float value) {f_y = value;}
    void setZ(float value) {f_z = value;}
    float x() const {return f_x;}
    float y() const {return f_y;}
    float z() const {return f_z;}

    float f_x, f_y, f_z;


    I wrote the following functional to be called as class-constructor:
    QScriptValue Pos(QScriptContext *context, QScriptEngine *engine)
    QScriptValue value = engine->newQObject(new CPos());
    value.setProperty("x", context->argument(0));
    value.setProperty("y", context->argument(1));
    value.setProperty("z", context->argument(2));
    return value;

    In my main functioan I do the following:
    QScriptEngine engine;
    QScriptValue proto = engine.newQObject(new CPos());
    engine.setDefaultPrototype(qMetaTypeId<CPos*>(), proto);
    engine.globalObject().setProperty("Pos", engine.newFunction(Pos, proto));

    But as far as I can see my script

    var p = new Pos();

    has no effect. Where did I go wrong?

Log in to reply