关于qt:动态添加到qml标签栏和stacklayout

Adding dynamically to qml tabbar and stacklayout

我正在尝试在qml中创建选项卡式页面。我使用了与StackLayout相关联的TabBar:

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
      TabBar {
      id: bar
      width: parent.width
      TabButton {
          text: qsTr("Home")
      }
      TabButton {
          text: qsTr("Discover")
      }
      TabButton {
          text: qsTr("Activity")
      }
  }

  StackLayout {
      width: parent.width
      currentIndex: bar.currentIndex
      Item {
          id: homeTab
      }
      Item {
          id: discoverTab
      }
      Item {
          id: activityTab
      }
  }

此代码可以轻松地动态添加新的tabButton:

1
2
        var tab = tabButton.createObject(TTabButton, {text: tabName});
        bar.addItem(tab);

哪个TTabButton是一个由TabButton项组成的单独文件。但是我找不到任何将新页面添加到StackLayout的方法。似乎应该是静态的。所以我的问题是如何在qml中进行动态制表?


您可以添加到StackLayout的子级中:

1
2
var item = stackItem.createObject(null, {id:"tabName"})
layout.children.push(item)

stackItem是添加到StackLayout layout的那些项的组件。