标签:
我们知道对于一些应用来说,判断方位可以使得我们可以重新定位我们的应用的布局,以使得我们的应用在不同的方位中更加合理及好看。在这篇文章中,我们来介绍如何来侦测应用方位的变化。
我们首先来创建一个我们自己的简单的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
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);
}
}
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);
}
}
运行一下我们的应用,可以看到:
整个项目的源码在:git clone https://gitcafe.com/ubuntu/oirentation.git
如何在Ubuntu QML应用中判断应用的方位(landscape或portrait)
标签:
原文地址:http://blog.csdn.net/ubuntutouch/article/details/45868417