Items inside TabView / Tab are not available

Suppose we have a QML file, for example:

Window {

    Component.onCompleted: rect.color  ="green"

    TabView {
        Tab {
            Rectangle {
                id:  rect
                color: "white"
            }
        }
    }
}

      

When I run this code, for some reason, it gives me this error:

ReferenceError: rect is not defined

Someone might say this is a scope issue, but the following code works fine:

Window {

    Component.onCompleted: rect.color  ="green"

    Item {
        Item {
            Rectangle {
                id:  rect
                color: "white"
            }
        }
    }
}

      

In my case, I have a large form with tabs and controls inside it, and I pass all controls to multiple functions to validate the form, i.e. some code:

function onClose() {
    validate(control1);
    validate(control2);
    // etc
}

      

but when accessing the controls using id

i get the above error.

+3


source to share


2 answers


How can I simply bind the rectangle to a color parameter instead of a hardcoded value?

This will allow you to further separate your Model and View code to make it more readable elsewhere in your project ... try:

Window {

    property string myColor: "White"
    Component.onCompleted: myColor = "Green"

    TabView {
        Tab {
            Rectangle {
                id:  rect
                color: myColor
            }
        }
    }

      



}

To view the QML object tree, you need to run the project in debug mode. Then split the code window so that the Locales and Expressions view is displayed (the checkbox is checked on the right). You will see your root element and all other controls nested in the tree, and now you can directly edit the values ​​of your properties and the changes will be reflected immediately. There is a youtube video tutorial on debugging: https://youtu.be/mPXn6L2Wftc?t=19m55s

I'm not sure if the tree will give you access to the controls at runtime, but it might help you debug.

0


source


Ok, since the element is Tab

not accessible from the outside, I think it can be done like this:

TabView {
    id: tabView
    Tab {
        title: "tab1"
        function validate() { /* validate all the controls related to tab1 only */ }
        Item { id: item1 }
        Item { id: item2 }
    }
    Tab {
        title: "tab2"
        function validate() { /* validate all the controls related to tab2 only */ }
        Item { id: item3 }
        Item { id: item4 }
    }
    function validateTabs() {
        for(var i = 0; i < tabView.count;i ++) {
            var tab = tabView.getTab(i);
            if(tab && tab.active && tab.item.validate) {
                if(!tab.item.validate())
                    return false;
            }
        }
        return true;
    }
}

      



The good thing is that if one Tab

was not open and therefore not changed, it will not be checked.

0


source







All Articles