- //TabWidget.qml
- import Qt 4.7
- Item {
- id: tabWidget
- default property alias content: stack.children //将tab页集合设置一个默认属性
- property int current: 0
- onCurrentChanged: setOpacities()
- Component.onCompleted: setOpacities()
- function setOpacities() {
- for(var i = 0; i < content.length; ++i) {
- content[i].opacity = (i == current ? 1 : 0);//将当前的tab设置为非透明,其余透明
- }
- }
- Row { //此组件为tab选项
- id: header
- Repeater {
- model: content.length
- delegate: Rectangle {
- width: tabWidget.width / content.length
- height: 36
- color: "#e3e3e3"
- Rectangle { //此组件为tab选项和tab页之间的一条线
- width: tabWidget.width; height: 1
- anchors { bottom: parent.bottom; bottomMargin: 1}
- color: "#abc2c2"
- }
- BorderImage { //tab选项图片
- anchors { fill: parent; leftMargin: 2; topMargin: 5; rightMargin: 1}
- border { left: 7; right: 7}
- source: tabWidget.current == index? "tab.png" : "unselect.png"
- }
- Text { //tab选项的文本
- horizontalAlignment: "AlignHCenter"; verticalAlignment: "AlignVCenter"
- anchors.fill: parent
- text: content[index].title
- elide: Text.ElideRight
- font.bold: tabWidget.current == index
- }
- MouseArea {
- anchors.fill: parent
- onClicked: tabWidget.current = index //存储当前选中tab页
- }
- }
- }
- }
- Item { //此组件为tab页
- id: stack
- width: tabWidget.width
- anchors.top: header.bottom
- anchors.bottom: tabWidget.bottom
- }
- }
- //main.qml
- import Qt 4.7
- TabWidget {
- id: tabs
- width: 640; height: 480
- Rectangle { //第一个tab页
- property string title: "Red"
- anchors.fill: parent
- color: "#e3e3e3"
- Rectangle {
- anchors.fill: parent; anchors.margins: 20 //tab边框与父容器的距离
- color: "#7fff7f"
- Text {
- width: parent.width - 20
- anchors.centerIn: parent; horizontalAlignment: "AlignHCenter"
- text: "Roses are red"
- font.pixelSize: 20
- wrapMode: Text.WordWrap
- }
- }
- }
- Rectangle { //第二个tab页
- property string title: "Green"
- anchors.fill: parent
- color: "#e3e3e3"
- Rectangle {
- anchors.fill: parent; anchors.margins: 20
- color: "#7fff7f"
- Text {
- width: parent.width - 20
- anchors.centerIn: parent; horizontalAlignment: "AlignHCenter"
- text: "Flower stems are green"
- font.pixelSize: 20
- wrapMode: Text.WordWrap
- }
- }
- }
- Rectangle { //第三个tab页
- property string title: "Blue"
- anchors.fill: parent
- color: "#e3e3e3"
- Rectangle {
- anchors.fill: parent; anchors.margins: 20
- color: "#7fff7f"
- Text {
- width: parent.width - 20
- anchors.centerIn: parent; horizontalAlignment: "AlignHCenter"
- text: "Violets are blue"
- font.pixelSize: 20
- wrapMode: Text.WordWrap
- }
- }
- }
- }