我正在执行查询并在dbgrid中显示返回的数据。
我想突出显示符合搜索条件的项目。类似的东西:
搜索:" 测试"
在DBGrid中,返回的数据将是。
f_500 = open('halo_classificatio_500_with_surface_pressure_term.txt', 'a')
f_200 = open('halo_classificatio_200_with_surface_pressure_term.txt', 'a')
f_178 = open('halo_classificatio_178_with_surface_pressure_term.txt', 'a')
f_100 = open('halo_classificatio_100_with_surface_pressure_term.txt', 'a')
over_density = [500,200,178,100]
for jj in over_density:
tm_msun = 2
cm_msun = 2
vr_mpc = 2
file('f_'+str(jj)).write("%s\t%s\t%s\n" % (tm_msun, cm_msun, vr_mpc))
这里的目标无疑是查询数据。但是如何在DBGrid中突出显示特定文本?
重要提示:只应突出显示文本的特定部分。
注意:所提供的信息是为了清楚说明,而不是与现实完全对应。
答案 0 :(得分:6)
此程序突出显示`FilterText'在DbGrid
procedure HighlightCellText(AGrid :TDbGrid; const ARect : TRect; AColumn : TColumn; FilterText : string; AState:TGridDrawState ;
BkColor : TColor = clYellow; SelectedBkColor : TColor = clGray);
var
HlRect : TRect;
Position : Integer;
HlText, FilterColName,DisplayText: string;
i, offset : Integer;
begin
DisplayText := Acolumn.Field.AsString;
Position := Pos(AnsiLowerCase(FilterText), AnsiLowerCase(DisplayText){ AnsiLowerCase(AColumn.DisplayText)});
if Position > 0 then
begin
// set highlight area
case AColumn.Alignment of
taLeftJustify: HlRect.Left := ARect.Left + AGrid.Canvas.TextWidth(Copy(DisplayText, 1, Position-1)) + 1;
taRightJustify: begin
Offset := AGrid.Canvas.TextWidth(Copy(DisplayText, 1,1)) - 1;
HlRect.Left := (ARect.Right - AGrid.Canvas.TextWidth(DisplayText)-offset) + AGrid.Canvas.TextWidth(Copy(DisplayText, 1, Position-1));
end;
taCenter: begin
Offset := ((ARect.Right - ARect.Left) div 2) - (AGrid.Canvas.TextWidth(DisplayText) div 2) - (AGrid.Canvas.TextWidth(Copy(DisplayText, 1,1)) - 2);
HlRect.Left := (ARect.Right - AGrid.Canvas.TextWidth(DisplayText)- offset) + AGrid.Canvas.TextWidth(Copy(DisplayText, 1, Position-1));
end;
end;
HlRect.Top := ARect.Top + 1;
HlRect.Right := HlRect.Left +AGrid.Canvas.TextWidth(Copy(DisplayText, Position, Length(FilterText))) + 1 ;
HlRect.Bottom := ARect.Bottom - 1;
//check for limit of the cell
if HlRect.Right > ARect.Right then
HlRect.Right := ARect.Right;
// setup the color and draw the rectangle in a width of the matching text
if gdSelected in AState then
AGrid.Canvas.Brush.Color := SelectedBkColor
else
AGrid.Canvas.Brush.Color := BkColor;
AGrid.Canvas.FillRect(HlRect);
HlText := Copy(DisplayText,Position, Length(FilterText));
AGrid.Canvas.TextRect(HlRect,HlRect.Left + 1,HlRect.Top + 1, HlText);
end;
end;
在DbGrid.OnDrawColumnCell事件中使用它:
例如,突出显示的文字是" ro"。
procedure TForm6.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
HighlightCellText(TDBGrid(Sender),Rect, Column,'ro',State);
end;
结果:
编辑: