我们知道对于一些应用来说,判断方位可以使得我们可以重新定位我们的应用的布局,以使得我们的应用在不同的方位中更加合理及好看。在这篇文章中,我们来介绍如何来侦测应用方位的变化。
我们首先来创建一个我们自己的简单的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 manifest
applicationName: "orientation.liu-xiao-guo"
/*
This property enables the application to change orientation
when the device is rotated. The default is false.
*/
automaticOrientation: true
// Removes the old toolbar and enables new features of the new header.
useDeprecatedToolbar: false
width: units.gu(60)
height: units.gu(85)
property bool isLandscape: pageStack.width > pageStack.height ? true : false
onWidthChanged: {
console.log("Main width is changed: " + width)
}
...
}
automaticOrientation: true
我们也尝试使用:
onWidthChanged: {
console.log("Main width is changed: " + width)
}
无论我们怎么晃动我们的手机,我们发现,上面的方法只被调用过一次,再也没有被调用过。所以用这种方法不可以。
我们也尝试在Page中使用同样的伎俩:
Page {
id: page1
title: i18n.tr("Orientation")
anchors.fill: parent
onWidthChanged: {
console.log("Page width is changed: " + width);
}
...
}
我们发现:
qml: PageStack height is changed: 768
qml: orientation: 1
qml: Page width is changed: 768
qml: PageStack width is changed: 768
qml: root width: 768
qml: PageStack height is changed: 1222
qml: orientation: 4
qml: Page width is changed: 1222
这个Page的width是有变化的。为了方便,我们使用了PageStack来侦测width的变化:
PageStack {
id: pageStack
anchors.fill: parent
onWidthChanged: {
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: sensor
active: true
alwaysOn: true
onReadingChanged: {
displayOrientation(reading);
}
}
运行一下我们的应用,可以看到:
整个项目的源码在:https://github.com/liu-xiao-guo/orientation