C++圖形用戶界面開發框架Qt 6.x - QML中的定位器和佈局

有很多種方法可以在QML中定位項目,以下是簡要的概述。

手動定位

通過設置項目的 x,y 屬性,可以將項目放置在屏幕上的特定 x,y 座標處。 根據可視化座標系規則,這將設置它們相對於父級左上角的位置。

結合使用綁定替代這些屬性的常量值,通過將 x 和 y 座標設置爲適當的綁定,也可以輕鬆實現相對定位。

 

import QtQuick

Item {
width: 100; height: 100

Rectangle {
// Manually positioned at 20,20
x: 20
y: 20
width: 80
height: 80
color: "red"
}
}

 

用例 - QML中的定位器和佈局

錨定

Item類型提供了錨定到其他Item類型的功能,每個項目有7條錨線:左、右、垂直居中、頂部、底部、基線和水平居中。三個垂直錨線可以錨定到另一個項目的三個垂直錨線中的任何一個,四個水平錨線可以錨定到另一個項目的水平錨線。

 

import QtQuick

Item {
width: 200; height: 200

Rectangle {
// Anchored to 20px off the top right corner of the parent
anchors.right: parent.right
anchors.top: parent.top
anchors.margins: 20 // Sets all margins at once

width: 80
height: 80
color: "orange"
}

Rectangle {
// Anchored to 20px off the top center corner of the parent.
// Notice the different group property syntax for 'anchors' compared to
// the previous Rectangle. Both are valid.
anchors { horizontalCenter: parent.horizontalCenter; top: parent.top; topMargin: 20 }

width: 80
height: 80
color: "green"
}
}

 

用例 - QML中的定位器和佈局

定位器

對於想要以常規模式定位一組類型的常見情況,Qt Quick提供了一些定位器類型。放置在定位器中的物品會以某種方式自動定位; 例如, Row將項目定位爲水平相鄰(形成一行)。

 

import QtQuick

Item {
width: 300; height: 100

Row { // The "Row" type lays out its child items in a horizontal line
spacing: 20 // Places 20px of space between items

Rectangle { width: 80; height: 80; color: "red" }
Rectangle { width: 80; height: 80; color: "green" }
Rectangle { width: 80; height: 80; color: "blue" }
}
}

 

用例 - QML中的定位器和佈局

佈局類型

Layout types功能與定位器類似,但允許進一步細化或限制佈局。 具體來說,Layout types允許您:

  • 設置文本和其他項目的對齊方式
  • 自動調整和填充分配的應用程序區域
  • 設置尺寸限制,例如最小或最大尺寸
  • 設置佈局內項目之間的間距

 

GroupBox {
id: gridBox
title: "Grid layout"
Layout.fillWidth: true

GridLayout {
id: gridLayout
rows: 3
flow: GridLayout.TopToBottom
anchors.fill: parent
Label { text: "Line 1" }
Label { text: "Line 2" }
Label { text: "Line 3" }

TextField { }
TextField { }
TextField { }

TextArea {
text: "This widget spans over three rows in the GridLayout.\n"
+ "All items in the GridLayout are implicitly positioned from top to bottom."
Layout.rowSpan: 3
Layout.fillHeight: true
Layout.fillWidth: true
}
}
}

 

上面的代碼片段來自基本佈局示例,該代碼段顯示了在佈局中添加各種字段和項目的簡單性。 GridLayout 可以調整大小,並且可以通過各種屬性自定義其格式。

Qt商用組件推薦

  • QtitanRibbon - Ribbon UI組件:是一款遵循Microsoft Ribbon UI Paradigm for Qt技術的Ribbon UI組件,QtitanRibbon致力於爲Windows、Linux和Mac OS X提供功能完整的Ribbon組件。
  • QtitanChart - Qt類圖表組件:是一個C ++庫,代表一組控件,這些控件使您可以快速地爲應用程序提供漂亮而豐富的圖表。
  • QtitanDataGrid - Qt網格組件:提供了一套完整的標準 QTableView 函數和傳統組件無法實現的獨特功能。使您能夠將不同來源的各類數據加載到一個快速、靈活且功能強大的可編輯網格中,支持排序、分組、報告、創建帶狀列、拖放按鈕和許多其他方便的功能。
  • QtitanNavigation:QtitanNavigationDesignUI 組件是一組 GUI 控件,它實現了菜單、導航框、命令欄等導航界面,並讓您以更少的滾動和點擊次數有效地查看所有實體(工作區、網格或其他項目)。
  • QtitanDocking:允許您像 Visual Studio 一樣爲您的偉大應用程序配備可停靠面板和可停靠工具欄。黑色、白色、藍色調色板完全支持 Visual Studio 2019 主題!

Qt技術交流羣:166830288      歡迎一起進羣討論

更多Qt產品教程、下載、正版授權資訊,請點擊獲取

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章