关于qt:在QML中将TabButton动态添加到TabBar

Adding TabButton dynamically to TabBar in QML

我试图在按下按钮时向TabBar动态添加一个tabButton,但是我花了很多时间进行搜索,但是我没有得到如何添加,下面是我正在研究的代码:

MyTabButton.qml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import QtQuick 2.4
import QtQuick.Controls 2.2

Item
{
    property int BtnWidth:0
    property int BtnHeight:0
    property string BtnText:""
    property bool isChecked : false

    TabButton
    {
        id:tabBtn
        text:BtnText
        width:BtnWidth
        height:BtnHeight

    }
}

MainForm.qml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import QtQuick 2.4
import QtQuick.Controls 2.2

Rectangle
{
    Button
    {
        id:button
        width:100
        height:100
        anchors.top:parent.top
        text:qStr("Add")
        onClicked{
            //How to add logic here to add tab in below tabBar.
        }
    }
    TabBar
    {
        id:tabBar
        anchors.top:button.bottom
        width:500
        height:500
    }
}

例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import QtQuick 2.7
import QtQuick.Controls 2.0

ApplicationWindow {
    id: window
    width: 360
    height: 630
    visible: true

    header: TabBar {
        id: tabBar
    }

    Component {
        id: tabButton
        TabButton { }
    }

    Button {
        text:"Add"
        anchors.centerIn: parent
        onClicked: {
            var tab = tabButton.createObject(tabBar, {text:"Tab" + tabBar.count})
            tabBar.addItem(tab)
        }
    }
}


您需要类似Component的东西,即TabButton。 您的文件MyTabButton.qml不会生成TabButton,而是导致包含TabButtonItem,但是,与此同时,您的TabBar不知道该怎么做。

因此,您的文件将需要以TabButton作为根元素

//MyTabButton.qml

1
2
3
4
5
6
7
import QtQuick 2.4
import QtQuick.Controls 2.2
TabButton
{
    id: tabBtn
    // customize as you like
}

然后,在要使用它的文件中创建此组件。 (例如main.qml)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import QtQuick 2.4
import QtQuick.Controls 2.0

ApplicationWindow {
    width: 800
    height: 600
    visible: true

    TabBar {
        id: tabBar
        width: 800
        height: 50
    }

    // The component is like a factory for MyTabButtons now.
    // Use myTabButton.createObject(parent, jsobject-with-property-assignments) to create instances.
    Component {
        id: myTabButton
        MyTabButton {
            /// EDIT ACCORDING TO YOUR COMMENTS ***
            Connections {
                target: tabBar
                onCurrentIndexChanged: doSomething()
            }
            /// EDIT OVER
        }
    }

    Button {
        anchors.centerIn: parent
        // Create a object out of the component, and add it to the container
        onClicked: tabBar.addItem(myTabButton.createObject(tabBar /*, { object to set properties }*/))
    }
}


TabBar继承具有addItem()Container