我想在QML中使用Screen.pixelDensity
来计算可视组件的大小。为了将元素的属性保存在一个地方(有几个),我创建了一个容器对象:
import QtQuick 2.0
Item
{
readonly property double constantValue: 100 * Screen.pixelDensity
property double first
property double second: first + constantValue
// and so on
Component.onCompleted: console.log(Screen.pixelDensity) // (1)
}
初始化对象时,语句(1)报告Screen.pixelDensity == 0
如果我在main.qml中添加相同的语句:
import QtQuick 2.2
import QtQuick.Controls 1.1
import QtQuick.Window 2.0
ApplicationWindow
{
title: qsTr("title")
width: 480
height: 800
// some visual stuff here
Component.onCompleted: console.log("testing: " + Screen.pixelDensity)
}
然后报告Screen.pixelDensity
非零,正如预期的那样。
为什么财产在第一种情况下行为不端?
答案 0 :(得分:2)
在组件完成后,Screen附加对象在Item或Item派生类型中有效。在这些项目中,它指的是当前正在显示该项目的屏幕。
如果项目没有显示(这是我从你的问题中理解的那样)那么信息就无法到达......因此它显示为0.