Search code examples
delphibuttondelphi-2010autosize

Automatically resize a Delphi button


I want to dynamically change the caption on a TButton. The problem is that TButton doesn't resize itself if the caption is too long to fit on the button; so the text bleeds over the edges of the button.

How can I get the button to change size to fit the caption?

Some ideas:

  • Use a different button component that can resize itself. Is there one?
  • Subclass TButton and set AutoSize=True (haven't tried this, don't know if it will work).
  • Calculate the size of the caption in pixels and manually change the width every time I change the caption.

Solution

  • I ended up going with option 3 ("Calculate the size of the caption in pixels and manually change the width every time I change the caption")

    My code looks somthing like this:

    // Called from the form containing the button
    button.Caption := newCaption;
    button.Width := self.Canvas.TextWidth(newCaption);