I am trying to implement a component which should by default (if no width
was explicitly set) take up as much space as it needs (i.e. depending on its implicitWidth
). And if width
was set at definition it should shrink its contents to fit in the provided area.
Here's an example:
import QtQuick 2.2
import QtQuick.Window 2.0
Window {
width: 200
height: 100
visible: true
property bool restricted: false
Component {
id: external
FocusScope {
implicitWidth: column.implicitWidth
implicitHeight: column.implicitHeight
focus: true
Column {
id: column
width: parent.width > 0 ? parent.width : undefined
Text {
id: label
width: parent.width > 0 ? parent.width : undefined
elide: Text.ElideRight
font.pixelSize: 24
text: "1234567890"
}
}
Keys.onRightPressed: label.text += label.text
}
}
Loader {
width: restricted ? 100 : undefined
sourceComponent: external
focus: true
Keys.onReturnPressed: restricted = !restricted
}
}
In this sample two modes are controlled by auxiliary bool
property, and I want it to support two forms of declaration:
Explicit width.
Text
should elide.Loader { width: 100 sourceComponent: external focus: true }
Loader
width should be enough to fit the whole text without eliding.Loader { sourceComponent: external focus: true }
Motivation is that such a component will be defined in a separate file and is being designed to be placed in different parts of UI with both behaviors desired depending on current needs. This sample with inline component declaration is only for demonstration purpose.
UPDATE:
The following trick parent.width > 0 ? parent.width : undefined
works, but only for initial setup. If component contents change and implicitWidth
is updated (in an unrestricted
mode) the width of the component does not change (i.e. Text
remains elided).
For example, press right key just right after launching example. You should see that Text
has become elided, but its width did not increased
twice regardless the fact that string was duplicated.