制作适应屏幕旋转的QML界面

引言

当手机由竖屏切换成横屏时我们通常需要调整程序的UI布局以适应屏幕; 或者更进一步当手机的方向发生变化时,如果我们也想让程序的UI随之改变该怎么做呢?那么本文就为大家介绍一种思路。


使用sensor感知方向变化

现在QML中已经可以直接使用Sensor了,不需要我们自己再通过c++代码的方式间接访问。我们获得当前手机方向信息后,就把当前状态设置为对应状态,而后我吗就可以根据不同的状态进行布局了。

OrientationSensor {
        id: orientation
        active: true

        onReadingChanged: {
            if (reading.orientation == OrientationReading.TopUp)
                content.state = "TopUp";
            else if (reading.orientation == OrientationReading.TopDown)
                content.state = "TopDown";
            else if (reading.orientation == OrientationReading.LeftUp)
                content.state = "LeftUp";
            else if (reading.orientation == OrientationReading.RightUp)
                content.state = "RightUp";
            else if (reading.orientation == OrientationReading.FaceUp)
                content.state = "FaceUp";
            else if (reading.orientation == OrientationReading.FaceDown)
                content.state = "FaceDown";
            else
                content.state = "";
        }
    }


切换布局

根据状态设置每一个矩形的宽度,从而适应屏幕的变化。

Flow {
            anchors.top: parent.top
            anchors.left: parent.left
            anchors.right: parent.right
            anchors.margins: 10
            spacing: 4
            Rectangle {
                width: (content.state == "LeftUp" || content.state == "RightUp") ? (parent.width-8)/3 : (parent.width-4)/2
                height: 60
                color: "yellow"
                Text {
                    text: "1"
                    color: "black"
                    font.pointSize: 10
                    anchors.centerIn: parent
                }
            }
// ...以下省略


程序截图

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值