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

QML proper using nested functions



  • Hi all!
    My code looks more or less like this:

    someJSscriptFile.js
    
    function getCurrentColor()
    {
    	return __getColor(control.currentValue)
    }
    
    function __getColor(value)
    {
    	if (control.pressed)
    	{
    		return "grey"
    	}
    
    	if(control.activated === false)
    	{
    		return "white"
    	}
    
        if(value ===0)
        {
            return "red";
        }
        return "green";
    }
    
    
    item1.qml
    
    item
    {
    id: defItem
      property var color : getColor()
    Text
    {
     text: "sometext"
    color: defItem.color
    }
    
    function getColor()
     {
         return someJSscriptFile.getCurrentColor()
     {
    }
    
    item2.qml
    
    ButtonStyle
    {
      property var color2 : getColor2()
    
    function getColor2()
     {
         return myItem.getCurrentColor()
     {
    
    property Component myItem: item1
    {
      color: color2
    }
    
    onSomeSignal()
    {
     label = myItem
    }
    }
    
    someLayout.qml
    RowLayout
    {
     Button
    {
      style:item2{}
    }
    }
    
    

    So my problem is that the color of text is black and I don't know how to fix it, am I missing some bindings or get the whole concept of QML wrong?

    Cheers, Kris



  • Hi @Kyeiv, I just did a quick test application and it worked for me:

    main.qml

    import QtQuick 2.9
    import QtQuick.Window 2.2
    
    import "someJSscriptFile.js" as Jss
    
    Window {
        visible: true
        width: 640
        height: 480
        title: qsTr("Hello World")
    
        Rectangle {
            id: rect
            color: Jss.getCurrentColor()
            anchors.fill: parent
        }
    }
    

    someJSScriptFile.js

    function getCurrentColor()
    {
        return __getColor(rect.currentValue)
    }
    
    function __getColor(value)
    {
        if (rect.pressed)
        {
            return "grey"
        }
    
        if(rect.activated === false)
        {
            return "white"
        }
    
        if(value ===0)
        {
            return "red";
        }
        return "green";
    }
    

    Is the variable "control" defined in your QML? Or what are you trying to use it for?