Labs / LVGL / 02 LVGL Basic Knowledge and Concepts

I. Core Objects and Interface Layout: The Skeleton System of GUI

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

Contents

An Object is a unified abstraction of all UI elements in LVGL and serves as the fundamental building block for constructing GUIs; together with the mechanisms of layout, scrolling and layers, it collectively defines the structure and spatial relationships of the interface.

1.1 Object Foundation (Objects)

4 1 0 2 3

1.1.1 Core Definition of an Object

All UI elements in LVGL (such as Button, Label, Image, Slider, Chart) are referred to as Objects, and are also commonly translated as "Widgets".

1.1.2 Attributes of the Object: Basic + Exclusive

The attributes of an object are divided into "basic attributes shared by all objects" and "exclusive attributes of specific controls", which correspond to two distinct sets of API designs.

1.1.2.1 Basic Attributes
Core Basic PropertiesDescription
PositionObject coordinates within the parent container (relative position)
SizeObject width and height
ParentParent object (container)
StylesStyle (visual appearance)
Event handlersEvent handler (interaction response)
1.1.2.2 Exclusive Attributes

Different types of controls have their own specific attributes, for example:

1.1.3 Working Mechanism of Objects

1.1.3.1 Parent-Child Structure

The core rules are as follows:

The core features are as follows:

1.1.3.2 Creation and Destruction of Objects

LVGL supports dynamically creating and deleting objects at runtime, and only "currently existing objects" occupy RAM, which is a core design for memory saving on embedded devices.

1.1.4 Screens: Special Top-Level Objects

A screen is a top-level object with no parent object. Each display always has an "active screen", which serves as the ultimate container for all UI elements.

We can create, activate and load, and bring up animated loading screens.

1.1.5 Parts: The "stylable components" of an object

Parts are "sub-modules" split by LVGL for widgets, similar to "pseudo-elements" in CSS, designed to enable fine-grained customization of the visual style of widgets.

LVGL has the following built-in general widgets (all controls are built by combining these components):

Part EnumerationPurposeExample scenario
LV_PART_MAINMain body of the widget (background rectangle)Button background, slider base
LV_PART_SCROLLBARScrollbarScrollbar of a list or text box
LV_PART_INDICATORIndicatorSlider progress bar, switch toggle block, checkbox tick box
LV_PART_KNOBDraggable handleSlider knob, volume control handle
LV_PART_SELECTEDSelected state markerSelected list item, selected option in a dropdown
LV_PART_ITEMSRepeated child elementsTable cells, list items
LV_PART_CURSORCursor / markerText box input cursor, chart value cursor

Different styles can be set for different parts of a control via components, for example:

1.1.6 States: The "interaction state identifier" of an object

An object can be in multiple "states" at the same time. LVGL automatically switches states based on user interactions, and also supports manual state modification. States serve as the core basis for style switching in different interaction scenarios.

The predefined states are as follows:

State EnumerationMeaningTrigger Scenarios
LV_STATE_DEFAULTDefault stateInitial state when the widget has not been operated
LV_STATE_CHECKEDChecked / toggled stateSwitch turned on, checkbox checked
LV_STATE_FOCUSEDFocused stateSelected by keyboard / encoder, touched / clicked by mouse
LV_STATE_PRESSEDPressed stateTouch / mouse is held on the widget without release
LV_STATE_DISABLEDDisabled stateWidget is not interactive (grayed out)
LV_STATE_SCROLLEDScrolled stateList / text box is being scrolled
LV_STATE_USER_1~4Custom stateBusiness extension (such as "Favorited", "Expired")

LVGL automatically updates its status based on user operations, for example:

We can also manually set / clear states via code (supports bitwise OR of multiple states |).

1.1.7 Snapshot: The "Screenshot Function" of Objects

It can generate a snapshot image (e. g. PNG/BMP) containing the object and all its sub-objects, which is commonly used for:

1.2 Layout and Space Management

The positioning, sizing and layout design of LVGL draw heavily on the core logic of CSS (with lightweight adaptations for embedded scenarios), and serve as the core capability for controlling the arrangement of UI elements.

1.2.1 Core Overview

The position/size/layout system of LVGL has the following core features (a CSS subset adapted to embedded resource constraints):

1.2.2 Core Units

LVGL supports three units, which are the basis for setting positions and dimensions, and can be passed directly in mpy via the corresponding method:

Unit TypeDescriptionExample (mpy)
PixelAbsolute pixel value; an integer represents pixels by defaultobj.set_x(10) → set the object's x coordinate to 10 pixels
PercentageRelative value (based on the parent object's content area size); requires conversion with lv.pct()obj.set_width(lv.pct(50)) → width is 50% of the parent object's content area
Content-adaptive (LV_SIZE_CONTENT)Special constant; the object size automatically fits all child elements (similar to CSS auto)obj.set_width(lv.SIZE_CONTENT) → width adapts to child elements

1.2.3 Boxing Model

LVGL follows the CSS border-box model, where an object's "size box" consists of 4 components (which determine the calculation logic for position and size):

Core Enumeration (mpy)Meaning
lv.ALIGN_TOP_LEFTTop-left corner of the parent object
lv.ALIGN_TOP_MIDTop center of the parent object
lv.ALIGN_TOP_RIGHTTop-right corner of the parent object
lv.ALIGN_BOTTOM_LEFTBottom-left corner of the parent object
lv.ALIGN_BOTTOM_MIDBottom center of the parent object
lv.ALIGN_BOTTOM_RIGHTBottom-right corner of the parent object
lv.ALIGN_LEFT_MIDLeft center of the parent object
lv.ALIGN_RIGHT_MIDRight center of the parent object
lv.ALIGN_CENTERExact center of the parent object

The key rules are as follows:

1.2.4 Important Notes

1.2.5 Location Settings

1.2.5.1 Location Settings

In mpy, settings can be configured directly via a simplified API, with the coordinate origin set at the top-left corner of the parent object's content area.

1.2.5.2 Alignment

Flexible alignment is achieved by modifying the "alignment origin", the core of which lies in the lv.ALIGN_XXX enumeration, which can be used directly in mpy.

We can align it to the parent object:

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)

You can also align it to any reference object:

Implemented via align_to, which supports the "external alignment" enumeration (LV_ALIGN_OUT_XXX). mpy example:

# Align the label to the top center of btn, offset upward by 10 pixels
label.align_to(btn, lv.ALIGN_OUT_TOP_MID, 0, -10)

External Alignment Core Enumeration (mpy):

1.2.6 Dimension Setting

1.2.6.1 Location Settings

In mpy, by simplifying API settings, it supports pixels, percentages, and LV_SIZE_CONTENT:

# Set width/height separately
obj.set_width(200)  # Width 200 pixels
obj.set_height(100) # Height 100 pixels

# Set width and height at once
obj.set_size(200, 100)

# Percentage example: height is 100% of the parent's content area (fills the parent's height)
obj.set_height(lv.pct(100))

# Content-adaptive example: width fits all child elements
obj.set_width(lv.SIZE_CONTENT)
1.2.6.2 Content Area Dimensions

Directly set the width and height of the "content area"(the actual width and height of the element = width and height of the content area + border + padding):

# Set content area width to 50 pixels (actual width = left padding + 50 + right padding)
obj.set_content_width(50)
# Set content area height to 30 pixels
obj.set_content_height(30)

# Get size (mpy)
w = obj.get_width()          # Get bounding box width
content_w = obj.get_content_width()  # Get content area width
1.2.6.3 Minimum / Maximum Dimensions

Set size extremities via style configuration to solve the issue of "percentage / Self-Adaptation size exceeding expectations", an mpy example is as follows:

# 1. Create a style and set max-height
style = lv.style_t()
style.init()
style.set_max_height(200)  # Maximum height 200 pixels (lv.pct(50) is also supported)

# 2. Add the style to the object to limit its height
obj.set_height(lv.pct(100))  # Originally fills the parent's height
obj.add_style(style, lv.PART_MAIN)  # Limit height to no more than 200 pixels

1.2.7 Style Control Position / Size

The simplified API for position and dimensions is essentially "syntactic sugar for styling", and directly using style settings offers the following advantages:

