我正在将一个基于QtWidgets的应用程序移植到QtQuick2上。
我正在努力弄清楚我应该使用什么QtQuick布局项。
我被困在QFormLayout。我根本找不到类似的东西。我能找到的最好的是一个GridLayout,但是我希望自动生成标签(就像在QFormLayout)。
QHBoxLayout转换为RowLayout
QVBoxLayout转换为ColumnLayout
QGridLayout转换为GridLayout
QFormLayout转换为?
发布于 2017-07-11 14:44:59
如果您对GridLayout感到满意,只是缺少自动标签生成,那么您可以创建一些小助手类,在该类中封装Label并保存控件的属性。
// FormControl.qml
import QtQuick 2.0
import QtQuick.Controls 2.0
Item {
id: root
property alias label: myLabel
Label {
id: myLabel
parent: root.parent
Layout.fillHeight: true
Layout.fillWidth: true
verticalAlignment: Qt.AlignVCenter
MouseArea {
anchors.fill: parent
onClicked: root.control.forceActiveFocus()
}
}
property Item control
Row {
id: content
parent: myLabel.parent // parent it to myLabel.parent, to make sure, that one is added first.
children: [control]
}
}用法很简单:
import QtQuick 2.7
import QtQuick.Layouts 1.1
import QtQuick.Controls 2.0
ApplicationWindow {
id: myWindow
visible: true
width: 600
height: 600
color: 'white'
GridLayout {
columns: 2
FormControl {
label.text: 'test1'
control: ComboBox {
model: ['hello', 'world', 'and', 'bye']
}
}
FormControl {
label.text: 'Text'
control: TextField {
}
}
FormControl {
label.text: 'Something Long'
control: TextField {
}
}
}
}当您在control中声明default property Item control时,可以省略它。然后,您可能会添加多个控件,其中第一个将丢失。
我使用Row从隐式高度和宽度中受益,但也可以使用Item并将宽度和高度设置为childrenRect.width/height。不过,我不知道这是否有力。
发布于 2017-07-11 14:09:45
据我所知,在QML中没有对应的QFormLayout。
您必须自己使用Repeater和GridLayout定义组件。
您可以在这里找到一些详细信息:用Repeater填充GridLayout
FormLayout.qml的示例:
import QtQuick 2.0
import QtQuick.Window 2.0
import QtQuick.Layouts 1.2
import QtQuick.Controls 2.0
GridLayout {
id: grid
// Emitted when text has changed
signal inputTextChanged(int index, string text)
columns: 2
rowSpacing: 5
columnSpacing: 5
property var labels: []
Repeater {
model: grid.labels
Text {
Layout.row: index
Layout.column: 0
Layout.preferredWidth: 100
Layout.preferredHeight: 100
text: modelData
verticalAlignment: Text.AlignVCenter
}
}
Repeater {
model: grid.labels
TextField {
Layout.row: index
Layout.column: 1
Layout.preferredWidth: 100
Layout.preferredHeight: 40
onTextChanged: inputTextChanged(index,text)
}
}
}main.qml:
import QtQuick 2.5
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.2
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
FormLayout {
anchors {
fill: parent
margins: 5
}
labels: ["label1","label2"]
onInputTextChanged: console.log(index + "/" + text)
}
}labels可以是任何qml接受的模型 (JS数组、ListModel或来自c++的AbstractItemModel )。

https://stackoverflow.com/questions/45035800
复制相似问题