Labs / LVGL

04 Quick Start Case - Layout and Space Management (Based on Web Simulator and LVGL v9.0

Author: Li Zisheng · Source: FreakStudio open documentation, v1.1 · License: CC BY 4.0

Contents

4.1 Box Model

LVGL box model = a 4-layer structure, which consists of, from the inside out:

Hierarchy

Function

Code Correspondence

Effect / Description

Content Area (Content)

The actual content placed inside the box.

Label and other content controls such as tags

Located at the innermost layer, where text and icons are displayed; it will be wrapped by padding and will not directly stick to the border.

Padding

The blank space between the content and the border.

set_pad_all(15)

Leave 15 pixels of blank space on the top, bottom, left and right sides respectively to keep the content away from the edges and make the interface more aesthetically pleasing.

Border

The outer contour line of the box.

set_border_width(),set_border_color()

It wraps the padding and the content area to form the boundary of the box.

Shadow

The projection on the exterior of the box.

Attributes such as shadow width and offset

It is only responsible for visual beautification, does not occupy layout space, and will not affect the size or position of the box.

Summary

The LVGL box model consists of a four-layer structure.

Content + padding + border + shadow

Total size of the control = content + padding + border; shadows are not included in the actual layout size.

The sample code is as follows:

import display_driver
import lvgl as lv

lv.init()
# Initialize screen
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)

# 1. Create container (box model carrier)
obj = lv.obj(scr)
obj.set_pos(80, 80)    # Position of the box on the screen
obj.set_size(120, 120) # Total size of the box

# 2. Core: box model styles (simplified, keeping only key attributes)
style = lv.style_t()
# --------- Padding: blank space inside the box ---------
style.set_pad_all(15)       # Uniform padding on all sides
# --------- Background (base color of the content area) ---------
style.set_bg_color(lv.color_hex(0xFF0000)) # Red background
style.set_bg_opa(255)
# --------- Border: the box's border ---------
style.set_border_width(3)   # Border width
style.set_border_color(lv.color_hex(0x00FF00)) # Green border
# --------- Shadow: drop shadow outside the box ---------
style.set_shadow_width(8)
style.set_shadow_color(lv.color_hex(0x00FFFF))
style.set_shadow_offset_x(5)
style.set_shadow_offset_y(5)

# Apply style
obj.add_style(style, lv.STATE.DEFAULT)

# 3. Content area: label (placed inside the box, squeezed by the padding)
label = lv.label(obj)
label.set_text("BOX")
label.center() # Centered inside the box
label.set_style_text_color(lv.color_hex(0xFFFFFF), 0)

