I've got a TWebComboBox
component on my form and every item in it has a different text size.
Currently what I've done as a temporary solution is to just manually check the selected item's text content and then manually set the Width
for the TWebComboBox
:
procedure TForm_Leaderboards.cbGameChange(Sender: TObject);
var
cb: TWebComboBox;
begin
cb := TWebComboBox(Sender);
if (cb.Text = 'Portal') then cb.Width := 95;
if (cb.Text = 'Portal 2') then cb.Width := 105;
if (cb.Text = 'Portal Stories: Mel') then cb.Width := 200;
// ... Lots more If Statements for other Texts
end;
This works, but it's tedious to do this and obviously super hardcoded.
How can I make this dynamic so that the Width
is automatically set to match the required width for the selected item's text?
I managed to get it working, but it's a bit hacky:
procedure TForm_Leaderboards.cbGameChange(Sender: TObject);
var
cb, TempCB: TWebComboBox;
begin
cb := TWebComboBox(Sender);
TempCB := TWebComboBox.Create(nil);
try
TempCB.WidthStyle := ssAuto;
TempCB.Font := cb.Font;
TempCB.Items.Text := cb.Text;
TempCB.Parent := Self;
cb.Width := TempCB.Width; // Sets correct width
finally
TempCB.Free;
end;
end;
Explanation:
Turns out that if you set the WidthStyle
to ssAuto
, then the TWebComboBox
will automatically resize itself to the Width
of the longest item in Items.Text
.
So we can abuse this by creating a new temporary TWebComboBox
and have only one item in the Items.Text
(The selected item), then the TWebComboBox
will automatically resize itself to the Width
for that one item, and then we can get that Width
and apply it to the correct TWebComboBox
.