> 文章列表 > Qt Quick - Container

Qt Quick - Container

Qt Quick - Container

Qt Quick - Container使用总结

  • 一、概述
  • 二、使用容器
  • 三、管理当前索引
  • 四、容器实现

一、概述

Container 提供容器通用功能的抽象基类。Container是类容器用户界面控件的基本类型,允许动态插入和删除Item。DialogButtonBox, MenuBar, SwipeView, 和 TabBar 都是继承至这个控件。

二、使用容器

通常情况下,Item被静态声明为Container的子Item,但也可以动态地添加、插入、移动和删除Item。可以使用itemAt()或contentChildren访问容器中的Item。

大多数容器都有“当前”项的概念。当前项是通过currentIndex属性指定的,可以通过只读的currentItem属性访问。
下面的例子演示了如何将Item动态插入TabBar,这是Container的具体实现之一。

 Row {TabBar {id: tabBarcurrentIndex: 0width: parent.width - addButton.widthTabButton { text: "TabButton" }}Component {id: tabButtonTabButton { text: "TabButton" }}Button {id: addButtontext: "+"flat: trueonClicked: {tabBar.addItem(tabButton.createObject(tabBar))console.log("added:", tabBar.itemAt(tabBar.count - 1))}}}

Qt Quick - Container

三、管理当前索引

当使用多个容器时,例如TabBar和SwipeView,它们的currentIndex属性可以相互绑定以保持它们同步。当用户与任何容器交互时,其当前索引的更改自动传播到另一个容器。
但是请注意,在JavaScript中为currentIndex赋值会删除相应的绑定。为了保留绑定,使用以下方法更改当前索引:

  • incrementCurrentIndex ()
  • decrementCurrentIndex ()
  • setCurrentIndex ()
  TabBar {id: tabBarcurrentIndex: swipeView.currentIndex}SwipeView {id: swipeViewcurrentIndex: tabBar.currentIndex}Button {text: qsTr("Home")onClicked: swipeView.setCurrentIndex(0)enabled: swipeView.currentIndex != 0}Button {text: qsTr("Previous")onClicked: swipeView.decrementCurrentIndex()enabled: swipeView.currentIndex > 0}Button {text: qsTr("Next")onClicked: swipeView.incrementCurrentIndex()enabled: swipeView.currentIndex < swipeView.count - 1}

四、容器实现

Container不提供任何默认的可视化。它用于实现SwipeView和TabBar等容器。在实现自定义容器时,API中最重要的部分是contentModel,它提供了包含的项目,可以用作项目视图和重复器的委托模型。

  Container {id: containercontentItem: ListView {model: container.contentModelsnapMode: ListView.SnapOneItemorientation: ListView.Horizontal}Text {text: "Page 1"width: container.widthheight: container.height}Text {text: "Page 2"width: container.widthheight: container.height}}

请注意,page 项的大小是如何手动设置的。这是因为这个例子使用了一个普通的容器,它没有对视觉布局做任何假设。在具体的容器实现中,通常没有必要指定Item的大小,例如SwipeView和TabBar。