Search code examples
qtwidgetqmlkde-plasma

QML/Qt: Make displayed text as large as possible depending on the parent containing it


I am trying to make a very simple KDE-Plasma Widget where only a certain number is displayed. I want to make this displayed number have a font size as large as possible depending on the parent containing it. Here is what it looks right now:

enter image description here

As you can see, the text inside has a lot of space around it. What I actually want it to be is something like the "Date And Time" Widget found in KDE Plasma (my widget is right next to it for comparison):

enter image description here

Here, the time displayed has much lesser space around it while also auto-resizing whenever the panel height is changed.

Here is what the current code looks like:

import QtQuick 2.6
import QtQuick.Layouts 1.0
import org.kde.plasma.components 2.0 as PlasmaComponents
import org.kde.plasma.plasmoid 2.0


Item {
    id: main
    anchors.fill: parent
    Layout.minimumWidth: units.iconSizes.large
    Layout.minimumHeight: units.iconSizes.large

    
    Plasmoid.preferredRepresentation: Plasmoid.fullRepresentation


    PlasmaComponents.Label {
        id: display

        anchors {
            fill: parent
            margins: Math.round(parent.width * 0.1)
        }

        verticalAlignment: Text.AlignVCenter
        horizontalAlignment: Text.AlignHCenter

        text: foobar

        font.pixelSize: 1000;
        minimumPointSize: theme.smallestFont.pointSize
        fontSizeMode: Text.Fit
        font.bold: true
    }

    Timer {
        some stuff
    }
}


I tried looking into the code of the above Date and Time widget and wrote down the exact same layouts/controls (which is what you are seeing in the above code) with the same positioning/styling properties and yet I get a lot of space around my text/or the font size continues to remain small.


Solution

  • Thanks to @JarMan's input I was able to realize that my text was being rendered in small font because of lack of space due to the root (item) element being square in shape.

    I have now figured that to change the layout sizes of the root element inside the KDE-Plasma panel, one needs to mess with Layout.preferredWidth and Layout.preferredHeight.

    Here is what I did:

    item {
        .
        .
        Layout.preferredWidth: 150 * units.devicePixelRatio
        Layout.preferredHeight: 50 * units.devicePixelRatio
        .
        .
    }
    

    Note: the 150 and 50 values aren't final. It basically gives an idea about the ratio at which the root element's width and height should be in (and I wanted a rectangle). It automatically resizes the inner content too as the Plasma Panel is resized.