How to get the instance id in callbacks for components

What do you want to achieve?

I do have a component which has a button as one of its children. The button has an event CLICKED that triggers a function callback which is correctly exported in ui_events.c. I have 8 instances of this component, layed out in a “grid” fashion, like an array counting instance variable trailing number 1-8 from left to right. In the event callback I’d like to have a reference on which instance id the event has occurred (best would be the trailing number of the instance variable, as this indicated the right order automatically in my layout casem or by using user_data payload).

What have you tried so far?

I studied the ui_comp.c code which uses callback user data to hold a reference to the component - but this is the wrong way around for me. I also tried to set a user_data on my button, hoping I can retrieve that over the event e argument but it gets me a reference of something else (the component?). There must be a way to nicely retrieve the instance id either as a user_data payload or by the framework something like the id of the array holding all instance vars.

I need an example code which shows how to achieve this, in either way:

  1. using user_data which then would hold a primitive integer as an index.
  2. using a parent of parent traversal until I reached my component (which is a pane) which I can then compare because my main program has an array of the component instance var.
  3. any other trick that I missed to see. I really think the developers of the component feature has thought about this usecase, otherwise the callback on component definition level wouldn’t make sense, as the event always happens on an instance during runtime.

Screenshot or video

Others

  • SquareLine Studio version:
  • Operating system:
  • Target hardware:

Can lv_obj_get_child_id(btn) work for you? It returns the index of a child. It gives 0 for the firstly created child of a parent, 1 for the second , etc.

many thanks this led me to the right solution. I was not aware that components is “just” another parent-child thing on lvgl because of additional code of the SLS on comp.c I was looking there.
In my case I have a deeper hierarchy so I had to traverse up:

lv_obj_t * obj = lv_event_get_target(e);
obj = lv_obj_get_parent(obj);
uint8_t ch = (uint8_t)lv_obj_get_child_id(obj);
Serial.printf("edit clicked on channel %d", ch);

this should cover my concern. Maybe a hint in the documentation or a helper functions in comp.c would have been helpful.

BTW: lv_obj_get_child_id(btn) is depricated. lv_obj_get_index(obj) should be used instead.

I’m thinking about a proper API for this.

Oh, true :slight_smile: