Invalid write to global property



  • Hi all! Could u help me with my little proble? I'm begginer in qt/qml. And I'd like to change some properties of qml component from anonter qml file, and I've decided to use JS like this:
    @.pragma library
    sc = String;
    function setSc(ss) {
    sc = ss;
    }

    function getSc () {
    return sc;
    }@
    Try to use it:
    @import "setInfo.js" as Scr
    ....
    onClicked: Scr.setSc("#777777")
    .....
    color: Scr.getSc()@
    But it doesn't work
    @qrc:/setInfo.js:8: ReferenceError: sc is not defined
    qrc:/setInfo.js:4: Error: Invalid write to global property "sc"@
    Can anyone help me? Will be grateful for u'r any solutions.


  • Moderators

    Hi and Welcome to Qt DevNet.

    Try declaring sc as var.


  • Moderators

    I think you forgot to add var keyword before your sc variable name:
    @
    var sc = String;
    @



  • @var sc;
    .......
    qrc:/Info.qml:6:12: Unable to assign [undefined] to QColor
    qrc:/main.qml:52:19: Unable to assign [undefined] to QString@
    And: @var sc = String;
    ......
    qrc:/Info.qml:6:12: Unable to assign a function to a property of any type other than var.
    qrc:/main.qml:52:19: Unable to assign a function to a property of any type other than var.@

    main.qml:52 @text: Scr.getSc()@
    Info.qml:6 @color: Scr.getSc()@


  • Moderators

    That is because it is not able to understand what String object is.
    Assingn some string instead,
    @
    var sc = "green";
    @



  • It works, thank u. But I can't write property by this way:
    @onClicked: Scr.setSc("red")@
    And it have not any errors using this.
    Have any idea?


  • Moderators

    It does write. Try this
    @
    onClicked: {
    Scr.setSc("red")
    rect.color = Scr.getSc() //assuming rect is id of that element
    }
    @



  • In my case, "rect" is located in another qml file, and I can not call to its property by this way. It seems, that setSc method does not work right.


  • Moderators

    bq. It seems, that setSc method does not work right.

    You can try printing the value in setSc function to check if it works.
    @
    function setSc(ss) {
    sc = ss
    console.log(sc)
    }
    @


Log in to reply
 

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