`Screen.pixelDensity` 在非可视组件中等于 0
`Screen.pixelDensity` equals 0 in non-visual components
我想在 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
被报告为非零,正如预期的那样。
为什么 属性 在第一种情况下行为不正常?
中所述
The Screen attached object is valid inside Item or Item derived types, after component completion. Inside these items it refers to the screen that the item is currently being displayed on.
如果没有显示该项目(我从你的问题中了解到)则无法访问该信息...因此显示0.
我想在 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
被报告为非零,正如预期的那样。
为什么 属性 在第一种情况下行为不正常?
The Screen attached object is valid inside Item or Item derived types, after component completion. Inside these items it refers to the screen that the item is currently being displayed on.
如果没有显示该项目(我从你的问题中了解到)则无法访问该信息...因此显示0.