2

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?

4

2 回答 2

3

最后绕过并尝试解决此问题并成功。决定发布作为答案,以防有人从谷歌偶然发现此问题并遇到类似问题。

解决方案是将 设置currentIndex为新的Tab,然后设置Tab. 这意味着该函数loadTab()如下所示:

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

这很好用。

于 2014-06-07T05:20:00.870 回答
0

更好的解决方案:

loadTab(){
    var c_tab=currentIndex
    var t=tb.addTab("x",viewComp)
    t.active = true;// real loading
    t.item.color="blue" 
}
于 2016-04-24T20:58:43.270 回答