本文介紹QT QML跨平臺移動APP開發中的元素佈局的相關問題,先看一張圖,我們來分析一下其中的問題:
這張圖片中,有如下問題:
- 整體的佈局沒有居中顯示
- 班級名稱:
沒有和 請輸入班級名稱輸入框垂直對齊
和輸入框的距離太遠 - 班主任的提示也一樣
- 最後的Button一行,需求要求右對齊,在QML的程序中沒有實現
代碼修改完以後的效果:
改變寬度試一下:
原代碼說明:
main.qml
import QtQuick 2.12
import QtQuick.Window 2.12
Window {
visible: true
width: 640
height: 480
title: qsTr("QML 元素佈局")
InputPage{
// 充滿父類
anchors.fill: parent
// 設置margins
anchors.margins: 10
}
}
InputPage.qml
import QtQuick 2.0
import QtQuick.Controls 2.12
Page {
// 定義參數,每行的高度
property int rowHeight: 40
// 定義參數,每行中,每列的間距
property int rowSpacing: 8
// 定義一列
Column{
id: column
// 充滿父類Page類
anchors.fill: parent
// 定義Column中,每行Row的間距
spacing: 10
Row{
// 寬度去Page的0.8
width: parent.width * 0.8
height: rowHeight
spacing: rowSpacing
// Row水平居中顯示
anchors.horizontalCenter: parent.horizontalCenter
Label{
text: "班級名稱"
// 定義垂直居中顯示
verticalAlignment: className.verticalAlignment
// 顯示字符,水平靠右顯示
horizontalAlignment: Text.AlignRight
// 設置寬度,Row的寬度的0.3
width: parent.width * 0.3
height: parent.height
}
TextField{
id: className
placeholderText: "請輸入班級名稱"
// 設置寬度,Row的寬度的0.60
width: parent.width * 0.60
height: parent.height
}
}
// 同上一行代碼
Row{
width: parent.width * 0.8
height: rowHeight
spacing: rowSpacing
anchors.horizontalCenter: parent.horizontalCenter
Label{
text: "班主任"
verticalAlignment: teacherInChargeClass.verticalAlignment
horizontalAlignment: Text.AlignRight
width: parent.width * 0.3
height: parent.height
}
TextField{
id: teacherInChargeClass
placeholderText: "請輸入班主任姓名"
width: parent.width * 0.6
height: parent.height
}
}
Row{
width: parent.width * 0.8
height: rowHeight
spacing: rowSpacing
anchors.horizontalCenter: parent.horizontalCenter
// 設置Button一行的左側的充滿寬度
Label{
text: ""
// 寬度說明
// 上述兩行(班級名稱,班主任)的總寬度是id=column的寬度的0.9倍
// 三個Button的寬度 = b1.width*3
// 三個Button的寬度,其中間的間隔有兩個間隔寬度
// 所以本行的寬度和上兩行的寬度是一致的,這樣就保證了button右對齊的
width: parent.width * 0.9 - b1.width*3 - rowSpacing*2
height: parent.height
}
Button{
id: b1
text: "新增"
width: parent.width * 0.15
height: parent.height
}
Button{
id: b2
text: "保存"
width: parent.width * 0.15
height: parent.height
}
Button{
id: b3
text: "放棄"
width: parent.width * 0.15
height: parent.height
}
}
}
}
參考課程 《QT QML跨平臺移動APP編程》