본문 바로가기

프로그래밍/Delphi

[Delphi]TComboBox내 아이템의 길이에 따라 가변 DropDown 만들기

1. 개요

  TComboBox의 Items에 추가된 항목들의 길이가 들쑥날쑥 할 경우에 현재 선택된 항목의 길이에 맞추어 커팅되지 않은 항목 문자열을 이용해 가변의 드롭다운 리스를 구현

2. 기존 ComboBox처리 내용
    . Property DropDownCount 는 드롭다운될 항목의 갯수를 보여줌(드롭다운 의 높이 결정)
    . Drop-down List의Width는 기본적으로 콤보박스의 넓이와 동일함
    . 만일 항목의 길이가 콤보박스의 wdth보다 길 경우에 자동으로 커팅되어 보여주게 됨
    . 기본적으로 TComboBox는 드롭다운될 항목의 넓이르 지정할 수 있는 방법이 없음

3. 항목의 크기에 맞추어 드롭다운 목록의 넓이를 지정하는 방법
    . TComboBox의 드롭다운 목록의 넓이를 지정할 수 있도록 구현하기 위하여 Windows Message를 이용할 수 있다
    . 이 메시지는 "CB_SETDROPPEDWIDTH" 이며 허용 가능한 최소 넓이를 픽셀로 ComboBox로 보낼 수 있다.
    예) 
      SendMessage(theComboBox.Handle, CB_SETDROPPEDWIDTH, 200, 0);
      // theComboBox의 드롭다운 목록의 최대 넓이를 200 Pixels로 제한 하도록 하는 메시지를 보냄
   
    . ComboBox안의 항목의 길이를 모두 표시해 주기 위해서는 아래와 같은 방법으로 길이를 지정할 수 있음
    . 이 예제는 항목들중 가장 큰 항목의 길이에 맞추도록 함
    . 콤보박스내 항목들이 미리 정의되어 있다면 폼의 OnCreate 이벤트 핸들어에서 "ComboBox_AutoWidth" 프로시저를 호출해 주도록 한다.
    . 만일 콤보박스내의 항목들이 동적으로 추가되거나 삭제 되는 경우라면 ComboBox의 OnDropDown에서 위 프로시저를 호출해 주면 됨
   
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    ComboBox1: TComboBox;
    ComboBox2: TComboBox;
    ComboBox3: TComboBox;
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}



procedure ComboBox_AutoWidth(const theComboBox: TCombobox);
const
  HORIZONTAL_PADDING = 4;
var
  itemsFullWidth: integer;
  idx: integer;
  itemWidth: integer;
begin
  itemsFullWidth := 0;

  // get the max needed with of the items in dropdown state
  for idx := 0 to -1 + theComboBox.Items.Count do
  begin
    itemWidth := theComboBox.Canvas.TextWidth(theComboBox.Items[idx]);
    Inc(itemWidth, 2 * HORIZONTAL_PADDING);
    if (itemWidth > itemsFullWidth) then itemsFullWidth := itemWidth;
  end;

  // set the width of drop down if needed
  if (itemsFullWidth > theComboBox.Width) then
  begin
    //check if there would be a scroll bar
    if theComboBox.DropDownCount < theComboBox.Items.Count then
      itemsFullWidth := itemsFullWidth + GetSystemMetrics(SM_CXVSCROLL);

    SendMessage(theComboBox.Handle, CB_SETDROPPEDWIDTH, itemsFullWidth, 0);
  end;
end;


procedure TForm1.FormCreate(Sender: TObject);
begin
  ComboBox_AutoWidth(ComboBox2);
  ComboBox_AutoWidth(ComboBox3);
end;

end.


콤보박스에는 다음 목록을 넣어보자
-----------------
현장르포 동행
아름다운 사람들
걸어서 세계속으로 가보세요...
KBS 오늘의 경제
-----------------

> 드롭다운에서 항목들은 오른쪽을 기준으로 커팅 됨


4. 콤보박스의 자동 넓이 구현
    .