# Show interface
lv.screen_load(scr)
04 Quick Start Case - Layout and Space Management (Based on Web Simulator and LVGL v9.0

This code transforms the abstract "box model" into an intuitive and visible interface by combining a red container, internal labels, and visual layering, which perfectly corresponds to the four-layer structure of LVGL widgets:

4.2 Position and Dimension Settings

In the following code, a rectangular control with a custom visual style is implemented: after initializing LVGL, set the screen background to black, create a 100×100 pixel square object at the screen coordinate (100,100), configure styles such as red background, green border, and green translucent shadow for this object, and finally load the screen to complete the rendering. Eventually, a red square with green border and shadow will be displayed on the screen:

import display_driver
import lvgl as lv

lv.init()

#Get the currently active screen object
scr = lv.screen_active()
#Set the screen background color to black
scr.set_style_bg_color(lv.color_hex(0x000000), 0)

#Create the object
obj = lv.obj(scr)
#Set the object position and size
obj.set_pos(100, 100)   #Set the top-left coordinates of the object
obj.set_size(100, 100)  #Set the width and height of the object

#Create a style
style_obj = lv.style_t()
#Border and background
style_obj .set_pad_all(10)    #Set padding in all four directions
#style_obj  .set_pad_left(10)   #Set left padding
#style_obj .set_pad_right(10)  #Set right padding
#style_obj .set_pad_top(10)    #Set top padding
#style_obj  .set_pad_bottom(10) #Set bottom padding
style_obj .set_bg_opa(255)  #Set background opacity; 0 is fully transparent
style_obj .set_bg_color(lv.color_hex(0xFF0000))   #Set background color
style_obj .set_border_color(lv.color_hex(0x00FF00))   #Set border color
style_obj  .set_border_width(2)   #Set border width
style_obj .set_border_opa(255)   #Set border opacity; 0 is fully transparent
#Shadow style
style_obj .set_shadow_color(lv.color_hex(0x00FF00))#Set shadow color
style_obj .set_shadow_width(10)#Set shadow width (shadow spread range)
style_obj .set_shadow_opa(50)#Set shadow opacity
style_obj .set_shadow_offset_x(10)#Set shadow horizontal offset
style_obj .set_shadow_offset_y(10)#Set shadow horizontal offset
#Apply the style
obj.add_style(style_obj , lv.STATE.DEFAULT)

# Load the screen
lv.screen_load(scr)
v9.0 4.2
100

4.2.1 Modify the position and size of the object

We can use the following methods to modify the position and size of an object:

#Set the object position and size
obj.set_pos(150, 150)   #Set the top-left coordinates of the object
obj.set_size(120, 120)  #Set the width and height of the object
100 4.2

4.2.2 Internal Alignment (Typesetting within the Parent Container)

Here is an example of internal alignment:

v9.0 4.2.2
# ============== Internal alignment: auto layout inside the parent container obj ==============
# 1. Create child widget (placed inside obj)
child = lv.obj(obj)
child.set_size(40, 40)  # Child widget size

# 2. Give the child widget a blue style (for easy distinction)
style_child = lv.style_t()
style_child.set_bg_color(lv.color_hex(0x00AAFF))
style_child.set_bg_opa(255)
child.add_style(style_child, lv.STATE.DEFAULT)

# 3. ✅ Core: internal alignment API (run any one line to see different effects)
child.align(lv.ALIGN.CENTER, 0, 0)          # Exact center of the parent container (no offset)
# child.align(lv.ALIGN.TOP_LEFT, 5, 5)       # Top-left of the parent container, offset inward by (5,5)
# child.align(lv.ALIGN.BOTTOM_RIGHT, -5, -5) # Bottom-right of the parent container, offset inward by (-5,-5)
# child.align(lv.ALIGN.LEFT_MID, 5, 0)      # Left-center of the parent container, offset 5px to the right

4.2.3 External Alignment (Align with Other Controls)

v9.0
# ============== External alignment: align outside the obj widget ==============
# 1. First create a reference widget (a button here; it can be any other widget)
ref_btn = lv.button(scr)
ref_btn.set_pos(200, 100)
ref_btn.set_size(60, 30)
ref_label = lv.label(ref_btn)
ref_label.set_text("REF")
ref_label.center()

# 2. Create the label widget to be aligned
label = lv.label(scr)
label.set_text("OUT_LABEL")
label.set_style_text_color(lv.color_hex(0xFFFFFF), 0)  # White text

# 3. ✅ Core: external alignment API (run any one line to see different effects)
label.align_to(ref_btn, lv.ALIGN.OUT_TOP_MID, 0, -10)    # Top-center of the reference button, offset 10px upward
# label.align_to(ref_btn, lv.ALIGN.OUT_RIGHT_MID, 10, 0) # Right-center of the reference button, offset 10px to the right
# label.align_to(ref_btn, lv.ALIGN.OUT_BOTTOM_LEFT, 0, 10) # Bottom-left of the reference button, offset 10px downward

4.3 Translation

It uses the "relative offset" based on the object's current position to solve the problem that "objects with different initial positions will offset by the same distance during interaction"(e. g., a button moves upward when pressed). Here is an mpy example:


# Initialize

import display_driver
import lvgl as lv

# Create a button with a label

lv.init()
scr = lv.screen_active()

btn = lv.button(scr)
btn.align(lv.ALIGN.CENTER, 0, 0)

# 1. Create the default state style
style_normal = lv.style_t()
style_normal.init()
style_normal.set_width(100)  # Default width 100 pixels

# 2. Create the pressed state style
style_pressed = lv.style_t()
style_pressed.init()
style_pressed.set_width(120)  # Width 120 pixels when pressed
# Create the pressed state style, set y-axis translation to -20 pixels (move up 20)
style_pressed.set_translate_y(-20)

# 3. Add styles to the button
btn.add_style(style_normal, lv.STATE.DEFAULT)
btn.add_style(style_pressed, lv.STATE.PRESSED)

lv.screen_load(scr)
v9.0 v1.20.0 1053 c349ae32bf 2024 09 11 4.3
v9.0

Furthermore, there are two key features:

4.4 Transformation

"Visual scaling" based on the object's current size only alters the display effect without affecting its actual dimensions (layout, scrollbars, and content Self-Adaptation will not detect this). mpy example (enlarging when the button is pressed):


# Initialize

import display_driver
import lvgl as lv

# Create a button with a label

lv.init()
scr = lv.screen_active()

btn = lv.button(scr)
btn.align(lv.ALIGN.CENTER, 0, 0)

# 1. Create the default state style
style_normal = lv.style_t()
style_normal.init()
style_normal.set_width(100)  # Default width 100 pixels

# 2. Create the pressed state style
style_pressed = lv.style_t()
style_pressed.init()
style_pressed.set_width(120)  # Width 120 pixels when pressed
# Expand width/height outward by 10 pixels each (visually +20 in width, +20 in height)
style_pressed.set_transform_width(10)
style_pressed.set_transform_height(10)

# 3. Add styles to the button
btn.add_style(style_normal, lv.STATE.DEFAULT)
btn.add_style(style_pressed, lv.STATE.PRESSED)

lv.screen_load(scr)
v9.0
v9.0 v1.20.0
FeatureTranslationTransformation
Position / sizeChanges the real positionVisual scaling only; the real size is unchanged
Layout ImpactAffects layout / scrollbarDoes not affect layout / scrollbar
PurposePosition offset during interactionVisual scaling during interaction (no layout interference)

4.5 Layout System

Layout is a core mechanism in LVGL for automatically arranging widgets, which can replace manually calling set_pos () to calculate coordinates, making the interface more structured and easier to maintain, and is especially suitable for GUI development with limited screen sizes in embedded scenarios.

The core concepts include the following. First, the layout container:

Layout types include:

Layout TypeApplicable scenariosCore characteristics
Flex layoutLinear arrangement (one row / one column), such as horizontal menus and vertical settings listsChild widgets are automatically arranged along a single direction (horizontal / vertical), with spacing handled automatically
Grid layoutTwo-dimensional table arrangement, such as number keypads and 3×3 function matricesDivides the container into cells of multiple rows and columns; child widgets can be precisely assigned to specified cells

The basic layout process is as follows:

  1. Create Container: lv.obj (scr)—— Generates an empty container for holding the layout
  2. Enable Layout: set_layout (layout_type)—— Select Flex or Grid mode
  3. Configuration Rules: Set parameters such as direction, spacing, grid rows and columns, etc.
  4. Add Control: Add child controls such as buttons and labels to the container — the controls will be automatically arranged according to the rules
  5. Load Display: lv.screen_load (scr)—— Render the layout to the screen
04 Quick Start Case - Layout and Space Management (Based on Web Simulator and LVGL v9.0
04 Quick Start Case - Layout and Space Management (Based on Web Simulator and LVGL v9.0

4.5.1 Row/Column Arrangement (Flex Layout)

The following code is a standard example of LVGL MicroPython flex layout, which implements horizontal row arrangement and vertical column arrangement of buttons:

import display_driver
import lvgl as lv

# Initialize LVGL
lv.init()
scr = lv.screen_active()

# Generic button callback function
def btn_cb(e):
    print("按钮点击")

# Minimal button creation
def make_btn(parent, text):
    btn = lv.button(parent)
    btn.set_size(70, 40)
    btn.add_event_cb(btn_cb, lv.EVENT.PRESSED, None)
    label = lv.label(btn)
    label.set_text(text)
    label.center()
    return btn

# ============== 1. Horizontal row layout (one horizontal row) ==============
row = lv.obj(scr)
row.set_size(320, 60)
row.set_pos(10, 10)
row.set_layout(lv.LAYOUT.FLEX)                # Correct: flex layout
row.set_style_flex_flow(lv.FLEX_FLOW.ROW, 0)  # Correct: horizontal row
row.set_style_pad_column(10, 0)               # Horizontal spacing between buttons

# Automatically arrange 3 buttons horizontally
make_btn(row, "A1")
make_btn(row, "A2")
make_btn(row, "A3")

# ============== 2. Vertical column layout (one vertical column) ==============
col = lv.obj(scr)
col.set_size(90, 220)
col.set_pos(10, 80)
col.set_layout(lv.LAYOUT.FLEX)                  # Correct: flex layout
col.set_style_flex_flow(lv.FLEX_FLOW.COLUMN, 0) # Correct: vertical column
col.set_style_pad_row(10, 0)                   # Vertical spacing between buttons

# Automatically arrange 4 buttons vertically
make_btn(col, "1A")
make_btn(col, "1B")
make_btn(col, "1C")
make_btn(col, "1D")

lv.screen_load(scr)
A1 A2 A3 1A 1B 1C 1D
A1 A2 A3 1A 1B 1C 1D
A1 A2 A3 1A 1B 1C 1D

In the code above, we performed the following operations on the layout container:

Among these, the core attribute settings of Flex layout include:

The layout direction attributes include:

Spacing control attributes include:

Core Fundamentals of Flex Layout

Layout Direction (Flow)

Controlling the arrangement direction of child controls is the core switch of Flex layout:

  • lv.FLEX_FLOW.ROW: Horizontal arrangement (left to right)
  • lv.FLEX_FLOW.COLUMN: Vertical and longitudinal arrangement (from top to bottom)
Spacing Control

Avoid overcrowded controls and optimize the aesthetic appeal of the interface:

  • When arranged horizontally: set_style_pad_column (pixels, 0)—— sets the horizontal spacing between child controls
  • When arranged vertically: set_style_pad_row (pixels, 0)—— Sets the vertical spacing between child controls
Alignment Logic

Child widgets will automatically fill along the layout direction, and their position within the container can be adjusted via alignment properties (such as lv.FLEX_ALIGN.CENTER).

4.5.2 Two-Dimensional Grid Arrangement (Grid Layout)

The code below implements a two-dimensional grid layout, which creates a regular button grid with 2 rows and 3 columns based on the officially revised API:

import display_driver
import lvgl as lv

# Initialize LVGL
lv.init()
scr = lv.screen_active()

# Click callback
def btn_cb(e):
    print("按钮点击")

# Create button
def make_btn(parent, text):
    btn = lv.button(parent)
    btn.set_size(70, 40)
    btn.add_event_cb(btn_cb, lv.EVENT.PRESSED, None)
    label = lv.label(btn)
    label.set_text(text)
    label.center()
    return btn

# ==================== 2D grid layout (2 rows, 3 columns) ====================
grid = lv.obj(scr)
grid.set_size(280, 150)
grid.set_pos(20, 20)
grid.set_layout(lv.LAYOUT.GRID)

# Define 3 columns + 2 rows
col_dsc = [80, 80, 80, lv.GRID_TEMPLATE_LAST]
row_dsc = [50, 50, lv.GRID_TEMPLATE_LAST]

# Correct API
grid.set_grid_dsc_array(col_dsc, row_dsc)

# Spacing
grid.set_style_pad_row(10, 0)
grid.set_style_pad_column(10, 0)

# Loop to create buttons + set grid positions strictly following your API
for i in range(6):
    col = i % 3   # Columns: 0,1,2
    row = i // 3  # Rows: 0,0,0,1,1,1
    
    btn = make_btn(grid, str(i+1))
    
    # ✅ Strictly matches the 6 parameters you provided!!!
    btn.set_grid_cell(
        lv.GRID_ALIGN.CENTER,  # 1. column_align: column alignment
        col,                   # 2. col_pos: column position
        1,                     # 3. col_span: spans 1 column
        lv.GRID_ALIGN.CENTER,  # 4. row_align: row alignment (must be passed in your API!)
        row,                   # 5. row_pos: row position
        1                      # 6. row_span: spans 1 row
    )

lv.screen_load(scr)
v9.0 2 3 1 6

In the code above, after initializing the LVGL graphics library and the screen container, we encapsulated a general button creation function with click response. By enabling GRID grid layout, defining row and column size descriptors, and setting spacing, we then generated buttons in a loop and strictly followed the 6-parameter specification of set_grid_cell to specify the grid alignment, position and span of each button, and finally loaded the screen to implement a neatly arranged grid interface, which fully demonstrates the core usage of LVGL grid layout.

The core APIs and attributes are defined as follows:

Core Fundamentals of Grid Layout

Grid Descriptor (col_dsc / row_dsc)

Defines the column width and line-height of the grid, serving as the "skeleton" of Grid layout:

  • Format:[col_width_1, col_width_2,. .., lv.GRID_TEMPLATE_LAST], lv.GRID_TEMPLATE_LAST is a fixed end marker.
  • Example: col_dsc = [80,80,80, lv.GRID_TEMPLATE_LAST]→ Defines 3 columns, each with a width of 80px
Grid Frame Binding

set_grid_dsc_array (col_dsc, row_dsc)—— Apply the defined row and column dimensions to the container to complete the construction of the cell framework.

Precise Control Positioning (set_grid_cell)

Assign specific cells to child controls, with the 6 parameters strictly corresponding to the LVGL grid rules:

  1. column_align: Column alignment method (e. g., lv.GRID_ALIGN.CENTER for center alignment)
  2. col_pos: the index of the column where the item is located (starting from 0)
  3. col_span: Number of columns occupied (usually 1)
  4. row_align: Row alignment mode
  5. row_pos: the index of the row where the element is located (starting from 0)
  6. row_span: Number of rows occupied (usually 1)

4.6 Scrolling

Scrolling is the core interaction mechanism in LVGL that enables users to swipe and browse when content exceeds the container, which is widely used in scenarios such as lists, long text, and carousels, with a design that fits the operation intuition of embedded devices.

The essence of scrolling lies in the "size difference" between the container and the content:

It should be noted that LVGL does not support diagonal scrolling, and you can only choose one of the following two directions:

The scrollbar is a standalone component (LV_PART_SCROLLBAR) of the container, used to visually indicate:

Scrollbars can have their styles (color, thickness, spacing) customized individually, and their show/hide logic can also be controlled.

A complete scrolling operation goes through three key stages, which can be monitored via event listeners:

LVGL MicroPython scrolling function API cheat sheet is as follows:

Category

Method

Function

Description / Scenario

Scroll Basic Configuration

set_scroll_dir(dir)

Set the allowed scrolling direction

It supports controlling horizontal scrolling, vertical scrolling, or disabling scrolling entirely.

Scroll Basic Configuration

set_scrollbar_mode(mode)

Set the scrollbar display mode

The scrollbar can be configured to automatically show, always show, or be hidden.

Scroll Basic Configuration

set_scroll_snap_x(align) / set_scroll_snap_y(align)

Set scroll snapping effect

It will automatically align to the specified position after you release it, which is suitable for scenarios such as carousel carousels.

Scroll Control Method

scroll_by (dx, dy, anim_en)

Relative Scrolling

Scroll based on the offset from the current position dx / dy pixels.

Scroll Control Method

scroll_to(x, y, anim_en)

Absolute Scrolling

Scroll directly to the specified x / y coordinate position.

Scroll Control Method

scroll_to_x(x, anim_en) / scroll_to_y(y, anim_en)

Independently control horizontal / vertical scrolling

Control the scrolling position in the X-axis or Y-axis direction respectively.

Scroll Control Method

scroll_to_view(anim_en)

Automatically scroll to display the current control

Make the current control fully displayed on the screen, which is often used for automatic element positioning.

Scroll State Acquisition

get_scroll_x() / get_scroll_y()

Get the current scroll coordinates

Returns the current X/Y scroll position of the container.

Scroll State Acquisition

get_scroll_top() / get_scroll_bottom()

Obtain the vertical boundaries

Returns the maximum scroll boundaries at the top / bottom in the vertical direction.

Scroll State Acquisition

get_scroll_left() / get_scroll_right()

Get the horizontal boundary

Returns the maximum scroll boundary on the left / right side in the horizontal direction.

04 Quick Start Case - Layout and Space Management (Based on Web Simulator and LVGL v9.0

Scroll Direction Setting:

FunctionRelated code
Vertical scrollingcontainer.set_scroll_dir(lv.DIR.VER)
Horizontal scrollingcontainer.set_scroll_dir(lv.DIR.HOR)
Scrolling disabledcontainer.set_scroll_dir(lv.DIR.NONE)
Scrollbar shown automaticallycontainer.set_scrollbar_mode(lv.SCROLLBAR_MODE.AUTO)

The LVGL scrollbar modes are as follows:

Enum constantMeaningCore function (beginner-friendly)
lv.SCROLLBAR_MODE.OFFOffNever shows the scrollbar, completely hidden
lv.SCROLLBAR_MODE.ONAlways shownAlways shows the scrollbar, whether or not the content overflows
lv.SCROLLBAR_MODE.ACTIVEShown while scrollingShown only while the finger is swiping / scrolling, and hidden once it stops
lv.SCROLLBAR_MODE.AUTOAutomatic displayRecommended by default; shows the scrollbar only when the content overflows the container

LVGL provides three types of core events for capturing the entire lifecycle of scrolling:

04 Quick Start Case - Layout and Space Management (Based on Web Simulator and LVGL v9.0

Core Event

Meaning of Core Events

SCROLL_BEGIN

Triggered when scrolling starts, the parameters of the scrolling animation (such as animation duration and easing curve) can be modified;

SCROLL_END

Triggered when scrolling ends, it is suitable for executing the final logic after scrolling (such as loading more content and updating status);

SCROLL

Triggered during the scrolling process (on every position change), it is suitable for real-time monitoring of scroll position (e. g. dynamically updating UI elements, recording scroll offset).

4.6.1 Scrolling Basic Demo

In the following case, we will create a small container, place a large number of buttons in it (the content will exceed the container size), which automatically supports scrolling, so you can intuitively feel the trigger conditions for scrolling.

import display_driver
import lvgl as lv

lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0) # Black background

# ==================== 1. Create scroll container (parent object) ====================
container = lv.obj(scr)
container.set_size(200, 150)  # Container size is very small (limits the display area)
container.set_pos(50, 50)     # Container position
container.set_scroll_dir(lv.DIR.VER) # Enable [vertical scrolling] (core)
container.set_scrollbar_mode(lv.SCROLLBAR_MODE.AUTO) # Scrollbar shows automatically

# ==================== 2. Create many child buttons (content exceeds the container, triggering scrolling) ====================
for i in range(10):
    btn = lv.button(container)
    btn.set_size(180, 30)
    btn.set_pos(10, 10 + i*40) # Arrange buttons vertically
    
    label = lv.label(btn)
    label.set_text(f"Button {i+1}")
    label.center()

lv.screen_load(scr)
v9.0 3 4 5 6
v9.0 6 7 8 9

Here, we can see that:

We can also set different scrolling directions for viewing:

FunctionRelated code
Vertical scrollingcontainer.set_scroll_dir(lv.DIR.VER)
Horizontal scrollingcontainer.set_scroll_dir(lv.DIR.HOR)
Scrolling disabledcontainer.set_scroll_dir(lv.DIR.NONE)

Here is the horizontal scroll:

v9.0 1 2 3

The following is to disable scrolling:

v9.0

If we do not specify the scrolling direction, it will be automatically set based on the sizes of the container and the internal controls (both vertical and horizontal directions are supported):

# The comment on the line below
# container.set_scroll_dir(lv.DIR.VER)
v9.0 1 4

We can also set the scrolling mode; the following is the case where the scrollbar is not displayed:

container.set_scrollbar_mode(lv.SCROLLBAR_MODE.OFF)
v9.0 2 3 4 5

The following is to display the scrollbar when scrolling:

container.set_scrollbar_mode(lv.SCROLLBAR_MODE.ACTIVE)
4 5 6 7

The following is the one that always displays the scrollbar:

container.set_scrollbar_mode(lv.SCROLLBAR_MODE.AUTO)
v9.0 4 5 6

4.6.2 Scroll Event Listening

Based on Case 1, monitor the scroll start and scroll end events, and print logs in the terminal so that beginners can intuitively observe the changes in scroll status.

import display_driver
import lvgl as lv

lv.init()
scr = lv.screen_active()
scr.set_style_bg_color(lv.color_hex(0x000000), 0)

# ==================== Scroll event callback function ====================
def scroll_event_callback(e):
    target = e.get_target()  # Get the object that triggered the event (the scroll container)
    event_code = e.get_code() # Get the event type
    
    # Check for the scroll event
    if event_code == lv.EVENT.SCROLL_BEGIN:
        print("📜 滚动开始了!")
    elif event_code == lv.EVENT.SCROLL_END:
        print("📜 滚动完全结束!")

# ==================== 1. Create the scroll container ====================
container = lv.obj(scr)
container.set_size(200, 150)
container.set_pos(50, 50)
container.set_scroll_dir(lv.DIR.VER)
container.set_scrollbar_mode(lv.SCROLLBAR_MODE.ACTIVE) # Show scrollbar only while scrolling

# ==================== 2. Bind the scroll listener event (core) ====================
container.add_event_cb(scroll_event_callback, lv.EVENT.SCROLL_BEGIN, None)
container.add_event_cb(scroll_event_callback, lv.EVENT.SCROLL_END, None)

# ==================== 3. Create child buttons ====================
for i in range(10):
    btn = lv.button(container)
    btn.set_size(180, 30)
    btn.set_pos(10, 10 + i*40)
    label = lv.label(btn)
    label.set_text(f"Button:{i+1}")
    label.center()

lv.screen_load(scr)
v9.0 Button4 Button5 Button6 Button7

Here, we bind an event callback to the scroll container, so that the system will automatically notify us when the screen is swiped.

The two core events are as follows:

Common usage scenarios include loading more content when scrolling to the bottom, hiding controls while scrolling, and so on.

4.7 Layer Management

The layers in LVGL essentially control the rendering hierarchy of UI elements (i. e., "which object appears on top of another"), and there are two core layer systems:

To be precise:

1 4.7

4.7.1 Creation Order: Default Hierarchy Rules

LVGL follows the default "later-created objects on top" principle: newly created objects (and their child objects) are drawn on top of older objects (and their child objects), which may cover the display area of the older objects.

# Initialize

import display_driver
import lvgl as lv

# Create a button with a label

lv.init()
scr = lv.screen_active()

# Create the first button (created first, lower in z-order)
btn1 = lv.button(scr)
# Position (x=60, y=40)
btn1.set_pos(60, 40)      
label1 = lv.label(btn1)
label1.set_text("Button 1")

# Create the second button (created later, higher in z-order, covers the overlapping area of btn1)
btn2 = lv.button(scr)
# Position (x=60, y=60)
btn2.set_pos(60, 60)     
label2 = lv.label(btn2)
label2.set_text("Button 2")

lv.screen_load(scr)
v9.0 1 2

4.7.2 Modify Hierarchy: Adjust the Display Order of Objects Manually

When the default creation order fails to meet requirements (e. g., moving a bottom-layer button to the top layer), LVGL provides 4 explicit ways to modify the layer hierarchy, which can be directly invoked via the corresponding object methods in MicroPython:

4.7.2.1 Pin to Top / Pin to Bottom (Most Commonly Used)
Method (mpy)Purpose
obj.move_foreground()Move the object (and its children) to the top layer of the parent container
obj.move_background()Move the object (and its children) to the bottom layer of the parent container
v9.0 1 2 btn1.move_foreground btn1

mpy example: bring the previously created btn1 to the top layer (to cover btn2)

# Move btn1 to the topmost layer of the parent container (scr)
btn1.move_foreground()
4.7.2.2 Move to the specified index position

Each child object of a parent container has an "index value", which determines its hierarchy:

mpy core method:

# 1. Get the object's current index
current_idx = obj.get_index()

# 2. Move to the specified index (e.g., move up 1 level)
obj.move_to_index(current_idx + 1)

# 3. Move directly to the bottom layer (index 0)
obj.move_to_index(0)

mpy example:

1 btn1.move_foreground btn1.get_index
v9.0 1 2
btn1.move_to_index 1 btn1 0
4.7.2.3 Hierarchy Impact of Changing the Parent Object

When you modify an object's parent container via obj.set_parent (new_parent), the object automatically becomes the topmost child of the new parent container.

# Change btn1's parent to btn2; btn1 becomes the topmost child of btn2
btn1.set_parent(btn2)
1 2 btn1.set_parent btn2

4.7.3 Top Layer and System Layer (Top & Sys Layers)

LVGL provides two globally visible special layers for each physical display (shared by all screens, not shared across different displays), which are higher in the hierarchy than all objects on regular screens:

Many beginners are confused about LVGL's layer_top / layer_sys / layer_bottom, and the core reason is that they fail to understand the essential difference between "ordinary screen objects" and "global special layers":

显示器最终显示效果 = 最顶层往下叠加
├─ layer_sys(系统层,最顶层)→ 比如鼠标光标,永远在所有内容上面
├─ layer_top(顶级图层)→ 比如全局弹窗、悬浮窗,覆盖所有屏幕
├─ 当前活跃的普通屏幕(屏幕A/屏幕B)→ 普通按钮/标签都在这一层
└─ layer_bottom(底层图层)→ 比如全局背景图,在所有屏幕下面
4.7.3.1 layer_top (top-level layer): Globally visible "floating window / modal popup"

Similar to the "floating window" or "system pop-up window" on a mobile phone: no matter which APP (corresponding to a regular screen in LVGL) you switch to, the floating window remains displayed; after "modal mode" is enabled, the underlying content cannot be clicked (for example, a mobile phone pop-up window blocks the operations on the APP).

In the following code, two regular screens that can be switched between each other are created, and a globally visible modal popup is generated on layer_top. This popup is similar to the "system-level popup" on mobile phones: it will not disappear when switching between screens, and will block the interaction of the underlying screen. The buttons on the underlying screen can only be used normally after the popup is closed.

# Initialize

import display_driver
import lvgl as lv

lv.init()

# ===================== Step 1: Create two normal screens (for switching test) =====================
# Screen A: add a button; clicking it switches to screen B
scr_a = lv.obj()  # Create normal screen A
btn_a = lv.button(scr_a)
btn_a.set_size(180, 60)
btn_a.set_pos(50, 50)
label_a = lv.label(btn_a)
label_a.set_text("Screen A: Switch to B")

# Screen B: add a button; clicking it switches to screen A
scr_b = lv.obj()  # Create normal screen B
btn_b = lv.button(scr_b)
btn_b.set_size(180, 60)
btn_b.set_pos(50, 150)
label_b = lv.label(btn_b)
label_b.set_text("Screen B: Switch to A")

# Bind the screen switching event
def switch_to_b(e):
    lv.screen_load(scr_b)
btn_a.add_event_cb(switch_to_b, lv.EVENT.CLICKED, None)

def switch_to_a(e):
    lv.screen_load(scr_a)
btn_b.add_event_cb(switch_to_a, lv.EVENT.CLICKED, None)

# ===================== Step 2: Create a global modal popup with layer_top =====================
# 1. Get the display's top layer (global layer, shared by all screens)
top_layer = lv.layer_top()

# 2. Add a "click absorb" flag to top_layer → implements modal behavior (buttons below cannot be clicked)
# Principle: when the user clicks the screen, the click event is received by top_layer, and widgets on the underlying screen do not get the click event
top_layer.add_flag(lv.obj.FLAG.CLICKABLE)

# 3. Create the popup on top_layer (globally visible, stays regardless of which screen is shown)
popup = lv.obj(top_layer)  # The parent object is top_layer, not a normal screen!
popup.set_size(300, 200)   # Popup size
popup.center()             # Popup centered
# Set popup style: white background, gray border, rounded corners
popup.set_style_bg_color(lv.color_hex(0xFFFFFF), 0)    # White background
popup.set_style_border_color(lv.color_hex(0xCCCCCC), 0)# Gray border
popup.set_style_border_width(2, 0)                     # Border width 2px
popup.set_style_radius(10, 0)                          # Corner radius 10px

# 4. Add text + close button to the popup
popup_label = lv.label(popup)
popup_label.set_text("Global Modal Popup\n→ Persists across screen switches\n→ Blocks clicks on underlying elements")
popup_label.center()

# Add close button: clicking it removes the modal and closes the popup
close_btn = lv.button(popup)
close_btn.set_size(120, 30)
close_btn.align(lv.ALIGN.BOTTOM_MID, 0, -10)  # Popup bottom center
close_label = lv.label(close_btn)
close_label.set_text("Close Popup")

# Event to close the popup: remove click absorption + delete the popup
def close_popup(e):
    top_layer.remove_flag(lv.obj.FLAG.CLICKABLE)  # Cancel click absorption
    popup.delete()  # Delete the popup
close_btn.add_event_cb(close_popup, lv.EVENT.CLICKED, None)

# ===================== Step 3: Load the initial screen and run the test =====================
lv.screen_load(scr_a)  # Load screen A first
v9.0

It can be seen that:

04 Quick Start Case - Layout and Space Management (Based on Web Simulator and LVGL v9.0
v1.20.0 1053 g149ae32bf 2024 09 11
4.7.3.2 layer_sys (system layer): The topmost "system-level element"

LVGL internally uses this layer to place elements that "must always be on top"(such as the mouse cursor). Even if layer_top has a pop-up window, layer_sys content will still cover the pop-up.

The demo code is as follows:

# Initialize

import display_driver
import lvgl as lv
import time

lv.init()

# ===================== Step 1: Create two normal screens (for switching test) =====================
# Screen A: add a button; clicking it switches to screen B
scr_a = lv.obj()  # Create normal screen A
btn_a = lv.button(scr_a)
btn_a.set_size(180, 60)
btn_a.set_pos(50, 50)
label_a = lv.label(btn_a)
label_a.set_text("Screen A: Switch to B")

# Screen B: add a button; clicking it switches to screen A
scr_b = lv.obj()  # Create normal screen B
btn_b = lv.button(scr_b)
btn_b.set_size(180, 60)
btn_b.set_pos(50, 150)
label_b = lv.label(btn_b)
label_b.set_text("Screen B: Switch to A")

# Bind the screen switching event
def switch_to_b(e):
    lv.screen_load(scr_b)
btn_a.add_event_cb(switch_to_b, lv.EVENT.CLICKED, None)

def switch_to_a(e):
    lv.screen_load(scr_a)
btn_b.add_event_cb(switch_to_a, lv.EVENT.CLICKED, None)

# ===================== Step 2: Create a global modal popup with layer_top =====================
# 1. Get the display's top layer (global layer, shared by all screens)
top_layer = lv.layer_top()

# 2. Add a "click absorb" flag to top_layer → implements modal behavior (buttons below cannot be clicked)
# Principle: when the user clicks the screen, the click event is received by top_layer, and widgets on the underlying screen do not get the click event
top_layer.add_flag(lv.obj.FLAG.CLICKABLE)

# 3. Create the popup on top_layer (globally visible, stays regardless of which screen is shown)
popup = lv.obj(top_layer)  # The parent object is top_layer, not a normal screen!
popup.set_size(300, 200)   # Popup size
popup.center()             # Popup centered
# Set popup style: white background, gray border, rounded corners
popup.set_style_bg_color(lv.color_hex(0xFFFFFF), 0)    # White background
popup.set_style_border_color(lv.color_hex(0xCCCCCC), 0)# Gray border
popup.set_style_border_width(2, 0)                     # Border width 2px
popup.set_style_radius(10, 0)                          # Corner radius 10px

# 4. Add text + close button to the popup
popup_label = lv.label(popup)
popup_label.set_text("Global Modal Popup\n→ Persists across screen switches\n→ Blocks clicks on underlying elements")
popup_label.center()

# Add close button: clicking it removes the modal and closes the popup
close_btn = lv.button(popup)
close_btn.set_size(120, 30)
close_btn.align(lv.ALIGN.BOTTOM_MID, 0, -10)  # Popup bottom center
close_label = lv.label(close_btn)
close_label.set_text("Close Popup")

# Event to close the popup: remove click absorption + delete the popup
def close_popup(e):
    top_layer.remove_flag(lv.obj.FLAG.CLICKABLE)  # Cancel click absorption
    popup.delete()  # Delete the popup
close_btn.add_event_cb(close_popup, lv.EVENT.CLICKED, None)

# ===================== Step 3: Load the initial screen and run the test =====================
lv.screen_load(scr_a)  # Load screen A first

# Get the system layer (topmost layer)
sys_layer = lv.layer_sys()

# 2. Create a small circle (simulates a mouse cursor)
cursor = lv.obj(sys_layer)
cursor.set_size(20, 20)       # Cursor size 20x20
cursor.set_style_bg_color(lv.color_hex(0xFF0000), 0)  # Red background
cursor.set_style_radius(10, 0)                        # Circle (radius = size/2)
04 Quick Start Case - Layout and Space Management (Based on Web Simulator and LVGL v9.0

After running, you can see the following:

As we run the command to adjust the ball position in the REPL, the red circular cursor will pass through the pop-up window of layer_top and always stay on top (the cursor remains visible even when blocked by the pop-up).

The summary is as follows:

4.7.4 layer_bottom (bottom layer): Global background image

Set the "background for all screen shares", such as the global background image of an APP, so that the background remains unchanged no matter which page (screen) you switch to (provided that the screen background is semi-transparent).

In the following code, we set:

# Initialize

import display_driver
import lvgl as lv
import time

lv.init()

# ===================== Step 1: Create the global background for layer_bottom =====================
# Get the bottom layer
bottom_layer = lv.layer_bottom()

# Global background: dark blue (#1A237E), fully opaque (to highlight the global background)
bg_rect = lv.obj(bottom_layer)
bg_rect.set_size(lv.pct(80), lv.pct(80))  # Fill the entire screen
bg_rect.set_style_bg_color(lv.color_hex(0x1A237E), 0)  # Dark blue (high contrast)
bg_rect.set_style_bg_opa(255, 0)  # Background opaque

# ===================== Step 2: Create two normal screens (semi-transparent background) =====================
# Screen A: semi-transparent background (so the light cyan of the bottom layer shows through)
scr_a = lv.obj()
scr_a.set_style_bg_opa(64, 0)  # Opacity 64 (25%), more transparent
scr_a.set_style_bg_color(lv.color_hex(0xF5F5F5), 0)  # Light gray
btn_a = lv.button(scr_a)
btn_a.set_pos(50, 50)
btn_a.set_size(180, 60)
label_a = lv.label(btn_a)
label_a.set_text("Screen A: Switch to B")

# Screen B: semi-transparent background as well
scr_b = lv.obj()
scr_b.set_style_bg_opa(64, 0)
scr_b.set_style_bg_color(lv.color_hex(0xF5F5F5), 0)
btn_b = lv.button(scr_b)
btn_b.set_pos(50, 150)
btn_b.set_size(180, 60)
label_b = lv.label(btn_b)
label_b.set_text("Screen B: Switch to A")

# Bind the switch event
def switch_to_b(e):
    lv.screen_load(scr_b)
btn_a.add_event_cb(switch_to_b, lv.EVENT.CLICKED, None)

def switch_to_a(e):
    lv.screen_load(scr_a)
btn_b.add_event_cb(switch_to_a, lv.EVENT.CLICKED, None)

# ===================== Step 3: Test the result =====================
lv.screen_load(scr_a)
04 Quick Start Case - Layout and Space Management (Based on Web Simulator and LVGL v9.0
04 Quick Start Case - Layout and Space Management (Based on Web Simulator and LVGL v9.0
04 Quick Start Case - Layout and Space Management (Based on Web Simulator and LVGL v9.0

It can be seen that when switching between screen A and screen B, the dark blue global background remains unchanged all the time, while the light gray screen background changes accordingly with the switching.

Version Record

Version Number

Modifier

Time

Content

v1.0

Li Zisheng

2026/03/24

Initialize the document.

v1.1

Li Zisheng

2026/03/24

Add layer management articles.