`
icheng
  • 浏览: 833229 次
  • 性别: Icon_minigender_1
  • 来自: 珠海
文章分类
社区版块
存档分类
最新评论

制作适应屏幕旋转的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
                }
            }
// ...以下省略


程序截图

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics