Dialog standardButtons position - qt

I want to make Dialog with only 1 button ("OK"). But when I use "standardButtons: Dialog.Ok" it positions it to the right. How it may be positioned in the middle? I would like to keep current button dimensions.
I've tried to use DialogButtonBox, and also Rectangle and Buttons in footer, but every time it not worked, or look like a mess
Code:
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
Window {
id: window
width: 640
height: 480
visible: true
title: qsTr("Hello World")
Button {
id: button
text: qsTr("Button")
anchors.verticalCenter: parent.verticalCenter
anchors.horizontalCenter: parent.horizontalCenter
onClicked: dialog.open()
}
Dialog {
id: dialog
modal: true
font.bold: true
title: "WARNING!!!"
Text {
id: dialogMessage
text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, \nsed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
horizontalAlignment: Text.AlignHCenter
}
parent: Overlay.overlay
x: parent.width/2 - width/2
y: parent.height/2 - height/2
standardButtons: Dialog.Ok
}
}

There are a few options:
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
Window {
id: window
width: 640
height: 480
visible: true
Dialog {
id: dialog
x: parent.width/2 - width/2
y: parent.height/2 - height/2
parent: Overlay.overlay
modal: true
font.bold: true
title: "WARNING!!!"
standardButtons: Dialog.Ok
visible: true
Text {
id: dialogMessage
text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, \nsed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
horizontalAlignment: Text.AlignHCenter
}
// Declare your own DialogButtonBox.
footer: DialogButtonBox {
alignment: Qt.AlignHCenter
}
// Assign it declaratively.
// Binding {
// target: dialog.footer
// property: "alignment"
// value: Qt.AlignHCenter
// }
// Assign it imperatively.
// Component.onCompleted: dialog.footer.alignment = Qt.AlignHCenter
}
}
I've left the other ones commented out to illustrate that you only need one of these approaches.
Note that you can't just do:
footer.alignment: Qt.AlignHCenter
because the type of the footer property is Item, not DialogButtonBox, and Item doesn't have an alignment property.

Consider using Column Layout, it will keep the dialog in shape. Also use both Layout.alignment and alignment property in the DialogButtonBox - the dialog will look just as You wish:
Dialog {
id: dialog
modal: true
font.bold: true
visible: true
title: "WARNING!!!"
ColumnLayout {
Text {
id: dialogMessage
Layout.alignment: Qt.AlignHCenter
text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, \nsed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
}
DialogButtonBox{
standardButtons: DialogButtonBox.Ok
Layout.alignment: Qt.AlignHCenter
alignment: Qt.AlignHCenter
onAccepted: dialog.close()
}
}
}

Related

How to have Text that wraps, has a maximum height, and becomes scrollable if the text goes over that maxiumum height?

I'm trying to set up a Text component that has a maximum height of the window's height divided by three. The source of the text gives it as a single line, so it also needs to wrap once its width exceeds that of the window. Finally, I'd like the text to become scrollable if its height exceeds 1/3 of the window's.
I've also got a ListView below it, and I want the top of the ListView to be right at the bottom of the Text.
So far, I've come up with this:
ColumnLayout {
anchors.fill: parent
// anchors.margins: 10
ScrollView {
id: descriptionBox
clip: true
Layout.fillWidth: true
Layout.preferredHeight: parent.height / 3
contentWidth: parent.width
Text {
id: descriptionBoxLabel
text: "Eum id neque possimus inventore similique. Et dolores exercitationem vel dignissimos. Voluptatibus assumenda veniam consequuntur. Harum reprehenderit tempora nostrum. Assumenda unde omnis non sit minima voluptas eligendi eum."
anchors.left: parent.left
anchors.right: parent.right
wrapMode: Text.WordWrap
}
}
ListView {
id: useListView
model: ["Apple", "Banana", "Pear", "Watermelon"]
delegate: CheckDelegate {
text: modelData
width: Window.width - 20
}
Layout.fillWidth: true
Layout.fillHeight: true
}
}
This kind of works, but the Text doesn't become scrollable when I shrink the height of the window, and the top of the ListView isn't lined up with the bottom of the Text.
I am not sure what the original issue is, but, I reworked it to use a Flickable instead of a ScrollView. The difference being you have to be meticulous in setting contentWidth and contentHeight correctly for the ScrollBar to work. I also tweaked the width calculation of your ListView delegate to follow the width of the ListView:
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
Page {
ColumnLayout {
anchors.fill: parent
Flickable {
id: descriptionBox
Layout.fillWidth: true
Layout.preferredHeight: Math.min(parent.height / 3, frame.height)
clip: true
contentWidth: frame.width
contentHeight: frame.height
ScrollBar.vertical: ScrollBar {
width: 20
policy: ScrollBar.AlwaysOn
}
Frame {
id: frame
width: descriptionBox.width - 20
Text {
id: descriptionBoxLabel
text: "Eum id neque possimus inventore similique. Et dolores exercitationem vel dignissimos. Voluptatibus assumenda veniam consequuntur. Harum reprehenderit tempora nostrum. Assumenda unde omnis non sit minima voluptas eligendi eum."
width: parent.width
wrapMode: Text.WordWrap
}
}
}
ListView {
id: useListView
Layout.fillWidth: true
Layout.fillHeight: true
model: ["Apple", "Banana", "Pear", "Watermelon"]
delegate: CheckDelegate {
text: modelData
width: ListView.view.width - 20
}
ScrollBar.vertical: ScrollBar {
width: 20
policy: ScrollBar.AlwaysOn
}
}
}
}
You can Try it Online!
[EDIT]
To eliminate the white space, modified the Layout height with:
Layout.preferredHeight: Math.min(parent.height / 3, frame.height)

ScrollView not working. Need help or suggestions

I am having trouble getting the scrollview to work properly. I'm most likely missing something or I'm doing something totally wrong. This isn't my first time dealing with this issue either. The page contains a scrollview which has a stacklayout inside of it. My goal is to scroll through the stacklayout content using the scrollview. I tried setting the contentWidth and the contentHeight of the scrollview but that did not fix the issue.
import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.12
import QtGraphicalEffects 1.12 // ColorOverlay
import "../../components" as NeroshopComponents
Page {
id: sellerHub
background: Rectangle {
color: "transparent"
}
NeroshopComponents.TabBar {
id: tabBar
anchors.top: parent.top
anchors.topMargin: tabBar.buttonHeight
anchors.horizontalCenter: parent.horizontalCenter
model: ["Overview", "Inventory", "Customers"]
Component.onCompleted: {
buttonAt(1).checked = true
}
}
ScrollView {
id: scrollView
width: parent.width; height: 2000//anchors.fill: parent
anchors.top: tabBar.bottom; anchors.topMargin: tabBar.buttonHeight + 10
//anchors.margins: 20
//contentHeight: height; contentWidth: width
ScrollBar.vertical.policy: ScrollBar.AlwaysOn////AsNeeded
clip: true
StackLayout {
id: dashboard
anchors.fill: parent
currentIndex: tabBar.checkedButtonIndex
Item {
id: overviewTab
// StackLayout child Items' Layout.fillWidth and Layout.fillHeight properties default to true
RowLayout {
id: stats
anchors.horizontalCenter: parent.horizontalCenter//Layout.alignment: Qt.AlignHCenter | Qt.AlignTop// <- this is not working :/
property real numberTextFontSize: 24
property string textColor: "#384364"////(NeroshopComponents.Style.darkTheme) ? "#ffffff" : "#384364"
property real boxWidth: 250//(scrollView.width / 3) - 20//scrollView.width / statsRepeater.count
property real boxHeight: 110
property real boxRadius: 6
spacing: 15
property bool useDefaultBoxColor: true//false
property string boxColor: "#ffffff"////(NeroshopComponents.Style.darkTheme) ? "#384364" : "#ffffff"
// Products (listed)
Rectangle {
Layout.preferredWidth: stats.boxWidth
Layout.preferredHeight: stats.boxHeight
color: stats.useDefaultBoxColor ? stats.boxColor : "#e9eefc"
radius: stats.boxRadius
Item {
anchors.fill: parent
anchors.centerIn: parent
Rectangle {
anchors.verticalCenter: parent.verticalCenter
anchors.left: parent.left; anchors.leftMargin: width / 2
width: 64; height: 64
color: "#e9eefc"
radius: 50
Image {
id: productIcon
source: "qrc:/images/open_parcel.png"
width: 32; height: 32
anchors.centerIn: parent
}
ColorOverlay {
anchors.fill: productIcon
source: productIcon
color: "#4169e1"
visible: productIcon.visible
}
}
Item {
anchors.right: parent.children[0].right; anchors.rightMargin: -(contentWidth + 20)
anchors.top: parent.children[0].top
Text {
text: "0"//"5430"
font.bold: true
font.pointSize: stats.numberTextFontSize
color: stats.textColor
}
Text {
text: "Products"
//font.bold: true
color: stats.textColor
anchors.left: parent.children[0].left
anchors.top: parent.children[0].bottom; anchors.topMargin: 10
}
}
}
}
// Sales (the total number of completed orders)
Rectangle {
Layout.preferredWidth: stats.boxWidth
Layout.preferredHeight: stats.boxHeight
color: stats.useDefaultBoxColor ? stats.boxColor : "#eff5ef"
radius: stats.boxRadius
Item {
anchors.fill: parent
anchors.centerIn: parent
Rectangle {
anchors.verticalCenter: parent.verticalCenter
anchors.left: parent.left; anchors.leftMargin: width / 2
width: 64; height: 64
color: "#eff5ef"
radius: 50
Image {
id: salesIcon
source: "qrc:/images/increase.png"
width: 32; height: 32
anchors.centerIn: parent
}
ColorOverlay {
anchors.fill: salesIcon
source: salesIcon
color: "#8fbc8f"
visible: salesIcon.visible
}
}
Item {
anchors.right: parent.children[0].right; anchors.rightMargin: -(contentWidth + 20)
anchors.top: parent.children[0].top
Text {
text: "0"//"17440"
font.bold: true
font.pointSize: stats.numberTextFontSize
color: stats.textColor
}
Text {
text: "Sales"
//font.bold: true
color: stats.textColor
anchors.left: parent.children[0].left
anchors.top: parent.children[0].bottom; anchors.topMargin: 10
}
}
}
}
// Ratings/Feedback/Reputation
Rectangle {
Layout.preferredWidth: stats.boxWidth
Layout.preferredHeight: stats.boxHeight
color: stats.useDefaultBoxColor ? stats.boxColor : "#fffbe5"
radius: stats.boxRadius
Item {
anchors.fill: parent
anchors.centerIn: parent
Rectangle {
anchors.verticalCenter: parent.verticalCenter
anchors.left: parent.left; anchors.leftMargin: width / 2
width: 64; height: 64
color: "#fffbe5"
radius: 50
Image {
id: ratingIcon
source: "qrc:/images/rating.png"
width: 32; height: 32
anchors.centerIn: parent
}
ColorOverlay {
anchors.fill: ratingIcon
source: ratingIcon
color: "#ffd700"//"#e6c200"
visible: ratingIcon.visible
}
}
Item {
anchors.right: parent.children[0].right; anchors.rightMargin: -(contentWidth + 20)
anchors.top: parent.children[0].top
Text {
text: qsTr("%1%2").arg("0").arg("%")
font.bold: true
font.pointSize: stats.numberTextFontSize
color: stats.textColor
}
Text {
text: "Reputation"
//font.bold: true
color: stats.textColor
anchors.left: parent.children[0].left
anchors.top: parent.children[0].bottom; anchors.topMargin: 10
}
}
}
}
}
// TODO: show recent orders from customers, show seller's top-selling products, show customer reviews on seller products
//ColumnLayout {}
} // overview tab
Item {
id: inventoryTab
// StackLayout child Items' Layout.fillWidth and Layout.fillHeight properties default to true
Component.onCompleted: { console.log("InventoryTab width",this.width) }
ColumnLayout {//GridLayout {//
id: productDetails
width: parent.width; height: childrenRect.height////anchors.fill: parent
Component.onCompleted: { console.log("ProductDetails width",this.width) }
spacing: 30////rowSpacing: 5
property string titleTextColor: (NeroshopComponents.Style.darkTheme) ? "#ffffff" : "#000000"
property real radius: 3
property real marginFromTitle: 7
property string textColor: (NeroshopComponents.Style.darkTheme) ? "#ffffff" : "#000000"
property string baseColor: (NeroshopComponents.Style.darkTheme) ? "#101010" : "#ffffff"
property string borderColor: (NeroshopComponents.Style.darkTheme) ? "#a9a9a9" : "#000000"
// RegisterItem to "products" table
//Product title (TODO: place both text and textfield in an item)
// If item fields are related then place them side-by-side in separate columns
Item {
//Layout.row: 0
Layout.alignment: Qt.AlignHCenter// | Qt.AlignTop
//Layout.topMargin: 0
Layout.preferredWidth: childrenRect.width////productNameField.width
Layout.preferredHeight: childrenRect.height // 72 (child margins included)
Text {
text: "Product name" // height=17
color: productDetails.titleTextColor
font.bold: true
}
TextField {
id: productNameField
width: 500; height: 50
anchors.top: parent.children[0].bottom
anchors.topMargin: productDetails.marginFromTitle
placeholderText: qsTr("Product title")
color: productDetails.textColor
selectByMouse: true
background: Rectangle {
color: productDetails.baseColor
border.color: productDetails.borderColor
radius: productDetails.radius
}
}
}
// Product price (sales price)
Item {
//Layout.row: 1
Layout.alignment: Qt.AlignHCenter
Layout.preferredWidth: childrenRect.width
Layout.preferredHeight: childrenRect.height
Text {
text: "Price"
color: productDetails.titleTextColor
font.bold: true
}
TextField {
id: productPriceField
width: 500; height: 50
anchors.top: parent.children[0].bottom
anchors.topMargin: productDetails.marginFromTitle
placeholderText: qsTr("Enter price")
color: productDetails.textColor
selectByMouse: true
background: Rectangle {
color: productDetails.baseColor
border.color: productDetails.borderColor
radius: productDetails.radius
}
}
}
// Product quantity
Item {
//Layout.row:
Layout.alignment: Qt.AlignHCenter
Layout.preferredWidth: childrenRect.width
Layout.preferredHeight: childrenRect.height
Text {
text: "Quantity"
color: productDetails.titleTextColor
font.bold: true
//visible: false
}
TextField {
id: productQuantityField
width: 500; height: 50
anchors.top: parent.children[0].bottom
anchors.topMargin: productDetails.marginFromTitle
placeholderText: qsTr("Enter quantity")
color: productDetails.textColor
selectByMouse: true
background: Rectangle {
color: productDetails.baseColor
border.color: productDetails.borderColor
radius: productDetails.radius
}
}
}
// Product condition
Item {
//Layout.row:
Layout.alignment: Qt.AlignHCenter
Layout.preferredWidth: childrenRect.width
Layout.preferredHeight: childrenRect.height
Text {
text: "Condition"
color: productDetails.titleTextColor
font.bold: true
//visible: false
}
ComboBox {
anchors.top: parent.children[0].bottom
anchors.topMargin: productDetails.marginFromTitle
width: 500
model: ["new", "used", "renewed (refurbished)"]
}
}
// Product code UPC, EAN, JAN, SKU, ISBN (for books) // https://www.simplybarcodes.com/barcode_types.html
Item {
//Layout.row:
Layout.alignment: Qt.AlignHCenter
Layout.preferredWidth: childrenRect.width
Layout.preferredHeight: childrenRect.height
Text {
text: "Product code"
color: productDetails.titleTextColor
font.bold: true
//visible: false
}
TextField {
id: productCodeField
width: 500; height: 50
anchors.top: parent.children[0].bottom
anchors.topMargin: productDetails.marginFromTitle
placeholderText: qsTr("Enter product code (optional)")
color: productDetails.textColor
selectByMouse: true
background: Rectangle {
color: productDetails.baseColor
border.color: productDetails.borderColor
radius: productDetails.radius
}
}
}
// Product categories
// Subcategories (will be determined based on selected categories)
// Weight
Item {
//Layout.row:
Layout.alignment: Qt.AlignHCenter
Layout.preferredWidth: childrenRect.width
Layout.preferredHeight: childrenRect.height
Text {
text: ""
color: productDetails.titleTextColor
font.bold: true
//visible: false
}
TextField {
id: productWeightField
width: 500; height: 50
anchors.top: parent.children[0].bottom
anchors.topMargin: productDetails.marginFromTitle
placeholderText: qsTr("Enter weight (e.g. 12 lbs.)")
color: productDetails.textColor
selectByMouse: true
background: Rectangle {
color: productDetails.baseColor
border.color: productDetails.borderColor
radius: productDetails.radius
}
}
//ComboBox {
// id: weightMeasurementUnit (default is kg)
//}
}
// Size
Item {
//Layout.row:
Layout.alignment: Qt.AlignHCenter
Layout.preferredWidth: childrenRect.width
Layout.preferredHeight: childrenRect.height
Text {
text: ""
color: productDetails.titleTextColor
font.bold: true
//visible: false
}
TextField {
id: productSizeField
width: 500; height: 50
anchors.top: parent.children[0].bottom
anchors.topMargin: productDetails.marginFromTitle
placeholderText: qsTr("Enter size")
color: productDetails.textColor
selectByMouse: true
background: Rectangle {
color: productDetails.baseColor
border.color: productDetails.borderColor
radius: productDetails.radius
}
}
//ComboBox
}
// Variations (i.e. Color, Size options to choose from - optional)
// Product location (ship to and ship from)
//Product description and bullet points
Item {
//Layout.row:
Layout.alignment: Qt.AlignHCenter
Layout.preferredWidth: childrenRect.width
Layout.preferredHeight: childrenRect.height
Text {
text: "Description"
color: productDetails.titleTextColor
font.bold: true
//visible: false
}
TextArea {
id: productDescArea
anchors.top: parent.children[0].bottom
anchors.topMargin: productDetails.marginFromTitle
width: 500; height: 250
}
}
//Product images
//Search terms and relevant keywords (tags)
// tags must be separated with a colon
Item {
//Layout.row:
Layout.alignment: Qt.AlignHCenter
Layout.preferredWidth: childrenRect.width
Layout.preferredHeight: childrenRect.height
Text {
text: ""
color: productDetails.titleTextColor
font.bold: true
//visible: false
}
TextField {
id: productKeywordsField
width: 500; height: 50
anchors.top: parent.children[0].bottom
anchors.topMargin: productDetails.marginFromTitle
placeholderText: qsTr("Enter keywords or search term")
color: productDetails.textColor
selectByMouse: true
background: Rectangle {
color: productDetails.baseColor
border.color: productDetails.borderColor
radius: productDetails.radius
}
}
}
// ListItem to "listings" table
//Button {
// id: listProductButton
//}
}
//ColumnLayout {
// id: inventoryManager // inventory can be managed here and sorted too
//}
}
Item {
id: customerOrdersTab
}
}
}
}
I suspect the reason why the ScrollView is not working for you is because your child StackLayout has anchors.fill: parent. This means the size of your child is already constrained, so it will never have a meaningful ScrollBar. Please review your anchoring / sizing.
Here's an example usage of ScrollView. Note that the ScrollView contains exactly one child. Note that I have not set the height of the child and allowed it to grow. Note that I modified the default policy making the ScrollBar always visible. Also note that I resize the ScrollBar to 20 pixels and that I shrunk the content within by 20 pixels:
import QtQuick
import QtQuick.Controls
Page {
ScrollView {
id: scrollView
anchors.fill: parent
ScrollBar.vertical.policy: ScrollBar.AlwaysOn
ScrollBar.vertical.width: 20
TextEdit {
id: textEdit
width: scrollView.width - 20
text: `
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus vel sagittis tellus. Aliquam rhoncus laoreet mi at varius. Phasellus et nisl quam. Duis luctus porta quam, a vehicula erat aliquet sed. Quisque viverra erat risus, vitae congue libero vestibulum vel. Mauris vel interdum purus. Aliquam mauris justo, pellentesque vel sagittis ac, placerat nec enim. Nulla gravida non libero non mollis. Donec sodales ornare tincidunt. Vivamus mattis augue quis justo convallis, molestie tempus velit sollicitudin. Suspendisse potenti. Fusce ut nibh et odio mattis semper at sit amet elit. Nullam pharetra augue nisi, at vestibulum magna dignissim sit amet. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nunc mattis congue magna at laoreet. Vestibulum tincidunt ante ligula, sit amet lacinia orci suscipit ac.
`.repeat(5)
wrapMode: Text.WordWrap
}
}
}
You can Try it Online!
Here's an example usage of Flickable. Note that the Flickable must set:
contentWidth and contentHeight correctly else you will not get a flickable action
note the optional setting of a ScrollBar of 20 pixels and that I shrink the content by the same amount
also note the optional setting of clip: true
again I've only constrained the width of the child but not the height, allowing it to grow
import QtQuick
import QtQuick.Controls
Page {
Flickable {
id: flickable
anchors.fill: parent
contentWidth: textEdit.width
contentHeight: textEdit.height
clip: true
ScrollBar.vertical: ScrollBar {
width: 20
policy: ScrollBar.AlwaysOn
}
TextEdit {
id: textEdit
width: flickable.width - 20
text: `
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus vel sagittis tellus. Aliquam rhoncus laoreet mi at varius. Phasellus et nisl quam. Duis luctus porta quam, a vehicula erat aliquet sed. Quisque viverra erat risus, vitae congue libero vestibulum vel. Mauris vel interdum purus. Aliquam mauris justo, pellentesque vel sagittis ac, placerat nec enim. Nulla gravida non libero non mollis. Donec sodales ornare tincidunt. Vivamus mattis augue quis justo convallis, molestie tempus velit sollicitudin. Suspendisse potenti. Fusce ut nibh et odio mattis semper at sit amet elit. Nullam pharetra augue nisi, at vestibulum magna dignissim sit amet. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nunc mattis congue magna at laoreet. Vestibulum tincidunt ante ligula, sit amet lacinia orci suscipit ac.
`.repeat(5)
wrapMode: Text.WordWrap
}
}
}
You can Try it Online!
You figured it out yourself already. I just add here what I've come up with. Because I didn't fully understand what you were trying to do I made different version of ScrollViews. As Stephen already said you anchor filled the StackLayout in the ScrollView which essentially makes it non scroll able as the StackLayout gets the same size as the ScrollView.
I came up with 4 solutions.
Scroll through a StackLayout via a ScrollBar.
Use a ScrollView with content.
Use a ScrollView around a StackLayout. In order to keep the height of the StackLayout correct it needs to be bound to the current item shown in the StackView. Otherwise it is as big as the biggest item in the layout.
The proper way which you came up with already to have ScrollView
per item in the StackLayout.
These are all the solutions in one application.
import QtQuick
import QtQuick.Controls.Basic
import QtQuick.Layouts
Window {
width: 800
height: 600
visible: true
title: qsTr("Hello StackLayout")
component Content : Rectangle {
color: "gray"
border { width: 1; color: "black" }
Text { text: index; font.pixelSize: 80; anchors.centerIn: parent}
}
// --- Solution 1 ---
Item {
id: frame
width: 400; height: 300
StackLayout {
id: stackLayout
anchors.fill: parent
Repeater {
id: repeater1
model: 5
delegate: Content {}
}
}
ScrollBar {
id: hbar
policy: ScrollBar.AlwaysOn
orientation: Qt.Vertical
size: 1.0 / repeater1.count
anchors.top: parent.top
anchors.right: parent.right
anchors.bottom: parent.bottom
onPositionChanged: {
let i = Math.floor((hbar.position / hbar.size) + 0.5)
if (i !== stackLayout.currentIndex)
stackLayout.currentIndex = i
}
}
}
// --- Solution 2 ---
ScrollView {
id: scrollView
anchors.left: frame.right
width: 400; height: 300
ColumnLayout {
spacing: 0
Repeater {
model: 5
delegate: Content { width: 400; height: 300 }
}
}
}
// --- Solution 3 ---
Item {
id: frame3
anchors.top: frame.bottom
width: 400; height: 300
TabBar {
id: bar
anchors.left: parent.left
anchors.right: parent.right
anchors.top: parent.top
Repeater {
model: 5
TabButton { text: index }
}
}
ScrollView {
anchors.left: parent.left
anchors.right: parent.right
anchors.top: bar.bottom
anchors.bottom: parent.bottom
StackLayout {
currentIndex: bar.currentIndex
implicitHeight: repeater3.itemAt(bar.currentIndex).implicitHeight
Repeater {
id: repeater3
model: 5
delegate: Content { width: 400; implicitHeight: 200 * (index + 1) }
}
}
}
}
// --- Solution 4 ---
Item {
anchors.top: scrollView.bottom
anchors.left: frame3.right
width: 400; height: 300
TabBar {
id: bar2
anchors.left: parent.left
anchors.right: parent.right
anchors.top: parent.top
Repeater {
model: 5
TabButton { text: index }
}
}
StackLayout {
anchors.left: parent.left
anchors.right: parent.right
anchors.top: bar2.bottom
anchors.bottom: parent.bottom
currentIndex: bar2.currentIndex
Repeater {
model: 5
delegate: ScrollView {
Content { width: 400; implicitHeight: 200 * (index + 1) }
}
}
}
}
}

How to make qml TableView row height dynamically adapt to content

The problem is the following:
If the length of the text is longer than the width of the cell, the text is wrapped, but the height of the row is not increased. which displays the rest of the text chopped. My other question is, how to adapt the height of each cell to the text contained in it?
Here's the QML part:
Window {
id: window
visible: true
width: 440
height: 400
title: qsTr("Table test")
ListModel {
id: stringsModel
ListElement {
ID: 0
String: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam'
}
ListElement {
ID: 1
String: 'This is a test string'
}ListElement {
ID: 1
String: 'This is another test string'
}
}
TableView {
anchors.fill: parent
frameVisible: false
model: stringsModel
TableViewColumn { role: "ID"; title: "ID"; width: window.width / 2 }
TableViewColumn { role: "String"; title: "String"; width: window.width / 2; delegate: stringDelegate;}
Component {
id: stringDelegate
Item {
id: stringItem
Text {
id: stringTxt
width: parent.width
text: styleData.value
wrapMode: TextEdit.WordWrap
}
}
}
}
}
Your delegate's root item should define its implicitHeight property.
Something like this:
Component {
id: stringDelegate
Item {
id: stringItem
implicitHeight: stringTxt.paintedHeight
Text {
id: stringTxt
width: parent.width
text: styleData.value
wrapMode: TextEdit.WordWrap
}
}
}

setting wrapMode property of Text in ScrollView

I wrote QML like this:
import QtQuick 2.2
import QtQuick.Controls 1.1
import QtQuick.Layouts 1.1
import App 0.1
ApplicationWindow {
id: appWindow
visible: true
width: 300
height: 500
ColumnLayout {
ScrollView {
ColumnLayout {
Text {
width: 250
text: "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
wrapMode: Text.WrapAnywhere
}
}
}
}
AppController {
id: controller
}
}
and this is the visual outcome:
I want to wrap Text inside ScrollView. I've tried many patterns but I failed to achieve the desired result. How can I do that?
Just remove ColumnLayout, that's not necessary here. This works for me (if that's what you're looking for):
import QtQuick 2.2
import QtQuick.Controls 1.3
ApplicationWindow {
id: appWindow
visible: true
width: 300
height: 500
ScrollView {
anchors.fill: parent
Column {
Repeater {
model: 10
delegate: Text {
width: appWindow.width - 50
text: "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
wrapMode: Text.WrapAnywhere
}
}
}
}
}
Try to avoid fixed sizes where possible. In your case the Text doesn't react to window resizing. Also when providing code snippets, just remove specific fragments like your AppController for example (even if it's no big deal in this case but it's easier for anyone to run and test your code) :)
Hope this helps!

Qml text wrap (max width)

I would like to put text inside a bubble, and I want that my bubble be equal to the text width, but if the text length is too long, I would like the text to wrap automatically and be equal to the parent width.
This code works but the text is not wrapping if text is too long:
Rectangle {
id:messageBoxCadre
width: (modelData.messageLength>25)? (wrapper.width - 20): messageBox.width+10
height: messageBox.height+5
color: modelData.myMessage ? "#aa84b2":"#380c47"
radius: 10
Text {
id:messageBox
text: '<b><font color=purple>'+modelData.message+'</font></b> '
wrapMode: "WordWrap"
}
}
and I tried this, text wrap, but if the text is too small the bubble width is not equal to the text size:
Rectangle {
id:messageBoxCadre
width: (modelData.messageLength>25)? (wrapper.width - 20): messageBox.width+10
height: messageBox.height+5
color: modelData.myMessage ? "#aa84b2":"#380c47"
radius: 10
Text {
id:messageBox
width: (modelData.messageLength>25)? (wrapper.width - 20): messageBox.width
text: '<b><font color=purple>'+modelData.message+'</font></b> '
wrapMode: "WordWrap"
}
}
You can almost do this neatly with states. The problem is that attempting to set the width of the parent by assigning it to the paintedWidth of the text box means it then sets the width of the text box, which QML detects as influencing paintedWidth. It wouldn't recurse further than this, but QML still kicks out warnings. One way around the problem is to do as follows, and have a dummy invisible text box that just works out how wide the text is/should be. Its a bit of a hack, but it works nicely.
You could change the "when" property of the state to be dependent on the size of the dummy text box (rather than the length of the string) if you preferred a pixel limit on the width of the box.
import QtQuick 1.0
Rectangle {
id: containing_rect
property string text
text: "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat"
//text: "a short string"
Text {
id: text_field
anchors.top: parent.top
anchors.left: parent.left
height: parent.height
width: parent.width
text: parent.text
wrapMode: Text.WordWrap
}
Text {
id: dummy_text
text: parent.text
visible: false
}
states: [
State {
name: "wide text"
when: containing_rect.text.length > 20
PropertyChanges {
target: containing_rect
width: 200
height: text_field.paintedHeight
}
},
State {
name: "not wide text"
when: containing_rect.text.length <= 20
PropertyChanges {
target: containing_rect
width: dummy_text.paintedWidth
height: text_field.paintedHeight
}
}
]
}
Here's another way, which uses the Component.onCompleted script. It's more static than my other method, so I guess it depends on what you want to do with it.
import QtQuick 1.0
Rectangle {
id: containing_rect
property string text
height: text_field.paintedHeight
text: "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat"
//text: "a short string"
Text {
id: text_field
anchors.top: parent.top
anchors.left: parent.left
height: parent.height
width: parent.width
text: parent.text
wrapMode: Text.WordWrap
}
Component.onCompleted: {
if (text_field.paintedWidth > 200) {
width = 200
} else {
width = text_field.paintedWidth
}
}
}
Very late to the party but the clean solution is to use an embedded TextMetrics object. Like this:
...
Text {
id: textObj
width: Math.min(textWidth, myThreshold)
// access to binding-loop-free width and height:
readonly property alias textWidth: textMetrics.boundingRect.width
readonly property alias textHeight: textMetrics.boundingRect.height
TextMetrics {
id: textMetrics
font: textObj.font
text: textObj.text
elide: textObj.elide
}
}
You can also try something like this, using the dummy text box mentioned above:
width: Math.min(dummy_text.paintedWidth, 250)
This will use the painted size of the text unless it is greater than your specified pixel width.
Try this:
Text {
property int MAX_WIDTH: 400
width: MAX_WIDTH
onTextChanged: width = Math.min(MAX_WIDTH, paintedWidth)
}
i did not use state, but i use the idea of dummy text to have width. thanks
my code :
Rectangle{
id:messageBoxCadre
width: (modelData.messageLength>25)? (wrapper.width - 20): messageBox.width+10
height: messageBox.height+5
color: modelData.myMessage ? "#aa84b2":"#380c47"
radius: 10
Text {
id:messageBox
width: (modelData.messageLength>25)? (wrapper.width - 20): dummy_text.dummy_text
text: '<b><font color=purple>'+modelData.message+'</font></b> '
wrapMode: "WordWrap"
}
Text {
id: dummy_text
text: '<b><font color=purple>'+modelData.message+'</font></b> '
visible: false
}
}
Obviously a couple years late, but I just ran into a similar issue (though I am using elide instead of wrap but the basics are the same). I ended up with what seems like a simple and clean solution so I figured if anyone else runs into this problem it can maybe help. Using the original code as an example:
property int maxWidth: 100 // however you want to define the max width
Rectangle{
id:messageBoxCadre
width: messageBox.paintedWidth+10 // width of the actual text, so your bubble will change to match the text width
height: messageBox.height+5
color: modelData.myMessage ? "#aa84b2":"#380c47"
radius: 10
Text {
id:messageBox
text: '<b><font color=purple>'+modelData.message+'</font></b> '
width: maxWidth // max width that your text can reach before wrapping
wrapMode: "WordWrap"
}
}
The only problem for this example is that with WordWrap, if a word is too long to fit the entire width of the Text item it will exceed whatever maxWidth you have set.

Resources