QT QML侧边导航栏

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

QT QML侧边导航栏

何名取   2022-06-19 我要评论

TabBar

在实际开发中导航栏是必不可少的控件,QtQuick Controls控件中可以使用TabBar来做导航栏,原始的导航栏是横向的,查找了其属性后发现无法直接设置为纵向的。本节将给小伙伴们介绍一种非常简单的实现实现QML侧边导航栏的最简方法。原始导航栏如下图:

属性列表

允许用户在不同的视图或子任务之间切换。标签栏提供了一个基于标签的导航模型。TabBar由TabButton控件填充,可以与任何提供currentIndex -属性的布局或容器控件一起使用,如StackLayout或SwipeView。

属性类型描述
contentHeightreal此属性保存内容高度。它用于计算选项卡栏的隐式总高度。
contentWidthreal此属性保存内容宽度。它用于计算选项卡栏的隐式总宽度。
positionenumeration此属性保存选项卡栏的位置。
TabBar.HeaderTabBar.Footer
附加属性类型描述
indexint这个附加属性保存TabBar中每个选项卡按钮的索引。它被附加到TabBar的每个选项卡按钮上。
positionenumeration这个附加属性保存选项卡栏的位置。它被附加到TabBar的每个选项卡按钮上。
TabBar.HeaderTabBar.Footer
tabBarTabBar此附加属性保存管理此选项卡按钮的选项卡栏。它被附加到TabBar的每个选项卡按钮上。

示例代码

    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
        }
    }

在TabBar中添加三个TabButton,点击TabButton可以实现对StackLayout中相应的Item的切换。

侧边导航栏

从position属性中可以看出,TabBar只能直接设置为顶部和底部,无法直接应用成侧边导航栏。此时,需要将 TabBar和TabButton的大小和位置进行调整,即可实现侧边导航栏。

修改代码

TabBar宽度影响自身和内部包含的TabButton的宽度。横向排列时,TabBar的宽度等于三个TabButton的宽度;纵向排列时,TabBar的宽度等于一个TabButton的宽度。

其次需要改变TabButton的宽度,高度以及排列的位置。横向排列时,TabButton的宽度大于高度;纵向排列时,为了美观,使TabButton的宽度小于高度。将所有TabButton都设置为首位相连,即第一个TabButton的bottom底部就是第二个TabButton的顶部。

    TabBar {
        id: bar
        width: firstBtn.width
        TabButton {
            id: firstBtn
            text: qsTr("Home")
            width: root.width/8
            height: root.height/3
            anchors.horizontalCenter: parent.horizontalCenter
            anchors.top: parent.top
        }
        TabButton {
            id: secondBtn
            text: qsTr("Discover")
            width: root.width/8
            height: root.height/3
            anchors.horizontalCenter: parent.horizontalCenter
            anchors.top: firstBtn.bottom
        }
        TabButton {
            id: thirdBtn
            text: qsTr("Activity")
            width: root.width/8
            height: root.height/3
            anchors.horizontalCenter: parent.horizontalCenter
            anchors.top: secondBtn.bottom
        }
    }

总结

以上就是实现实现QML侧边导航栏的最简方法,除此之外还可以自定义绘制导航栏控件,不过比起本节介绍的方法较为复杂,不如这种方法来得快捷。更多相关QT QML侧边导航栏内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们