如何解决TListBox.ScrollWidth使用什么值? [英] How can I work out what values to use for TListBox.ScrollWidth?

查看:210
本文介绍了如何解决TListBox.ScrollWidth使用什么值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力解决如何在 TListBox 上设置 ScrollWidth 来控制水平滚动条。这是我的第一个尝试:

I'm trying to work out how to set ScrollWidth on a TListBox to control the horizontal scroll bar. Here's my first attempt:

program ListBoxSizing;

uses
  Math, Forms, StdCtrls;

var
  Form: TForm;
  ListBox: TListBox;

procedure BuildForm;
begin
  //Form.Font.Size := 9;
  Form.ClientWidth := 200;
  Form.ClientHeight := 100;
  ListBox := TListBox.Create(Form);
  ListBox.Parent := Form;
  ListBox.SetBounds(0, 0, Form.ClientWidth, Form.ClientHeight);
  ListBox.Items.Add('ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ');
end;

procedure SetScrollWidth;
var
  i, MaxWidth: Integer;
begin
  MaxWidth := -1;
  for i := 0 to ListBox.Items.Count-1 do
    MaxWidth := Max(MaxWidth, ListBox.Canvas.TextWidth(ListBox.Items[i]));
  if MaxWidth<>-1 then
    ListBox.ScrollWidth := MaxWidth;
end;

begin
  Application.MainFormOnTaskbar := True;
  Application.CreateForm(TForm, Form);
  BuildForm;
  SetScrollWidth;
  Application.Run;
end.

这是结果看起来与水平滚动条移动尽可能的最右边:

This is how the result looks with the horizontal scroll bar moved as far right as possible:

注意最后一个字符的最后一部分是如何被切断的。

Notice how the last part of the final character has been chopped off.

现在,如果我们取消注释更改表单字体大小的行,它看起来像这样:

Now, if we uncomment the line that changes the form's font size, it looks like this:

现在,似乎在后续调用 TextWidth

Now, it seems that the change to font size hasn't been accounted for in the subsequent calls to TextWidth.

所以,我的问题是,我需要使用什么代码来准确地设置 ScrollWidth 基于列表框的当前内容。

So, my question is, what code do I need to use to be able to set ScrollWidth accurately, based on the current contents of the list box.

推荐答案

procedure SetScrollWidth;
var
  I, MaxWidth: Integer;
begin
  MaxWidth := -1;
  // assign control's font to canvas
  ListBox.Canvas.Font := ListBox.Font;
  for I := 0 to ListBox.Items.Count - 1 do
    MaxWidth := Max(MaxWidth, ListBox.Canvas.TextWidth(ListBox.Items[I]));
  // consider non-client area
  if MaxWidth <> -1 then
    ListBox.ScrollWidth := MaxWidth + ListBox.Width - ListBox.ClientWidth;
end;

这篇关于如何解决TListBox.ScrollWidth使用什么值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