mpy example (the width increases 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

# 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)
I. Core Objects and Interface Layout: The Skeleton System of GUI
v1.20.0

1.2.8 Translation

Relative offset based on the object's current position, which solves the problem that "objects with different initial positions offset by the same distance during interaction"(e. g., moving up when a button is pressed), 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)
I. Core Objects and Interface Layout: The Skeleton System of GUI
I. Core Objects and Interface Layout: The Skeleton System of GUI

In addition, there are two key features:

1.2.9 Transformation

"Visual scaling" based on the object's current size only changes the display effect, without affecting the actual size (the layout, scroll bars, and content Self-Adaptation will not perceive it). mpy example (enlarge 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)
I. Core Objects and Interface Layout: The Skeleton System of GUI
I. Core Objects and Interface Layout: The Skeleton System of GUI
Layout TypeMain PurposeKey Features
Flexbox (lv.LAYOUT_FLEX)Arranges child objects in rows / columnsSupports wrapping, adaptive expansion, alignment, and spacing adjustment
Grid (lv.LAYOUT_GRID)Arranges child objects in a two-dimensional gridFixed rows and columns, cell merging, adaptive proportions

1.2.10 Layout System (Layout)

The layout automatically calculates the position and size of child objects (overriding manually set x/y/width/height), which is enabled via set_layout in mpy:

# Enable Flex layout on the parent container
container = lv.obj(lv.screen_active())
container.set_layout(lv.LAYOUT_FLEX)
1.2.10.1 Built-in Layouts

LVGL has two built-in core layouts (inspired by CSS), which are the most commonly used layout methods in mpy:

Flags (mpy)Purpose
lv.OBJ_FLAG_HIDDENHidden objects are ignored by the layout
lv.OBJ_FLAG_IGNORE_LAYOUTThe object is completely free of layout control (position / size set manually)
lv.OBJ_FLAG_FLOATINGEquivalent to IGNORE_LAYOUT, and is ignored by LV_SIZE_CONTENT

Control the behavior of child objects in the layout via flags, which in mpy are set using add_flag / remove_flag as follows:

Feature NameCore descriptionKey controls (flag / event / API)Additional notes
Scrollability control1. Removing the specified flag disables container scrolling (scroll actions can still be passed to the parent container);
2. Can restrict the container to scroll only in specific directions (/ direction combinations)
1. Disable scrolling: remove LV_OBJ_FLAG_SCROLLABLE;
2. Direction restriction: lv_obj_set_scroll_dir(obj, LV_DIR_...)
Supported directions: LV_DIR_TOP/LEFT/BOTTOM/RIGHT/HOR/VER/ALL, can be combined (e.g. `LV_DIR_TOP、LV_DIR_LEFT`)
Scroll chainWhen a child container reaches its scroll limit, the scroll action is passed up level by level to the parent container (child → parent → grandparent), and the parent scrolls insteadEnable / disable: LV_OBJ_FLAG_SCROLL_CHAIN_HOR (horizontal) / VER (vertical)With the flag off, the scroll action ends at the current container and is no longer passed up
Scroll momentumSimulates physical inertia: after the user releases a swipe, scrolling decelerates slowly, restoring a realistic interaction feelEnable / disable: LV_OBJ_FLAG_SCROLL_MOMENTUM-
Elastic scrollWhen scrolling past the boundary, the content slightly exceeds the edge, then automatically bounces back to a valid position after release, improving the interaction experienceEnable: LV_OBJ_FLAG_SCROLL_ELASTICUnder normal conditions the container cannot scroll beyond its content
SnappingWhen scrolling ends, child objects automatically align to a specified position in the container, making scrolling more orderly (e.g. carousel / list item alignment)1. Child object can snap: LV_OBJ_FLAG_SNAPPABLE;
2. Alignment rule: lv_obj_set_scroll_snap_x/y(obj, LV_SCROLL_SNAP_...) (NONE/START/END/CENTER)
After the scroll is released, the momentum end point is calculated first, then the nearest snap point is found and scrolled to with animation
Scroll oneWhen enabled, each scroll switches only one snappable child object (e.g. a carousel moves one page per swipe)Enable: LV_OBJ_FLAG_SCROLL_ONEPrerequisite: the child objects are snappable, and the container's snap alignment is set to something other than NONE
Scroll on focusWhen focus moves to a child object outside the container's visible area, the container automatically scrolls to bring that object into viewNo specific control flag; a built-in LVGL featureSupports recursive scroll adaptation for nested containers and across tabs (tabview)
Manual scrolling1. Active trigger: scroll by an offset / to specified coordinates;
2. Real-time retrieval: scroll offset coordinates
1. Trigger API: lv_obj_scroll_by/to/to_x/to_y();
2. Coordinate retrieval API: lv_obj_get_scroll_x/y/top/bottom/left/right()
Can be used for saving the scroll position, updating the UI dynamically, etc.
Self size1. Self size is the actual size of the object's content area (as opposed to its displayed size);
2. Scrolling is triggered when self size > displayed size (scrolling is possible even without children)
Custom self size: handle the LV_EVENT_GET_SELF_SIZE eventTypical scenario: table widget (many rows make the self height much larger than the displayed height)

mpy Example:

# Child object ignores the layout; position is set manually
obj.add_flag(lv.OBJ_FLAG_IGNORE_LAYOUT)
obj.set_pos(10, 10)  # Layout will not modify this position
1.2.10.3 Custom Layout

In MPY, custom layouts (for advanced use cases) can be implemented by registering layout callbacks, with the core logic as follows:

1.2.11 Scroll

The scrolling system of LVGL is the core mechanism for implementing interactive browsing when content exceeds the container in embedded GUIs, featuring an intuitive design that aligns with user expectations and supporting a rich set of customization features.

1.2.11.1 Core Principle of Scrolling

The trigger logic of scrolling in LVGL is extremely intuitive:

1.2.11.2 Scrollbar: A Visual Indicator for Scrolling

A scrollbar provides intuitive feedback of the scrolling status, and supports flexible display and style control:

1.2.11.3 Scroll Events: Monitor Scrolling Behavior

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

Core Event

Meaning of Core Events

LV_EVENT_SCROLL_BEGIN

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

LV_EVENT_SCROLL_END

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

LV_EVENT_SCROLL

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

1.2.11.4 Rolling Core Expansion Features

LVGL provides a rich set of scroll enhancement features covering both interactive experience and functional control:

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

1.3 Layer Management (Layers)

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

To be precise:

1

1.3.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)
1 2

