Unexpected behavior of operator= in Qml/JavaScript



  • I have defined a couple of context variables from C++, something like this:
    @class MyClass : public QObject
    {
    Q_OBJECT
    Q_PROPERTY(QString name ...)
    };
    MyClass myVar1, myVar2;
    QQmlContext *ctxt = m_pMainView->rootContext();
    ctxt->setContextProperty("myVar1", &myVar1);
    ctxt->setContextProperty("myVar2", &myVar2);
    @

    In JavaScript in Qml, I can assign anything I want to myVar1, I don't get any errors or warnings, and the value of myVar1 never changes:
    @
    myVar1 = myVar2;
    myVar1 = 3.0;
    myVar1 = "Fred";
    @

    Having written my own code to inject variables into JavaScript (in the past, not related to Qt) I can certainly imagine why, but it seems like a bad idea that I don't get any sort of warning or error.

    Are there any macros I can insert into MyClass, or anything clever I can do that will make the operator= actually do something?

    Thanks,
    Chris



  • Hmm this can't work because your registred variables are a class and you want to set the value of a property of this class. So i think this is the right way
    @
    myvar1.name = "name"
    @
    The problem with the warning and errors is that qml is JIT so when you compile your project only the c++ side will be compiled the qml and javascript would be interpreted i think so the first time you get errors is when your programm is running and the qml is interpreted.



  • Yes, it would work to specify the values one at a time, the problem is that I would like to copy all of the values from myVar2 to myVar1, which means I need to write
    @myVar1.name = myVar2.name;
    myVar1.target = myVar2.target;
    myVar1.size = myVar2.size;
    etc. etc. etc.
    @

    which is not only annoying, but is error-prone and violates several object-oriented design principles.

    And yes, Qml and JavaCcript are interpreted and C++ is compiled, the problem is that the interpreter doesn't give me warnings or errors ever - including when the program is running and the Qml is interpreted and executed.

    I realize that JavaScript doesn't really support copying of objects by value, I'm working around this limitation in the language, my concern I guess is that by JavaScript rules, if I say
    @myVar1 = myVar2;
    @

    it should make myVar1 refer to the same object as myVar2 but that isn't happening, and no errors or warnings are being generated.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.