我想在 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
报告为非零。
为什么该属性在第一种情况下行为不当?
最佳答案
如 QML doc for Screen
中所述
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。
关于qt - `Screen.pixelDensity` 在非可视组件中等于 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30996576/