Screen 是 Qt Quick 提供的一个类型,用于访问屏幕相关信息(如分辨率、DPI、方向等)。它通常与 Window 或 ApplicationWindow 一起使用来管理多屏幕应用。
属性
属性 | 类型 | 描述 | 示例 |
---|---|---|---|
name | string | 屏幕名称 | "HDMI-1" |
manufacturer | string | 屏幕制造商 | "Samsung" |
model | string | 屏幕型号 | "U28E590" |
serialNumber | string | 屏幕序列号 | "XYZ123" |
width | int | 屏幕宽度(像素) | 1920 |
height | int | 屏幕高度(像素) | 1080 |
desktopAvailableWidth | int | 可用宽度(减去任务栏等) | 1920 |
desktopAvailableHeight | int | 可用高度(减去任务栏等) | 1040 |
pixelDensity | real | 每毫米像素数(物理密度) | 3.4 |
logicalPixelDensity | real | 逻辑像素密度(考虑缩放) | 2.0 |
primaryOrientation | enum | 主方向(Portrait/Landscape等) | Qt.LandscapeOrientation |
orientation | enum | 当前方向 | Qt.PortraitOrientation |
orientationUpdateMask | enum | 监听哪些方向变化 | Qt.PrimaryOrientation |
virtualX | int | 虚拟桌面中的X位置 | 0 |
virtualY | int | 虚拟桌面中的Y位置 | 1080 (第二屏幕) |
primary | bool | 是否是主屏幕 | true |
方法
方法 | 参数 | 返回值 | 描述 |
---|---|---|---|
setOrientation() | orientation (enum) | void | 强制设置屏幕方向 |
angleBetween() | a , b (两个enum方向) | int | 计算两个方向间的角度差 |
方向枚举值:
qml
Qt.PrimaryOrientation
Qt.PortraitOrientation
Qt.LandscapeOrientation
Qt.InvertedPortraitOrientation
Qt.InvertedLandscapeOrientation
信号
信号 | 参数 | 描述 |
---|---|---|
orientationChanged() | orientation (enum) | 屏幕方向改变时触发 |
geometryChanged() | - | 屏幕尺寸或位置变化时触发 |
physicalDotsPerInchChanged() | dpi (real) | 物理DPI变化时触发 |
logicalDotsPerInchChanged() | dpi (real) | 逻辑DPI变化时触发 |
primaryChanged() | isPrimary (bool) | 主屏幕状态变化时触发 |
基础使用示例
qml
import QtQuick 2.15
import QtQuick.Window 2.15
Window {
visible: true
title: "Screen Info Demo"
// 获取主屏幕引用
property var primaryScreen: Screen.primaryScreen
Text {
anchors.centerIn: parent
text: `
屏幕名称: ${primaryScreen.name}
分辨率: ${primaryScreen.width}x${primaryScreen.height}
物理DPI: ${primaryScreen.pixelDensity * 25.4} (${primaryScreen.pixelDensity} px/mm)
当前方向: ${getOrientationName(primaryScreen.orientation)}
${primaryScreen.primary ? "主屏幕" : "副屏幕"}
`
wrapMode: Text.Wrap
}
function getOrientationName(ori) {
const map = {
0: "Primary",
1: "Portrait",
2: "Landscape",
3: "InvertedPortrait",
4: "InvertedLandscape"
}
return map[ori] || "Unknown"
}
}
多屏幕管理示例
qml
// 获取所有屏幕列表
property var screens: Screen.screens
// 在第二屏幕创建窗口
Component.onCompleted: {
if (screens.length > 1) {
secondWindow.screen = screens[1]
secondWindow.show()
}
}
Window {
id: secondWindow
width: 800
height: 600
title: "Second Screen Window"
}
常见应用场景
-
响应式布局:
qml
GridView { cellWidth: Screen.desktopAvailableWidth / 4 cellHeight: Screen.desktopAvailableHeight / 4 }
-
多屏幕应用:
qml
Window { screen: Qt.application.screens[1] // 显示在第二个屏幕 }
-
方向检测:
qml
Screen.onOrientationChanged: { if (orientation === Qt.LandscapeOrientation) { console.log("横向模式") } }
-
DPI适配:
qml
Text { font.pixelSize: 12 * Screen.logicalPixelDensity }