How to properly set and show properties for Custom Components

What I’m trying to do:
Understand the proper way to set custom properties and display them for custom components.

Currently I have a simple custom component creativly named “LabelTextbox”, which contains a ColumnPanel, inside, are a Label and a Text box.

On the column_panel_show event:

  def column_panel_show(self, **event_args):
    self.label_title.text = self.title

I feel like I’m missing something here… even though I get the functionality I want.

Clone link:
https://anvil.works/build#clone:2MS3OL6MMX5QG3ZC=OERB5BGFJOOQYBLVWTMZGJ2X

I think the Docs explain this pretty well: Anvil Docs | Custom Components

Implementing it that way will initialize your custom component as desired, but you will not be able to update the title after it’s shown. To get code like this (label_textbox_1.title = "Changed Title") to work as expected, you need to follow the instructions in the “Running code when properties are updated” subsection of the docs.

Can you be more specific about your concern or what you’re unclear about?

1 Like

Yes, I think the updating of values was what I was missing.

Hummm… I must be missing something, I updated the code to match the docs, but I don’t have a good understanding (obviously).

Here’s the updated code for the custom component:

from ._anvil_designer import LabelTextBoxTemplate
from anvil import *

class LabelTextBox(LabelTextBoxTemplate):
  def __init__(self, **properties):
    self.init_components(**properties)
    
  @property
  def my_prop(self):
      return self._title

  @my_prop.setter
  def my_prop(self, value):
      self.label_title.text = value
      self._title = value

And here’s how I’m setting the prop…:

from ._anvil_designer import StartupTemplate
from anvil import *

class Startup(StartupTemplate):
  def __init__(self, **properties):
    self.labeltb._title = 'Hello world'
    self.init_components(**properties)

Replying to myself, this video helped me understand the concept better. Here’s the final code:

Here’s the updated code for the custom component:

from ._anvil_designer import LabelTextBoxTemplate
from anvil import *

class LabelTextBox(LabelTextBoxTemplate):
  def __init__(self, **properties):
    self.init_components(**properties)
    
  @property
  def title(self):
      return self._title

  @title.setter
  def title(self, value):
      self.label_title.text = value
      self._title = value

Calling code…:

from ._anvil_designer import StartupTemplate
from anvil import *

class Startup(StartupTemplate):
  def __init__(self, **properties):
    self.labeltb.title = 'hello world!'
    self.init_components(**properties)
2 Likes