Slint GridLayout 详解:从基础到实战的网格布局指南

📅 2026/7/5 15:16:13 👁️ 阅读次数 📝 编程学习
Slint GridLayout 详解:从基础到实战的网格布局指南

Slint GridLayout 详解:从基础到实战的网格布局指南

  • 一、Slint GridLayout 详解
    • 1、📌 核心概念
    • 2、🧩 子元素放置
    • 3、⚙️ 响应式逻辑
    • 4、🧾属性详解
  • 二、代码示例
    • 1、示例代码
    • 2、效果展示

一、Slint GridLayout 详解

1、📌 核心概念

GridLayout是用于创建二维网格布局的容器组件,对标 HTML 中的 CSS Grid。它通过以下方式定义布局结构:

GridLayout { spacing: 5px; Row { Rectangle { background: red; } Rectangle { background: blue; } } Row { Rectangle { background: yellow; } Rectangle { background: green; } } }

2、🧩 子元素放置

通过colandrow属性控制子元素在网格中的位置:

export component Foo inherits Window { width: 200px; height: 150px; GridLayout { Rectangle { background: red; } Rectangle { background: blue; } Rectangle { background: yellow; row: 1; } Rectangle { background: green; } Rectangle { background: black; col: 2; row: 0; } } }

涉及的属性参数:

  • rowspan/colspan:跨越的行数/列数
  • col/row:旧版兼容写法(建议用新语法)

3、⚙️ 响应式逻辑

网格尺寸自适应规则:
实际宽度 = 列权重 ∑ 所有权重 × 容器总宽度 \text{实际宽度} = \frac{\text{列权重}}{\sum \text{所有权重}} \times \text{容器总宽度}实际宽度=所有权重列权重×容器总宽度

4、🧾属性详解

属性详解
spacing布局中元素之间的距离。此单一值同时应用于水平和垂直间距。
spacing-horizontal水平间距
spacing-vertical垂直间距
padding网格结构周围的填充作为一个整体。此单个值应用于所有边。
padding-left左边距
padding-right右边距
padding-top顶边距
padding-bottom底边距
row该元素在网格中的行索引。除非已明确设置,否则设置此属性会将该元素的列重置为零。
col元素在网格中的列索引。设置此属性可覆盖顺序列分配(例如,跳过某一列)。
rowspan此元素应跨越的行数。
colspan此元素应跨越的列数。

二、代码示例

1、示例代码

import{AboutSlint,VerticalBox,LineEdit,HorizontalBox,Button,GroupBox,GridBox,ComboBox,Spinner,Slider,ListView,Palette,ProgressIndicator,CheckBox,Switch,StandardTableView,SpinBox}from"std-widgets.slint";export component GridDemo inherits Window{title:"Slint GridLayout 完整示例";width:800px;height:600px;// 主网格布局:3列 + 自动行,演示核心特性main-grid:=GridLayout{// ========== 1. 全局间距 & 内边距 ==========spacing:8px;// 单元格之间间距padding:10px;// 布局整体内边距// ========== 第1行:普通单元格(默认填满) ==========Rectangle{background:#e6f7ff;Text{text:"单元格 (1,1)";}}Rectangle{background:#f0f8ff;Text{text:"单元格 (1,2)";}}Rectangle{background:#f5fafe;Text{text:"单元格 (1,3)";}}// ========== 第2行:跨行 / 跨列 (核心特性) ==========Rectangle{background:#ffeaa7;colspan:2;// 横跨 2 列Text{text:"colspan=2 跨两列";}}Rectangle{background:#dfe6e9;rowspan:2;// 纵跨 2 行Text{text:"rowspan=2 跨两行";}}// ========== 第3行:承接上一行跨行位置 ==========Rectangle{background:#81ecec;Text{text:"单元格 (3,1)";}}Rectangle{background:#74b9ff;Text{text:"单元格 (3,2)";}}// ========== 第4行:对齐方式 + 最小尺寸 ==========Rectangle{background:#a29bfe;min-width:80px;min-height:40px;// 内部水平/垂直对齐Text{text:"左上对齐";horizontal-alignment:start;vertical-alignment:top;}}Rectangle{background:#fd79a8;Text{text:"居中对齐";horizontal-alignment:center;vertical-alignment:center;}}Rectangle{background:#00b894;Text{text:"右下对齐";horizontal-alignment:end;vertical-alignment:bottom;}}// ========== 第5行:混合原生控件 + 拉伸权重 ==========// row/column 权重:控制单元格拉伸比例Row{GridLayout{spacing:4px;Button{text:"按钮1";}CheckBox{text:"选项";}SpinBox{value:50;}}}}}

2、效果展示