Консультация № 40163
13.04.2006, 09:40
0.00 руб.
0 3 3
Здравствуйте, эксперты!
Подскажите, можно ли организовать вывод записей в ListBox разными цветами. Меняю ListBox1.Font.Color для определённых записей. Выводится всё одним цветом.

Обсуждение

Неизвестный
13.04.2006, 10:00
общий
это ответ
Здравствуйте, Ramil!
Поставьте для ListBox: Style = lbOwnerDrawFixed и перерисовывайте каждую строку по своему усмотрению через событие OnDrawItem. Вот самый простой вариант:
<p align=‘left‘ style=‘color: #0066CC; border: #909090 1px dotted; background-color: #FAFCFE; padding:5px; border-left: #06600 3px solid; width: 97%; white-space:pre;‘><font color=#FF6600><b>procedure </b></font>TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
<font color=#CC3300><b>begin</b></font>
ListBox1.Canvas.Font.Color<font color=#0000FF>:=</font>RGB(Index*Index,Index*Index,Index*Index*Index);
ListBox1.Canvas.TextOut(Rect.Left+1,Rect.Top+1,ListBox1.Items[Index]);
<font color=#CC3300><b>end</b></font>;</p>
Рисование как на обычной канве (Canvas).
Неизвестный
13.04.2006, 13:06
общий
это ответ
Здравствуйте, Ramil!

Ответ такой:

Изменяем сначало свойтво Style объекта ListBox примерно так:
ListBox1.Style:=lbOwnerDrawVariable;

А затем пишем такой обработчик на событие OnDrawItem:

procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
begin
with (Control as TListBox).Canvas do
begin
case Index mod 3 of
0: Font.Color := clBlue;
1: Font.Color := clRed;
2: Font.Color := clGreen;
end;
FillRect(Rect);
TextOut(Rect.Left, Rect.Top, (Control as TListBox).Items[Index]);
end;
end;
В данном примере строки перекрашиваются с периодим 3. (Blue,Red,Green,Blue,Red,Green,..........)
Неизвестный
13.04.2006, 14:36
общий
это ответ
Здравствуйте, Ramil!
Установите свойство ListBox1.Style равным lbOwnerDrawFixed, а в обработчик OnDrawItem напишите код, приведенный в приложении.

Приложение:
procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState);begin with (Control as TListBox).Canvas do begin case Index of 0: begin Font.Color := clBlue; Brush.Color := clYellow; end; 1: begin Font.Color := clRed; Brush.Color := clLime; end; 2: begin Font.Color := clGreen; Brush.Color := clFuchsia; end; end; FillRect(Rect); TextOut(Rect.Left, Rect.Top, (Control as TListBox).Items[Index]); end;end;
Форма ответа