我想通过以下方式对窗口的宽度做出响应:
当窗口的宽度小于某个特定的maximumWidth
,例如1000px
时,表单应占据整个可用宽度。
当窗口的宽度大于maximumWidth
时,表单应水平居中放置,且宽度固定为900px
。
这是我的代码:
main.qml
import QtQuick 2.9
import QtQuick.Controls 2.2
import QtQuick.Layouts 1.3
ApplicationWindow {
id: window
visible: true
width: 800 // 1100
title: "Stack"
ScrollView {
anchors.fill: parent
GridLayout {
columns: 2
CVerticalLabel {
text: "Miscellaneous"
background: "blue"
Layout.fillHeight: true
}
GridLayout {
columns: 2
Text {
text: "Company Name"
color: "red"
font.bold: true
font.pointSize: 16
}
TextField {
objectName: "company_name"
font.bold: true
Layout.fillWidth: true
implicitHeight: 30
implicitWidth: 1000
}
}
}
}
}
CVerticalLabel.qml
import QtQuick 2.9
Item {
id: control
property string text
property color color: "red"
property color background: "blue"
property real bgOpacity: 0.6
width: 15 * 1.6
Rectangle {
anchors.fill: control
color: control.background
opacity: control.bgOpacity
}
Text {
color: control.color
text: control.text
font.bold: true
font.pointSize: 10
width: control.height
height: control.width
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
rotation: 90
y: -height
transformOrigin: Item.BottomLeft
}
}
代码产生以下结果:
问题是,表单向左对齐并且其大小始终是固定的,即,它没有考虑不同的窗口宽度。因此,第二列不会拉伸以填充剩余的可用宽度。
如何获得理想的结果?
答案 0 :(得分:1)
当窗口宽度超过GridLayout
时,为了使900px
以最大宽度为1000px
的页面居中,我建议您采用以下解决方案:
添加Page
作为ScrollView
的父项:
Page {
id: page
anchors.fill: parent
ScrollView {
...
}
}
通过考虑其子元素的边界矩形的宽度以及GridLayout
的宽度,使Page
动态的左锚边距:
anchors.leftMargin: (page.width - childrenRect.width)/2
这是我为您创建的一个示例,说明如何更改您的代码以实施建议的解决方案:
ApplicationWindow {
id: window
title: "Stack"
visible: true
width: 1400
Page {
id: page
anchors.fill: parent
property int responsiveWidth: 1000
property int maximumWidth: 900
ScrollView {
anchors.fill: parent
GridLayout {
columns: 2
width: page.width > page.responsiveWidth ? page.maximumWidth : page.width
anchors.top: parent.top
anchors.left: parent.left
anchors.leftMargin: (page.width - childrenRect.width)/2
CVerticalLabel {
text: "Miscellaneous"
background: "blue"
Layout.fillHeight: true
}
GridLayout {
columns: 2
CTextLabel {
text: "Company Name"
color: "red"
}
PanelTextField {
objectName: "company_name"
font.bold: true
Layout.fillWidth: true
}
}
}
}
}
}
提供的示例将产生以下结果:
@800px
@1100px