在TStringGrid上设置所选行的背景色 [英] Setting background color of selected row on TStringGrid
问题描述
我有一个TStringGrid,其中所选行(最大1,没有多选)应该始终具有不同的背景colo(u)r。
I have a TStringGrid where the selected row (max 1, no multi-select) should always have a different background colo(u)r.
我设置了DefaultDrawing属性设置为false,并提供OnDrawCell事件的方法,如下所示-但它不起作用。我什至无法确切描述它是如何工作的;我想如果可以的话,我已经解决了这个问题。只需说,不是完整的行都具有相同的背景色,而是杂烩。多行具有一些选定颜色的单元格,而并非选定行的所有单元格都具有选定颜色。
I set the DefaultDrawing property to false, and provide a method for the OnDrawCell event, shown below - but it is not working. I can't even describe exactly how it is not working; I supect that if I could I would already have solved the problem. Suffice it to say that instead of having complete rows all with the same background colour it is a mish-mash. Muliple rows have some cells of the "Selected" colour and not all cells of the cselected row have the selected colour.
请注意,我将单元格的行与strnggrid的行进行了比较;由于仅选中了所选行的单元格,因此我无法检查所选单元格的状态。
Note that I compare the cell's row with the strnggrid's row; I can't check the cell state for selected since only cell of the selected row is selected.
procedure TForm1.DatabaseNamesStringGridDrawCell(Sender: TObject;
ACol, ARow: Integer;
Rect: TRect;
State: TGridDrawState);
var cellText :String;
begin
if gdFixed in State then
DatabaseNamesStringGrid.Canvas.Brush.Color := clBtnFace
else
if ARow = DatabaseNamesStringGrid.Row then
DatabaseNamesStringGrid.Canvas.Brush.Color := clAqua
else
DatabaseNamesStringGrid.Canvas.Brush.Color := clWhite;
DatabaseNamesStringGrid.Canvas.FillRect(Rect);
cellText := DatabaseNamesStringGrid.Cells[ACol, ARow];
DatabaseNamesStringGrid.Canvas.TextOut(Rect.Left + 2, Rect.Top + 2, cellText);
end;
推荐答案
如果要绘制选定的行或单元格使用不同的颜色,您必须检查状态
变量中的 gdSelected
值。
if you are trying of paint the selected row or cell with a different color you must check for the gdSelected
value in the state
var.
procedure TForm1.DatabaseNamesStringGridDrawCell(Sender: TObject;
ACol, ARow: Integer;
Rect: TRect;
State: TGridDrawState);
var
AGrid : TStringGrid;
begin
AGrid:=TStringGrid(Sender);
if gdFixed in State then //if is fixed use the clBtnFace color
AGrid.Canvas.Brush.Color := clBtnFace
else
if gdSelected in State then //if is selected use the clAqua color
AGrid.Canvas.Brush.Color := clAqua
else
AGrid.Canvas.Brush.Color := clWindow;
AGrid.Canvas.FillRect(Rect);
AGrid.Canvas.TextOut(Rect.Left + 2, Rect.Top + 2, AGrid.Cells[ACol, ARow]);
end;
这篇关于在TStringGrid上设置所选行的背景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!