I am using Qt Quick to develop an app (Qt 5.8). I have text that appears in multiple places so I created a component to use to display the text. The areas the text can vary in placement and size. How can I adjust my text so that the data displays in 1 line horizontally and all text is the same size if I simply want to display the following?
FLAPS 1
GEAR DOWN
TRIM -1.0
I used Text and was able to get close, however since GEAR DOWN has more characters the text was smaller, than flaps and trim. So I moved on to using Label. Can someone provide better insight on how to have text size based on its container's width or height?
main.qml
import QtQuick 2.6
import QtQuick.Window 2.2
Window {
id: windowRoot
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Rectangle{
height: windowRoot.height * .80
width: windowRoot.width * .80
color: "green"
anchors.centerIn: parent
Rectangle {
id: rect1
opacity: .5
anchors.top: parent.top
anchors.left: parent.left
color: "lime"
border.color: "orange"
height: parent.height * 1/2
width: parent.width * 1/2
TextHolder {
anchors.top: parent.top
anchors.left: parent.left
width: parent.width * 1/4
height: parent.height
}
}
Rectangle {
id: rect2
anchors.top: parent.top
anchors.left: rect1.right
color: "yellow"
border.color: "blue"
height: parent.height * 1/2
width: parent.width * 1/2
}
Rectangle {
id: rect3
anchors.top: rect1.bottom
anchors.left: parent.left
color: "pink"
border.color: "red"
height: parent.height * 1/2
width: parent.width * 1/2
TextHolder {
anchors.top: parent.top
anchors.left: parent.left
width: parent.width * 1/4
height: parent.height * 1/2
}
}
Rectangle {
id: rect4
anchors.top: rect2.bottom
anchors.left: rect3.right
color: "orange"
border.color: "lime"
height: parent.height * 1/2
width: parent.width * 1/2
TextHolder {
anchors.bottom: parent.bottom
height: parent.height * 1/4
width: parent.width * 1/4
anchors.horizontalCenter: parent.horizontalCenter
}
}
}
}
TextHolder.qml
import QtQuick 2.0
import QtQuick.Layouts 1.1
import QtQuick.Controls 1.1
Rectangle {
color: "purple"
border.color: "steelblue"
border.width: 3
property color colorOfText: "white"
property real textSize: 48
Item {
id: inputs
property int flapHndl: 1
property int gearHndl: 1
property real trim: -1.0
}
clip: true
ColumnLayout {
anchors.top: parent.top
width: parent.width
height: parent.height
spacing: 5
Label {
id: flapLabel
text: "FLAPS " + inputs.flapHndl
color: colorOfText
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
font.pixelSize: textSize
fontSizeMode: Text.HorizontalFit
Layout.fillWidth: true
}
Label {
id: gearLabel
text: {
if (inputs.gearHndl === 1)
return "GEAR DOWN"
else
return "GEAR UP"
}
color: colorOfText
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
font.pixelSize: textSize
fontSizeMode: Text.HorizontalFit
Layout.fillWidth: true
}
Label {
id: trimLabel
text: "TRIM " + inputs.trim.toFixed(1)
color: colorOfText
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
font.pixelSize: textSize
fontSizeMode: Text.HorizontalFit
Layout.fillWidth: true
}
}
}
Can someone provide better insight on how to have text size based on
its container's width or height?
For evaluating the text width and height we can definitely use QML type TextMetrics and having the metrics we can then attempt to fit the text in. If the text still won't fit we can then try to adjust the font size. For that, some logic might need to be implemented with JavaScript. So, the below code is an example of the "feedback" type of solution.
Rectangle {
property string textToShow
property int widthLimit: 400
onTextToShowChanged: {
while (txtMeter.width > widthLimit) {
txtMeter.font.pixelSize --;
}
}
TextMetrics {
id: txtMeter
font.family: "Courier"
font.pixelSize: 25
text: textToShow
}
Text {
font: txtMeter.font
text: textToShow
}
}
P.S. This is just a sketchy idea and your actual implementation may differ
There is fontSizeMode property of Text
Text {
id: goToParentFolderText
anchors.fill: parent
font.family: fontAwesomeSolid.name
text: "\uf060"
fontSizeMode: Text.Fit
font.pointSize: 100
color: Material.accent
}
I was able to get #Alexander V's answer to work, with a minor change. The outer textToShow property was processing its update before the TextMetrics block was updated (which caused the width calculation to be incorrect). You can fix this issue by triggering onTextChanged inside the TextMetrics blocks instead.
Rectangle {
property string textToShow
property int widthLimit: 400
TextMetrics {
id: txtMeter
font.family: "Courier"
font.pixelSize: 25
text: textToShow
onTextChanged: {
while (txtMeter.width > widthLimit) {
txtMeter.font.pixelSize --;
}
}
}
Text {
font: txtMeter.font
text: textToShow
}
}
Related
Basically I want to display a text telling the user if a switch is turned on or off. The words "on" and "off" have a small background associated with them so I thought maybe making two labels would work. Now I have an issue where I'm hard coding the position of the second label, and it doesn't look clean because both of them are not centered. Here is the code:
import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Window 2.0
Window {
visible: true
width: 400
height: 400
property bool switchOn: false
Rectangle {
color: '#D3D3D3'
anchors.fill: parent
Label {
id: sentence
text: qsTr("The switch is currently turned ")
color: 'black'
width: parent.width
wrapMode: Text.Wrap
font.pixelSize: 40
anchors.top: parent.top
Label {
id: endText
text: switchOn ? qsTr(" off ") : qsTr(" on ")
font.pixelSize: 40
color: "white"
anchors {
top: parent.top
left: parent.left
topMargin: 50
leftMargin: 310
}
// #disable-check M16
background: Rectangle {
color: switchOn ? "grey" : "red"
radius: 8
}
}
}
Switch {
id: switch1
anchors.horizontalCenter: parent.horizontalCenter
anchors.top: parent.top
anchors.topMargin: 150
text: qsTr("Switch")
onToggled: switchOn = !switchOn
}
}
}
How can I have that sentence appear as one sentence and center it within a parent object?
EDIT:
Here I can get them in a row, but if my sentence ends on the second row and my first row is longer than the first, the ending text is placed way further than it needs to be:
import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Window 2.0
Window {
visible: true
width: 400
height: 400
property bool switchOn: false
Rectangle {
color: '#D3D3D3'
anchors.fill: parent
Row {
anchors.horizontalCenter: parent.horizontalCenter
Label {
id: sentence
text: qsTr("The switch is currently ")
color: 'black'
width: 300
wrapMode: Text.Wrap
font.pixelSize: 40
anchors.top: parent.top
}
Label {
id: endText
text: switchOn ? qsTr(" off ") : qsTr(" on ")
font.pixelSize: 40
color: "white"
anchors.top: sentence.top
anchors.topMargin: 45
// #disable-check M16
background: Rectangle {
color: switchOn ? "grey" : "red"
radius: 8
}
}
}
Switch {
id: switch1
anchors.horizontalCenter: parent.horizontalCenter
anchors.top: parent.top
anchors.topMargin: 150
text: qsTr("Switch")
onToggled: switchOn = !switchOn
}
}
}
You can do that by using the lineLaidOut signal of the Label. It gives you information about each line's geometry (you can also modify them if needed):
import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Window 2.0
Window {
id: root
visible: true
width: 400
height: 400
property bool switchOn: false
Rectangle {
color: '#D3D3D3'
anchors.fill: parent
Label {
id: sentence
text: qsTr("The switch is currently ")
color: 'black'
anchors.horizontalCenter: parent.horizontalCenter
width: 300
wrapMode: Text.Wrap
font.pixelSize: 40
anchors.top: parent.top
property real lastLineY
property real lastLineWidth
onLineLaidOut: line => {
if (line.isLast) {
lastLineY = line.y;
lastLineWidth = line.implicitWidth
}
}
Label {
id: endText
text: root.switchOn ? qsTr(" off ") : qsTr(" on ")
font.pixelSize: 40
color: "white"
x: sentence.lastLineWidth
y: sentence.lastLineY
background: Rectangle {
color: root.switchOn ? "grey" : "red"
radius: 8
}
}
}
Switch {
anchors.horizontalCenter: parent.horizontalCenter
anchors.top: parent.top
anchors.topMargin: 150
text: qsTr("Switch")
onToggled: root.switchOn = !root.switchOn
}
}
}
You can put the Labels within a Row, and horizontally center the Row.
Rectangle {
color: '#D3D3D3'
anchors.fill: parent
Row {
anchors.horizontalCenter: parent.horizontalCenter
Label {
id: sentence
...
}
Label {
id: endText
anchors.top: sentence.top
...
}
}
}
I have the following SpinBox model which I am trying to recreate using the new QtQuick.Control 2, because this one it's using version 1. And I've encountered some problems which I am not sure how to solve.
On the validation side, I should not be able to write anything on the suffix side, just on the number part. Also I should not be allowed to remote the suffix from there while editing
My width should be fixed and I should not be allowed to write more than that.
My Code:
import QtQuick 2.6
import QtQuick.Controls 2
import QtQuick.Controls.Styles 1.4
import QtGraphicalEffects 1.0
SpinBox {
id: root
property color borderColor: "red"
property string multipleValuesTooltip: ""
property color backgroundColor: "yellow"
property bool showTooltip: true
font.pointSize: 10
property int maximumValue: 50
property int minimumValue: 0
property string suffix: ""
property int decimals: 0
to: maximumValue
from: minimumValue
editable: true
rightPadding: {
console.log(root.contentItem.height)
return Math.max(40, Math.round(root.contentItem.height))
}
textFromValue: function(value, locale) {
return qsTr("%1"+suffix).arg(value);
}
contentItem: TextInput {
z: 5
text: root.textFromValue(root.value, root.locale)
font: root.font
color: "white"
selectionColor: "#21be2b"
selectedTextColor: "#ffffff"
horizontalAlignment: Qt.AlignHCenter
verticalAlignment: Qt.AlignVCenter
validator: root.validator
inputMethodHints: Qt.ImhFormattedNumbersOnly
}
up.indicator: Rectangle {
height: parent.height / 2
anchors.right: parent.right
anchors.top: parent.top
implicitWidth: 20 // Adjust width here
implicitHeight: {
console.log(root.contentItem.height)
return root.contentItem.height - 10
}
color: root.up.pressed ? "red" : "pink"
Image {
source: "qrc:/resources/arrow-down.png"
height: Math.min(15, sourceSize.height)
width: Math.min(30, sourceSize.width)
anchors.centerIn: parent
rotation: 180
}
}
down.indicator: Rectangle {
height: parent.height / 2
anchors.right: parent.right
anchors.bottom: parent.bottom
implicitHeight: root.contentItem.height - 10
implicitWidth: {
console.log("W: ",root.width)
return 20
}
color: root.down.pressed ? "red" : "pink"
Image {
source: "qrc:/resources/arrow-down.png"
height: Math.min(15, sourceSize.height)
width: Math.min(30, sourceSize.width)
anchors.centerIn: parent
}
}
background: Item {
implicitHeight: root.height === 0 ? Math.max(30, Math.round(root.contentItem.height * 1.2)) : root.height
implicitWidth: root.contentItem.width + leftPadding +rightPadding
baselineOffset: root.anchors.baselineOffset
Rectangle {
id: baserect
anchors.fill: parent
color: "purple"
radius: 3
}
Rectangle { // Border only
anchors.fill: parent
border.color: "black"
color: "transparent"
radius: 3
}
Rectangle {
anchors.right: parent.right
anchors.rightMargin: root.rightPadding - 10
anchors.verticalCenter: parent.verticalCenter
color: "black"
height: parent.height - parent.height/5
width: 1
}
}
}
I couldn't find any documentation or any kind of information regarding this wherever I've searched for. If any of you could help me I would be really grateful.
I am trying to use a ListView with a simple header that stays on top of the list. It is working fine for most situations. When I scroll all the way to the top manually the top item is located below the header:
When I set the current index from outside the list to highlight an item the list scrolls to the highlighted item. This is expected and desired behavior. However the list scrolls in a way, that the highlighted item will be on the same height (y) as the header. Therefore the header partially covers the item. In the picture the header is transparent, the highlight is light green:
How can I set up the list so that the list content always starts below the header? Or as a workaround, how can I set the height of the current item after the automatic scroll on selection?
For completeness here is the current code of my list.
ListView {
id: particleList
anchors.fill: parent
model: particleModel
clip: true
highlight: Rectangle { color: Material.color(Material.Green); opacity: 0.2}
highlightMoveDuration: Style.animationDurationMedium
headerPositioning: ListView.OverlayHeader
header: Item {
height: 40
anchors.left: parent.left
anchors.right: parent.right
Row {
anchors.fill: parent
MediumText {
horizontalAlignment: Text.AlignHCenter
width: parent.width / 3
text: qsTr("Width")
}
MediumText {
horizontalAlignment: Text.AlignHCenter
width: parent.width / 3
text: qsTr("Height")
}
MediumText {
horizontalAlignment: Text.AlignHCenter
width: parent.width / 3
text: qsTr("Area")
}
}
}
footer: SmallText {
anchors.left: parent.left
anchors.right: parent.right
text: particleModel.count
}
populate: Transition {
NumberAnimation { properties: "x,y"; duration: 1000 }
}
delegate: Item {
height: 40
anchors.left: parent.left
anchors.right: parent.right
Row {
anchors.fill: parent
MediumText {
anchors.verticalCenter: parent.verticalCenter
width: parent.width / 3
text: model.width
horizontalAlignment: Text.AlignRight
rightPadding: 20
}
MediumText {
anchors.verticalCenter: parent.verticalCenter
width: parent.width / 3
text: model.height
horizontalAlignment: Text.AlignRight
rightPadding: 20
}
MediumText {
anchors.verticalCenter: parent.verticalCenter
width: parent.width / 3
text: model.area
horizontalAlignment: Text.AlignRight
rightPadding: 20
}
}
Rectangle {
anchors.left: parent.left
anchors.right: parent.right
anchors.top: parent.top
height: 1
visible: model.index !== 0
color: Material.color(Material.Grey)
}
}
}
The Listview rows always scroll behind the header.
So make it opaque (e.g. Rectangle with background instead of item) and increase the z value to have it on top.
For the scrolling use highlightRangeMode, preferredHighlightBegin and preferredHighlightEnd.
I have a tab bar with a stacklayout like the following:
Rectangle {
id: rect
height: 190
anchors.right: parent.right
anchors.left: parent.left
color: "transparent"
anchors.top: uniqueHandleText.bottom
anchors.topMargin: 100
TabBar {
id: frame
anchors.right: parent.right
anchors.left: parent.left
background: Rectangle {
color: "#737373"
}
x: -hbar.position * width
Repeater {
model: wizard.categories
TabButton {
id: tabData
property bool selected: false
text: modelData.name
width: 200
font.pixelSize: 18
contentItem: Text {
text: tabData.text
font: tabData.font
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
elide: Text.ElideRight
wrapMode: Text.WordWrap
color: "#FFFFFF"
}
background: Rectangle {
implicitWidth: frame.width
implicitHeight: 180
opacity: enabled ? 1 : 0.3
color: tabData.checked ? "#BD9CBE": "#737373"
}
}
}
}
ScrollBar {
id: hbar
hoverEnabled: true
active: hovered || pressed
orientation: Qt.Horizontal
size: rect.width / frame.width
anchors.left: parent.left
anchors.right: parent.right
anchors.top: frame.bottom
}
Text {
font.pixelSize: 18
text: "Next"
anchors.right: parent.right
visible: frame.x != frame.width ? true: false
}
StackLayout {
id: stack1
anchors.left: parent.left
anchors.right: parent.right
anchors.top: frame.bottom
currentIndex: frame.currentIndex
Repeater {
model: wizard.categories
Item {
id: homeTab
TabBar {
id: homeTabTab
anchors.right: parent.right
anchors.left: parent.left
anchors.top: parent.top
height: 180
background: Rectangle {
color: "#958096"
}
Repeater {
model: modelData.sub_categories
TabButton {
property bool selected: false
id: currentTab
text: modelData.name
width: 200
font.pixelSize: 18
background: Rectangle {
implicitWidth: frame.width
implicitHeight: 180
opacity: enabled ? 1 : 0.3
color: currentTab.checked ? "#958096": "#8D758E"
}
contentItem: Text {
text: currentTab.text
font: currentTab.font
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
elide: Text.ElideRight
wrapMode: Text.WordWrap
color: "#FFFFFF"
MouseArea {
anchors.fill: parent
onClicked: {
if(currentTab.checked){
currentTab.checked = false
} else {
currentTab.checked = true
}
}
onDoubleClicked: {
currentTab.selected = true
var found = false;
var someText = frame.itemAt(stack1.currentIndex).text;
print(someText)
for(var i = 0; i<wizard.selectedSkills.count; i++){
if(wizard.selectedSkills.get(i).name === someText){
wizard.selectedSkills.get(i).sub_categories.append({"name":currentTab.text});
wizard.skills.push({"name": someText})
found = true;
}
}
if(!found){
print(currentTab.text)
wizard.selectedSkills.append({"name":someText, "sub_categories":[{"name":currentTab.text}]})
}
print(window.selectedSkills)
}
}
}
}
}
}
}
}
}
}
I've tried many different things to add a scrollbar or to figure out how to use the flickable functionality that TabBar has. However, the documentation doesn't specify how it works, it just does. Therefore, they are not accessible (or even rewritteable, to use those properties). I want to add a small indicator like an arrow to specify that there is more elements for ease of navigation on desktop on top of the TabBar functionality.
It doesn't seem like the necessary properties are exposed in order to make this happen the easy way.
However, since this is QML, it means the whole object tree is gaping wide open to introspection, allowing us to establish that the item that does the flicking is the contentItem of a ListView inside the Container the ToolBar inherits. The view happens to be the second visible child, although this is technically "private implementation" that one should not rely on. So it is better to take some extra care to establish whether or not you have the correct object.
ApplicationWindow {
id: main
width: 640
height: 480
visible: true
TabBar {
id: toolbar
width: parent.width
height: 50
Repeater {
model: 10
TabButton {
text: "test " + index
width: 100
}
}
}
Rectangle {
height: 5
width: main.width * (view ? view.visibleArea.widthRatio : toolbar.width / toolbar.contentWidth)
color: "red"
anchors.top: toolbar.bottom
x: view ? (main.width - width) * (view.contentX / (view.contentWidth - view.width)) : 0
}
property ListView view: {
var l = toolbar.visibleChildren.length
while (--l) if ("cacheBuffer" in toolbar.visibleChildren[l]) return toolbar.visibleChildren[l]
return null
}
}
And there you have it. We iterate the tabview children until we find one that has a property cacheBuffer which is fairly unique to ListView, and once we have that, we can access the needed properties. As you see, for the indicator width we can do even without the list view, as the toolbar exposes a contentWidth property, but for the indicator position there is no workaround.
And it works:
I'm showing a message on the bottom:
Msg.qml
import QtQuick 2.4
Item {
property alias text: mf.text
anchors.fill: parent
antialiasing: false
opacity: 0.9
z: 100
MsgForm {
id: mf
width: parent.width
y: parent.height - height - 5
}
}
MsgForm.ui.qml
import QtQuick 2.4
Item {
property alias text: msg.text
width: 200
id: message
height: msg.height+10
Rectangle {
id: rectangle
color: "#fb9191"
anchors.fill: parent
border.color: "#fd6666"
border.width: 2
Text {
id: msg
anchors.top: parent.top
anchors.topMargin: 2
textFormat: Text.PlainText
anchors.right: parent.right
anchors.rightMargin: 4
anchors.left: parent.left
anchors.leftMargin: 4
wrapMode: Text.WordWrap
clip: false
font.bold: true
font.pointSize: 12
font.family: "Tahoma"
}
}
}
How can I animate the form to appear from the bottom smoothly?
After the animation, if the window resizes, the message must stay always on the bottom.
You can play with anchors.bottomMargin property to raise the message item from the bottom.
import QtQuick 2.4
Item {
property alias text: mf.text
anchors.fill: parent
antialiasing: false
opacity: 0.9
z: 100
MsgForm {
id: mf
property bool showing: false
width: parent.width
anchors{
bottom: parent.bottom
bottomMargin: mf.showing ? 0 : -mf.height
Behavior on bottomMargin{
NumberAnimation{ }
}
}
}
}
Thanks everyone. In the end I've solved the issue by following advices received in the qtcentre forum.
The desired effect can be achieved easily by defining a local numerical property that is use to bind to either an anchors.XXXXmargin or the y property expression.
Following this approach a possible solution is the following:
MsgForm {
property bool showing: false
property int position: showing ? height : 0
width: parent.width
y: parent.height - position
Behavior on position {
NumberAnimation {duration: 500}
}
}
You can make an animation on the opacity change:
Msg.qml
import QtQuick 2.4
Item {
property alias text: mf.text
anchors.fill: parent
antialiasing: false
opacity: 0.9
z: 100
MouseArea{
anchors.fill: parent
onClicked: mf.opacity = !mf.opacity
}
MsgForm {
id: mf
//y: parent.height - height - 5
opacity:0
Behavior on opacity {
NumberAnimation{
duration:600
}
}
width: parent.width
anchors.bottom: parent.bottom
}
}
or any other NumberAnimation. I recommand you to create States, within it do some propertyChanges, and on some actions, example button clicked change states.
example in your MsgForm.ui.qml add:
MouseArea{
anchors.fill: parent
onClicked: mf.state= "show"
}
and in the action, example:
in my mouseArea I change the state of mf
MouseArea{
anchors.fill: parent
onClicked: mf.state= "show"
}
If you want an Animation on the y try this:
MsgForm.ui.qml
import QtQuick 2.4
Item {
id: message
property alias text: msg.text
width: parent.width
height: msg.height+10
Rectangle {
id: rectangle
color: "#fb9191"
anchors.fill: parent
border.color: "#fd6666"
border.width: 2
Text {
id: msg
anchors.top: parent.top
anchors.topMargin: 2
textFormat: Text.PlainText
anchors.right: parent.right
anchors.rightMargin: 4
anchors.left: parent.left
anchors.leftMargin: 4
wrapMode: Text.WordWrap
clip: false
font.bold: true
font.pointSize: 12
font.family: "Tahoma"
}
}
Behavior on y {
NumberAnimation{
duration:300
}
}
states: [
State {
name: "show"
PropertyChanges {
target: message
y: parent.height - height
}
},
State {
name: "hide"
PropertyChanges {
target: message
y: parent.height + height + 5
}
}
]
}
Msg.qml
import QtQuick 2.4
Rectangle {
property alias text: mf.text
width:800
height: 480
antialiasing: false
opacity: 0.9
z: 100
MouseArea{
anchors.fill: parent
onClicked: mf.state= "show"
}
MsgForm {
id: mf
//y: parent.height - height - 5
y: parent.height +height + 5
width: parent.width
}
}