Solved Proper use of anchors.baseline
-
I need to display lots of meter readings, e.g. "440 hertz" and sometimes to be a more fancy or descriptive, like "frequency: 440 hertz" possibly on a flashing background. Starting is easy enough:
Item { Text { id: description text: "frequency:" verticalAlignment: Qt.AlignCenter } Row { anchors.baseline: description.baseline anchors.left: description.right width: implicitWidth id: reading Text { id: value text: "440" anchors.baseline: reading.baseline } Text { id: units text: "hertz" anchors.baseline: value.baseline } }
(to keep this example simple I kept Row inline instead of moving it to a separate Component).
And it works! But let's add some color:Item { Rectangle { anchors.fill: reading color: "red" } Rectangle { anchors.fill: description color: "green" } //code from here is the same as in previous example Text { id: description text: "frequency:" verticalAlignment: Qt.AlignCenter } Row { anchors.baseline: description.baseline anchors.left: description.right width: implicitWidth id: reading Text { id: value text: "440" anchors.baseline: reading.baseline } Text { id: units text: "hertz" anchors.baseline: value.baseline } }
Now it's looking weird...
The documentation clearly states that baselines for non-text objects (like Row) equals top, so this behavior is by design and not a QML bug.
Therefore I'm doing it wrong: so my question is what's the proper way to extend baseline alignment while traversing non-text containers? My goal is to write a 'Reading' component to be used alone, or as a bulding block of a more complete object (adding description, flashing background to name a few). -
The solution is to set the
baselineOffset
property of your Row to one of your nested Text object:baselineOffset: value.baselineOffset
You can then use anchors.baseline with it.
-
The solution is to set the
baselineOffset
property of your Row to one of your nested Text object:baselineOffset: value.baselineOffset
You can then use anchors.baseline with it.
-
@GrecKo Beautiful solution, for some unknown reason I was erroneously thinking of the baseline like a sort of read-only property dictated by font geometries, instead of something that can be moved. Cleaner and simpler, thank you!