如何在Ubuntu QML应用中判断应用的方位(landscape或portrait)

我们知道对于一些应用来说,判断方位可以使得我们可以重新定位我们的应用的布局,以使得我们的应用在不同的方位中更加合理及好看。在这篇文章中,我们来介绍如何来侦测应用方位的变化。

我们首先来创建一个我们自己的简单的QML应用。对于大多数的QML应用来说,一般是含有一个“MainView”的:

MainView {id: root// objectName for functional testing purposes (autopilot-qt5)objectName: "mainView"// Note! applicationName needs to match the "name" field of the click manifestapplicationName: "orientation.liu-xiao-guo"/*This property enables the application to change orientationwhen the device is rotated. The default is false.*/automaticOrientation: true// Removes the old toolbar and enables new features of the new header.useDeprecatedToolbar: falsewidth: units.gu(60)height: units.gu(85)property bool isLandscape: pageStack.width > pageStack.height ? true : falseonWidthChanged: {console.log("Main width is changed: " + width)} …}

为了能够使得我们的应用能够在水平及垂直方向变动,我们必须打开这个开关:

automaticOrientation: true我们也尝试使用:

onWidthChanged: {console.log("Main width is changed: " + width)}无论我们怎么晃动我们的手机,我们发现,上面的方法只被调用过一次,再也没有被调用过。所以用这种方法不可以。

我们也尝试在Page中使用同样的伎俩:

Page {id: page1title: i18n.tr("Orientation")anchors.fill: parentonWidthChanged: {console.log("Page width is changed: " + width);}…}我们发现:

qml: PageStack height is changed: 768qml: orientation: 1qml: Page width is changed: 768qml: PageStack width is changed: 768qml: root width: 768qml: PageStack height is changed: 1222qml: orientation: 4qml: Page width is changed: 1222这个Page的width是有变化的。为了方便,我们使用了PageStack来侦测width的变化:

PageStack {id: pageStackanchors.fill: parentonWidthChanged: {console.log("PageStack width is changed: " + width);console.log("root width: " + root.width);}onHeightChanged: {console.log("PageStack height is changed: " + height);}}在我们的MainView中,我们可以定义一个变量:

property bool isLandscape: pageStack.width > pageStack.height ? true : false这样通过这个变量,我们很容知道我们的应用是在什么一个方位的。

另外,我们也可以通过OrientationSensor来侦测手机方位的变化:

function displayOrientation(reading) {orientation.text = "unknown"console.log("orientation: " + reading.orientation);if ( reading.orientation === OrientationReading.TopUp) {orientation.text = "TopUp";} else if ( reading.orientation === OrientationReading.TopDown) {orientation.text = "TopDown";} else if ( reading.orientation === OrientationReading.LeftUp) {orientation.text = "LeftUp";} else if ( reading.orientation === OrientationReading.RightUp) {orientation.text= "RightUp";} else if ( reading.orientation === OrientationReading.FaceDown) {orientation.text = "FaceDown";} else if ( reading.orientation === OrientationReading.FaceUp) {orientation.text = "FaceUp";}}OrientationSensor {id: sensoractive: truealwaysOn: trueonReadingChanged: {displayOrientation(reading);}}

运行一下我们的应用,,可以看到:

整个项目的源码在:git clonehttps://gitcafe.com/ubuntu/oirentation.git

醒来第一眼看见的是他,然后倒头继续睡。这就是我想要的幸福。

如何在Ubuntu QML应用中判断应用的方位(landscape或portrait)

相关文章:

你感兴趣的文章:

标签云: