如何解决如何在 QML 的 ColumnLayout 中使用自己的对象?
我想生成一个表格,其中每一行都是一个 Text() 和一个 ComboBox()。我希望组合框向右对齐,并且文本标签的左侧也是这样的:
我有主要的qml:
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.12
Window {
id: wind
width: 640
height: 480
visible: true
title: qsTr("Public Transport Searcher")
property string oz: "Odjezdová zastávka"
property string pz: "Příjezdová zastávka"
property string co: "Čas odjezdu"
Rectangle{
id: rect
x: wind.width/16
implicitHeight: parent.height/3*2
implicitWidth: wind.width/8*7
anchors.right: parent.right
anchors.left: parent.left
anchors.margins: 20
radius: 5
color: "lightblue"
ColumnLayout{
id: cl
spacing: 30
width: parent.width
anchors.top: parent.top
anchors.left: parent.left
anchors.margins: 20
anchors.fill: parent
Row{
id: r1
Layout.alignment: Qt.AlignTop
//Layout.alignment: Qt.AlignTop
Layout.margins: 15
Text{
id: r1t1
text: "Vyhledávač jízdních řádů"
font.pointSize: 16
font.bold: true
}
}
Line{
id: r2
tt2: oz
Layout.alignment: Qt.AlignLeft
//anchors.top: r1.bottom
}
Line{
id: r3
tt2: pz
Layout.alignment: Qt.AlignLeft
}
Line{
id: r4
tt2: co
Layout.alignment: Qt.AlignLeft
}
}
}
}
还有一个单独的 Line.qml 项:
import QtQuick 2.15
import QtQuick.Controls 2.12
Item {
property string tt2: "v"
Text{
id: txt
text: tt2
anchors.verticalCenter: parent.verticalCenter
anchors.left: parent.left
}
ComboBox{
id: cb
anchors.verticalCenter: parent.verticalCenter
//anchors.fill: parent
anchors.left: txt.right
}
}
现在它运行了,但左上角的所有行都被覆盖了。 我知道我可以使用 GridLayout 但我想利用自己的对象为一行(如果我有很多这样的行)避免复制粘贴技术并单独初始化行的每个对象。 你能告诉我如何以优雅的方式做到这一点吗?
解决方法
问题是您的 Line
项目没有任何 ColumnLayout
可以读取的隐式大小。也就是说,Line
的基础只是一个 Item
,它的默认 implicitHeight
和 implicitWidth
都是 0 - 所以 ColumnLayout
不正确地呈现它们。您有多种选择。
一种选择是将 implicitHeight
/implicitWidth
(或 Layout.preferredWidth
/Layout.preferredHeight
)添加到您的 Line
的 Item
:>
import QtQuick 2.12
import QtQuick.Controls 2.12
Item {
implicitHeight: 30
implicitWidth: parent.width
property string tt2: "v"
Text{
id: txt
text: tt2
anchors.verticalCenter: parent.verticalCenter
anchors.left: parent.left
}
ComboBox{
id: cb
anchors.verticalCenter: parent.verticalCenter
//anchors.fill: parent
anchors.left: txt.right
}
}
实现此目的的另一种方法是将 Line
的基础更改为 RowLayout
(并删除会冲突的内部锚点):
import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.12
RowLayout {
property string tt2: "v"
Text {
id: txt
text: tt2
Layout.preferredWidth: 200 // to align ComboBoxes,all text must have same width
// Layout.fillWidth: true // a different option for aligning ComboBoxes
}
ComboBox {
id: cb
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。