How to right align text on a label

I’m trying to write software for a digital dashboard with a digital mph readout.

At 0 I need the digit to be align right and at 10 move to one place left.
I’ve tried lv_label_set_align(label_mph, LV_LABEL_ALIGN_RIGHT) but it has no effect.

My code is:
void draw_mph(void)
static lv_style_t style_mph;

      lv_style_set_text_color(&style_mph, LV_STATE_DEFAULT, LV_COLOR_WHITE);
      lv_style_set_text_font(&style_mph, LV_STATE_DEFAULT, &arial_100);
      label_mph = lv_label_create(lv_disp_get_scr_act(NULL), NULL);
      lv_obj_set_width(label_mph, 150);
      lv_label_set_align(label_mph, LV_LABEL_ALIGN_RIGHT); 

      lv_obj_add_style(label_mph, LV_OBJ_PART_MAIN,&style_mph);
      lv_obj_set_pos(label_mph, 305, 15);
      lv_label_set_text(label_mph, "0");

      static lv_style_t style_mph_text;
      lv_style_set_text_color(&style_mph_text, LV_STATE_DEFAULT, LV_COLOR_WHITE);
      lv_style_set_text_font(&style_mph_text, LV_STATE_DEFAULT, &lv_font_montserrat_16);
      lv_obj_t * label_mph_lb = lv_label_create(lv_disp_get_scr_act(NULL), NULL);
      lv_obj_set_pos(label_mph_lb, 420, 100);
      lv_obj_add_style(label_mph_lb, LV_OBJ_PART_MAIN,&style_mph_text);

      lv_label_set_text(label_mph_lb, "mph");

I want the 0 to be above the text “mph” and at 10 move to the left.

So how do I right align the text ?

The problem is that by default labels size themselves automatically and thus your lv_obj_set_width call isn’t working the way you’d expect. You have to change the long mode of the label to fix this.

lv_label_set_long_mode(label_mph, LV_LABEL_LONG_BREAK);
lv_obj_set_width(label_mph, 150);
lv_obj_align(label_mph, NULL, LV_ALIGN_IN_TOP_RIGHT, 0, 0);

The above code should do what you want.

1 Like

Wow that worked.

Thank you very much.