Atsushi4のブログ

へたれQtプログラマの備忘録的ななにか

Qt Quickで縦と横のレイアウトを切り替える

Qt勉強会 #40 @Tokyo での自分のもくもく内容です。
qt-users.connpass.com

Qt Quickアプリケーションを自分のAndroid端末で動かしてみよう、というのが当日のターゲットでした。
ここで、Androidアプリなら画面の縦横切替が欲しいなーと思ってちょっと悩んだのでその内容です。

つまりこんな感じで縦横を切り替えたい、ということです。


f:id:Atsushi4:20161025091819p:plain


f:id:Atsushi4:20161025091833p:plain

結局また Tasuku Suzuki (@task_jp) | Twitter せんせーの助言を受けつつ
とにかく動いたので上げておきます。

GridLayoutのflowで縦横レイアウト方向が変えられるようです。
ブログ用に1ファイルで書いています。良い子は真似しない。

あと、縦横の判定はScreen.orientationが使えるぽいですが
今回はデスクトップでも動くように縦横比較にしました。

嘘です。jsでこのフラグの書き方が良くわかりません。


MainWindow.qml とか。Qt Creatorから 「ツール」-「外部」-「Qt Quick」-「Qt Quick 2 Preview」で動くと思います。

import QtQuick 2.5
import QtQuick.Layouts 1.1

Item {
    GridLayout {
        id: layout
        property int spacing: 9
        columnSpacing: spacing
        rowSpacing: spacing
        anchors.fill: parent
        anchors.margins: 15
        GridLayout {
            id: buttons
            property int buttonSize: (Math.max(width, height) - (spacing * 8)) / 9
            property int spacing: 9
            signal pressed(string buttonText)
            flow: GridLayout.TopToBottom
            onPressed: text.text = buttonText
            Layout.preferredWidth: buttonSize
            Layout.preferredHeight: parent.height
            rowSpacing: spacing
            columnSpacing: spacing
            onWidthChanged: console.debug(width, height, buttonSize)
            Repeater {
                model: 9
                Rectangle {
                    color: '#CC9'
                    Layout.preferredWidth: buttons.buttonSize
                    Layout.preferredHeight: buttons.buttonSize
                    radius: buttons.buttonSize / 5
                    Text {
                        text: index + 1
                        font.pixelSize: 24
                        anchors.centerIn: parent
                    }
                    MouseArea {
                        anchors.fill: parent
                        onClicked: buttons.pressed(index + 1)
                    }
                }
            }
        }
        Rectangle {
            color: '#9CC'
            Layout.fillWidth: true
            Layout.fillHeight: true
            Text {
                id: text
                text: "Hello Layout"
                font.pixelSize: 36
                anchors.centerIn: parent
            }
        }
    }
    state: width < height ? "vertical" : ""
    states: [
        State {
            name: "vertical"

            PropertyChanges {
                target: layout
                flow: GridLayout.TopToBottom
            }

            PropertyChanges {
                target: buttons
                Layout.preferredWidth: layout.width
                Layout.preferredHeight: buttonSize
                flow: GridLayout.LeftToRight
            }
        }
    ]
}

おしまい。