QtQuick 2.12 如何实现页面垂直滑动,低版本SwipeView是否支持?
Qt Quick Controls 2.12实现垂直页面滑动切换的解决方案
基于现有SwipeView实现垂直滑动的方案
Qt Quick Controls 2.12版本的SwipeView确实没有内置vertical属性,但可以通过坐标旋转的方式低成本实现垂直滑动效果,不需要额外改写组件逻辑,仅需对SwipeView和内部页面做反向旋转处理即可,示例代码如下:
SwipeView { id: view currentIndex: 0 anchors.centerIn: parent // 旋转整个SwipeView,将原生水平滑动方向转为垂直 rotation: -90 // 旋转后适配父容器尺寸 width: parent.height height: parent.width Item { id: mainPage // 反向旋转内容,保证页面显示方向正常 rotation: 90 anchors.fill: parent PageMain{} } Item { id: secondPage rotation: 90 anchors.fill: parent } }
该方案适配成本极低,适合页面交互逻辑简单的场景;如果页面内存在依赖触摸坐标的自定义交互,需要额外处理旋转带来的坐标映射问题。
其他可行实现方案
如果不想使用旋转的兼容方案,还有两种更稳定的原生实现方案,无版本限制:
自定义Flickable实现
基于原生Flickable组件实现,逻辑完全可控,支持自定义滑动阻尼、动画效果等参数,适配所有Qt Quick版本,示例代码如下:
Flickable { id: verticalFlick anchors.fill: parent contentWidth: width // 页面总高度 = 单页面高度 * 页面数量,可根据实际页面数动态调整 contentHeight: height * 2 flickableDirection: Flickable.VerticalFlick snapMode: Flickable.SnapToItem property int currentIndex: 0 onCurrentIndexChanged: contentY = currentIndex * height // 滑动结束后自动吸附到对应页面 onMovementEnded: { currentIndex = Math.round(contentY / height) } Item { id: mainPage height: parent.height width: parent.width y: 0 PageMain{} } Item { id: secondPage height: parent.height width: parent.width y: parent.height } }基于ListView实现
利用ListView自带的吸附能力实现页面切换,无需自己处理滑动结束的吸附逻辑,代码更简洁,还可复用ListView的懒加载、缓存能力,适合页面数量较多的场景,示例代码如下:
ListView { id: pageList anchors.fill: parent orientation: ListView.Vertical snapMode: ListView.SnapOneItem highlightRangeMode: ListView.StrictlyEnforceRange currentIndex: 0 // 隐藏默认滚动条 ScrollBar.vertical: null // 页面数量,可根据实际需求调整 model: 2 delegate: Item { width: ListView.view.width height: ListView.view.height Loader { anchors.fill: parent sourceComponent: index === 0 ? mainPageComp : secondPageComp } } Component { id: mainPageComp PageMain{} } Component { id: secondPageComp Item {} } }
内容的提问来源于stack exchange,提问作者Pascal Achtel
相关产品推荐
相关产品推荐