1.3.2 Modify Hierarchy: Proactively Adjust the Display Order of Objects

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

1.3.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
Button1 Button2 btn1.move_foreground btn1 btn2

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()
1.3.2.2 Move to the specified index position

Each child object of a parent container has an "index value", which determines the 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
1 2 btn1.get_index btn1.move_to_index
btn1.move_to_index 1 0 button2 btn1
1.3.2.3 Hierarchy Impact of Changing the Parent Object

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

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

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

LVGL provides two globally visible special layers (shared by all screens, not shared across different displays) for each physical display, which are hierarchically higher than all objects on ordinary 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(底层图层)→ 比如全局背景图,在所有屏幕下面
1.3.3.1 layer_top (Top-level Layer): Globally Visible "Floating Window / Modal Pop-up"

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; when "modal mode" is enabled, the underlying content cannot be clicked (for example, a mobile phone pop-up window blocks 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 does not disappear when switching between screens, and will block the interaction of the underlying screen. The underlying buttons 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
I. Core Objects and Interface Layout: The Skeleton System of GUI

It can be seen that:

I. Core Objects and Interface Layout: The Skeleton System of GUI
I. Core Objects and Interface Layout: The Skeleton System of GUI
1.3.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)
I. Core Objects and Interface Layout: The Skeleton System of GUI

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 the top (it remains visible even when blocked by the pop-up window).

The summary is as follows:

1.3.4 layer_bottom (bottom layer): Global background image

Set the "background for all screen sharing", 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)
I. Core Objects and Interface Layout: The Skeleton System of GUI
I. Core Objects and Interface Layout: The Skeleton System of GUI
I. Core Objects and Interface Layout: The Skeleton System of GUI

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

Version Record

Version Number

Modifier

Time

Content

v1.0

Li Zisheng

2026/03/23

Initialize the document.