Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Using a function to generate a string for text:



  • Hi,

    I would like to let a function directly feed a text property, like:

    Text {
           text: function textSource() {
                  switch (lockKey.mode) {
                         case first: return "First option";
                         case second: return "Second option";
                         case third: return "Third option";
                         default: return "Default option";
                  }            
           }
    }
    
    

    But I get the following error message:

    Unable to assign a function to a property of any type other than var.
    

    while, on the other hand,

    Text {
           function textSource() {
                  switch (lockKey.mode) {
                         case first: return "First option";
                         case second: return "Second option";
                         case third: return "Third option";
                         default: return "Default option";
                  }
           }
           text: textSource()
    }
    

    does work, indeed. I've tried to trick around with

    text: String()+function textSource() { ...}
    

    but this leads to an on-screen text output of:

    "function textSource() {native code}"
    

    Is there a syntax trick that I am missing? Or is there any reasoning behind that restriction?



  • Replying to myself. The simple solution is not to use "function", but to just write the JS code in curly brackets. Didn't know that's even legal...

                    text:  {
                        switch (lockKey.mode) {
                            case first: return "First option";
                            case second: return "Second option";
                            case third: return "Third option";
                            default: return "Default option";                   }
                    }
    

    Sorry for the noise. I'll leave this for those searching for the error message (as I did).


Log in to reply