`Screen.pixelDensity` equals 0 in non-visual components

半城伤御伤魂 提交于 2019-12-11 03:28:34

问题


I want to use Screen.pixelDensity in QML to calculate the size of my visual components. In order to keep an element's properties in one place (there are a couple of them) I created a container object:

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)
}

When the object is initialized, the statement (1) reports that Screen.pixelDensity == 0

If I put the same statement in my 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)
}

then Screen.pixelDensity is reported to be non-zero, as expected.

Why does the property misbehave in the first case?


回答1:


As mentioned in the 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.

If the item is not displayed (that's what I understood from your question) then the information can't be reached... Thus it displays 0.



来源:https://stackoverflow.com/questions/30996576/screen-pixeldensity-equals-0-in-non-visual-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!