Search code examples
qtqmlqt5qtquick2

Adding tabs dynamically in qml


I'm trying to dynamically create Tabs in QML. The code below is a simple example of what I want to do.

import QtQuick 2.0
import QtQuick.Controls 1.0

ApplicationWindow{
    id:win

    TabView{
        id:tb
        anchors.fill:parent

        MouseArea{
            anchors.fill:parent
            onClicked:tb.loadTab()
        }

        Component{
            id:viewComp
            Rectangle{
                anchors.fill:parent
                color:"black"
            }
        }

        function loadTab(){
            var t=addTab("x",viewComp)
            t.item.color="blue" //line 20
        }
    }
}

Addition of the first Tab works as expected. However, after that any other Tab added triggers the error:

TypeError: Cannot set property 'color' of null`.

I tried to access the Tabwith getTab() to change the color, but I get the same error. Can someone explain what am I doing wrong?


Solution

  • Finally got around and tried to fix this and was successful. Decided to post as an answer in case someone stumbles on this from google and has a similar problem.

    The solution was to set the currentIndex to the new Tab and then set properties of the Tab. This means that the function loadTab() looks like this:

    loadTab(){
        var c_tab=currentIndex
        var t=tb.addTab("x",viewComp)
        currentIndex=count-1
        t.item.color="blue" 
        currentIndex=c_tab
    }
    

    This works nicely.