我有一个TStringGrid,其中所选行(最多1,没有多选)应始终具有不同的背景颜色(u)r。
我将DefaultDrawing属性设置为false,并为OnDrawCell事件提供了一种方法,如下所示 - 但它不起作用。我甚至无法准确描述它是如何不工作的;我怀疑如果可以,我已经解决了这个问题。可以这么说,它不是具有相同背景颜色的完整行,而是一种混合物。多行包含一些“已选定”颜色的单元格,并且并非所有选定行的单元格都具有所选颜色。
请注意,我将单元格的行与strnggrid的行进行比较;我无法检查选定的单元格状态,因为只选择了所选行的单元格。
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;
答案 0 :(得分:6)
如果您尝试使用不同颜色绘制选定的行或单元格,则必须检查gdSelected
变量中的state
值。
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;
答案 1 :(得分:2)
您是否启用了运行时主题?运行时主题会覆盖您尝试为Windows Vista及更高版本强制执行的任何颜色方案。
答案 2 :(得分:2)
在stringgrid中选择新单元格时,只有前一个和新选择的单元格无效。因此,不会重绘前一行和新行的剩余单元格,从而产生您描述的效果。
一种解决方法是为两个受影响的行调用InvalidateRow,但这是一个受保护的方法,您必须找到一种从OnSelectCell事件处理程序到达此方法的方法。根据您的Delphi版本,有不同的方法来实现它。
最干净的方法是从TStringGrid派生,但在大多数情况下,这是不可行的。使用较新的Delphi版本,您可以使用类助手来实现此目的。否则你必须依赖通常的protected hack。
答案 3 :(得分:2)
这对我有用
procedure TFmain.yourStringGrid(Sender: TObject; ACol, ARow: Integer; Rect: TRect;
State: TGridDrawState);
var
md: integer;
begin
with yourStringGrid do
begin
if yourStringGrid,Row = ARow then
Canvas.Brush.Color:= clYellow //your highlighted color
else begin
md := Arow mod 2;
if md <> 0 then Canvas.Brush.Color:= $00BADCC1 else //your alternate color
Canvas.Brush.Color:= clwhite;
end;
Canvas.FillRect(Rect);
Canvas.TextOut(L, Rect.top + 4, cells[ACol, ARow]);
end;
end;
刷新网格
procedure TFmain.yourStringGridClick(Sender: TObject);
begin
yourStringGrid.Refresh;
end;
注意:有一点延迟,但效果很好。
(在Delphi XE2中使用)