跳到主要内容

可堆叠布局 Stack

一个将其子控件叠放在一起的控件。

如果您想简单地重叠多个子控件,例如在图像上叠放一些文本和图像,然后在底部添加一个渐变和按钮,那么这个控件非常有用。

Stack 还非常适用于实现需要知道目标值的绝对位置的隐式动画

Examples

Live example

Transparent title over an image

import flet as ft

def main(page: ft.Page):
st = ft.Stack(
[
ft.Image(
src=f"https://picsum.photos/300/300",
width=300,
height=300,
fit=ft.ImageFit.CONTAIN,
),
ft.Row(
[
ft.Text(
"Image title",
color="white",
size=40,
weight="bold",
opacity=0.5,
)
],
alignment=ft.MainAxisAlignment.CENTER,
),
],
width=300,
height=300,
)

page.add(st)

ft.app(target=main)

Avatar with online status

import flet as ft

def main(page):
page.add(
ft.Stack(
[
ft.CircleAvatar(
foreground_image_url="https://avatars.githubusercontent.com/u/5041459?s=88&v=4"
),
ft.Container(
content=ft.CircleAvatar(bgcolor=ft.colors.GREEN, radius=5),
alignment=ft.alignment.bottom_left,
),
],
width=40,
height=40,
)
)

ft.app(target=main, view=ft.AppView.WEB_BROWSER)

Absolute positioning inside Stack

import flet as ft

def main(page: ft.Page):

page.horizontal_alignment = ft.CrossAxisAlignment.CENTER
page.vertical_alignment = ft.MainAxisAlignment.CENTER

page.add(
ft.Container(
ft.Stack(
[
ft.Container(width=20, height=20, bgcolor=ft.colors.RED, border_radius=5),
ft.Container(
width=20,
height=20,
bgcolor=ft.colors.YELLOW,
border_radius=5,
right=0,
),
ft.Container(
width=20,
height=20,
bgcolor=ft.colors.BLUE,
border_radius=5,
right=0,
bottom=0,
),
ft.Container(
width=20,
height=20,
bgcolor=ft.colors.GREEN,
border_radius=5,
left=0,
bottom=0,
),
ft.Column(
[
ft.Container(
width=20,
height=20,
bgcolor=ft.colors.PURPLE,
border_radius=5,
)
],
left=35,
top=35,
),
]
),
border_radius=8,
padding=5,
width=100,
height=100,
bgcolor=ft.colors.BLACK,
)
)

ft.app(target=main)

属性

clip_behavior

内容将根据此选项进行裁剪(或不裁剪)。

属性值为 ClipBehavior 枚举,支持的值有:

  • NONE
  • ANTI_ALIAS
  • ANTI_ALIAS_WITH_SAVE_LAYER
  • HARD_EDGE(默认)

controls

要在 Stack 中显示的控件列表。列表中的最后一个控件将显示在最顶层。