How to change color of selected text in label?

Description

How can I change the color of selected text in a label?

What do you want to achieve?

When text in a label is selected, I want the background to be black and the text color to be white. I’m using the Mono theme, so it shows selections as black text on a cyan background.

What have you tried so far?

I’ve looked at the label’s style options and it only offers the MAIN style. lv_style_t has a sel_color field to let me change the background of selected text, but I see no way to change the selected text’s foreground color.

Thank you,
Bob

There is no way to do it easily in 6.1, from what I can tell. When I implemented text selection I didn’t think of the fact that some displays would need foreground color inversion.

However, it wouldn’t be too complex to add for 7.0. I’ll see what I can do.

I agree. I think it should be only a new property to set the text color too, besides the background color.

1 Like

Is this new property added to 9.3?

You can do it like this in v9.4


  lv_obj_t * label = lv_label_create(lv_screen_active());
  lv_label_set_text(label, "Hello world!");
  lv_label_set_text_selection_start(label, 2);
  lv_label_set_text_selection_end(label, 5);
  lv_obj_center(label);
  lv_obj_set_style_text_color(label, lv_color_hex(0xff0000), LV_PART_SELECTED);
  lv_obj_set_style_bg_color(label, lv_color_hex(0x00ff00), LV_PART_SELECTED);

image

1 Like

If you’re looking to change colors within a single label, the easiest way is to enable recoloring. You just need to set lv_label_set_recolor(label, true); and then you can use the hex tags directly in your string like: lv_label_set_text(label, “Normal #ff0000 Selected# Normal”);. It’s much lighter than trying to manage the selection state manually for a static label!