如何在QML + JS中为水平和垂直方向设置不同的锚点

时间:2019-04-16 11:01:14

标签: javascript qml positioning

我有用于布局的qml模型,并且希望将屏幕旋转90度。旋转的一切都工作正常,但我对定位有疑问。

我有两个正方形。如果视图是水平的-我想让它们水平地彼此相邻,每个屏幕宽度为1/4。当屏幕垂直时:我想让它们一上一下,分别为1/2屏幕宽度,看:

+-------------+    +---------+
|             |    |         | 
|   AAA BBB   |    |  AAAAA  |
|   AAA BBB   |    |  AAAAA  |
|             |    |  BBBBB  |
+-------------+    |  BBBBB  |
                   |         |
                   +---------+

我可以将每个锚点设置为:anchors.left: horizontal() ? parent.left : id_of_a.left 其中horizontal()是一个js函数,但看起来似乎不太清楚。

如何根据方向设置不同的锚点?

1 个答案:

答案 0 :(得分:0)

您可以更改条件以使用此“ isHorizo​​ntal”属性,也可以将自己的代码添加到最新的if中。将此代码添加到您的主页。

property bool changeOfWidth: false;
property bool changeOfHeight: false;
property bool newOrientation: false;
property bool isHorizontal: false;

onWidthChanged: {
    changeOfWidth = true; 
    newOrientation = (changeOfWidth && changeOfHeight);
}
onHeightChanged: {
    changeOfHeight = true; 
    newOrientation = (changeOfWidth && changeOfHeight);
}

onNewOrientationChanged: {
    if (newOrientation) {
        changeOfWidth = false;
        changeOfHeight = false;
        isHorizontal = width > height;
        if (isHorizontal) {
            // landscape
            console.log("landscape");
        } else {
            // portrait
            console.log("portrait");
        }
    }
}

对于Qt 5.2和更高版本:

import QtQuick.Window 2.2;

property bool isHorizontal: 
    Screen.primaryOrientation === Qt.LandscapeOrientation ||
    Screen.primaryOrientation === Qt.InvertedLandscapeOrientation;

onIsHorizontalChanged: {
    if (isHorizontal) {
        // landscape
        console.log("landscape");
    } else {
        // portrait
        console.log("portrait");
    }
}