对于有些应用来说,获取屏幕分辨率这个信息可能是重要的。比如有些游戏或阅读器应用,希望在应用启动后,马上得到屏幕的分辨率,这样可以和容易地适配不同屏幕尺寸的手机或装置。有些应用可以是用QtQuick.Window的Screen来得到这个信息,但是我们可以看一下在文章中如下的提醒:
Note that the Screen type is not valid at Component.onCompleted, because the Item or Window has not been displayed on a screen by this time.
为了能够在应用启动时得到屏幕的分辨率,我们可以使用C++的代码来实现。
screen.h
#ifndef SCREEN_H
#define SCREEN_H
#include <QObject>
#include <QGuiApplication>
#include <QScreen>
#include <QDebug>
class Screen : public QObject
{
Q_OBJECT
public:
Q_PROPERTY(int height READ height)
Q_PROPERTY(int width READ width)
explicit Screen(QObject *parent = 0);
int height() { return m_height; };
int width() { return m_width; };
private:
int m_height;
int m_width;
};
#endif // FILEIO_H
screen.cpp
#include "screen.h"
Screen::Screen(QObject *parent) : QObject(parent)
{
QScreen* screen = QGuiApplication::primaryScreen();
QSize screenSize = screen->size();
qDebug() << "width: " << screenSize.width();
m_width = screenSize.width();
m_height = screenSize.height();
}
我们可以使用Ubuntu SDK提供的“QML App with C++ plugin (cmake)”来创建一个应用来测试。测试应用的代码如下:
import QtQuick 2.0
import Ubuntu.Components 1.1
import Screen 1.0
import QtQuick.Window 2.0
/*!
\brief MainView with Tabs element.
First Tab has a single Label and
second Tab has a single ToolbarAction.
*/
MainView {
// objectName for functional testing purposes (autopilot-qt5)
objectName: "mainView"
// Note! applicationName needs to match the "name" field of the click manifest
applicationName: "screen.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(50)
height: units.gu(76)
MyScreen {
id: screen
}
Page {
title: i18n.tr("App with backend")
MyType {
id: myType
Component.onCompleted: {
myType.helloWorld = i18n.tr("Hello world..")
}
}
Column {
spacing: units.gu(1)
anchors {
margins: units.gu(2)
fill: parent
}
Label {
id: label
objectName: "label"
text: myType.helloWorld
}
Button {
objectName: "button"
width: parent.width
text: i18n.tr("Tap me!")
onClicked: {
myType.helloWorld = i18n.tr("..from Cpp Backend")
}
}
}
Component.onCompleted: {
console.log("screen width: " + screen.width);
console.log("screen height: " + screen.height);
console.log("SCREEN width: " + Screen.width );
console.log("SCREEN height: " + Screen.height)
}
}
}
我们应用的输出为:
qml: screen width: 768
qml: screen height: 1280
qml: SCREEN width: 0
qml: SCREEN height: 0
我们可以看出来,MyScreen得到了正确的分辨率,但是“Screen.width”及“Screen.height”得到的是“0”。
整个项目的源码在:https://github.com/liu-xiao-guo/screen