在 LVGL(Light and Versatile Graphics Library)中,lv_table
是一个用于显示二维表格数据的控件,适用于显示简易的表格、列表、配置项等,类似于一个轻量级的 Excel 表格。
lv_table
是什么?lv_table
是一个可以显示行列形式文本数据的控件,支持:
lv_obj_t * table = lv_table_create(parent);
lv_table_set_cell_value(table, row, col, "内容");
const char * value = lv_table_get_cell_value(table, row, col);
lv_table_set_row_cnt(table, 5);
lv_table_set_col_cnt(table, 3);
lv_table_set_cell_align(table, row, col, LV_TEXT_ALIGN_CENTER);
// 设置固定列宽
lv_obj_set_style_width(table, 100, 0); // 所有列宽
// 设置样式控制行高
lv_obj_set_style_pad_row(table, 8, 0);
lv_obj_t * table = lv_table_create(lv_scr_act());
lv_obj_set_size(table, 200, 150);
lv_obj_center(table);
// 设置行列数
lv_table_set_row_cnt(table, 4);
lv_table_set_col_cnt(table, 3);
// 设置表格内容
lv_table_set_cell_value(table, 0, 0, "ID");
lv_table_set_cell_value(table, 0, 1, "Name");
lv_table_set_cell_value(table, 0, 2, "Score");
lv_table_set_cell_value(table, 1, 0, "1");
lv_table_set_cell_value(table, 1, 1, "Alice");
lv_table_set_cell_value(table, 1, 2, "92");
lv_table_set_cell_value(table, 2, 0, "2");
lv_table_set_cell_value(table, 2, 1, "Bob");
lv_table_set_cell_value(table, 2, 2, "85");
你可以给 lv_table
添加边框、背景色、字体等样式。例如:
lv_obj_set_style_border_width(table, 1, 0);
lv_obj_set_style_border_color(table, lv_color_black(), 0);
lv_obj_set_style_text_font(table, &lv_font_montserrat_14, 0);
也可以对不同的单元格设置不同样式(如选中样式、标题样式等),可以通过 lv_table_set_cell_type()
实现。
支持点击事件,可以识别点击了哪一行哪一列:
lv_obj_add_event_cb(table, table_event_cb, LV_EVENT_CLICKED, NULL);
void table_event_cb(lv_event_t * e) {
lv_obj_t * table = lv_event_get_target(e);
uint16_t row = lv_table_get_selected_row(table);
LV_LOG_USER("点击了第 %d 行", row);
}
用途 | 示例 |
---|---|
设置列表 | 参数项:名称 + 值 |
显示数据表格 | ID + 姓名 + 成绩 |
选项菜单 | 多行按钮表 |
信息日志 | 时间戳 + 信息 |
注意点 | 说明 |
---|---|
默认无滚动条 | 内容超出不会自动显示,需要设置父容器带滚动 |
列宽/行高 | 需要自行设置或通过样式调整,否则可能排版拥挤 |
最大支持64行 | 默认最大行为 64(可通过 LV_TABLE_CELL_CNT 宏修改) |
每个单元格是一个字符串 | 不支持富文本或图像嵌入 |
如果你想让表格支持更复杂的交互,比如点击后跳转编辑页、多选行、动态样式高亮等,可以考虑:
lv_btn
, lv_dropdown