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

348 views Asked by At

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

There are 1 answers

0
Thomas Ayoub On BEST ANSWER

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.