Firemonkey MouseToCell equivalent

与世无争的帅哥 提交于 2019-12-22 08:08:16

问题


In Delphi VCL if I wanted to see which cell (column and row) of a TStringGrid my mouse was hovering over I'd use MouseToCell. This method is no longer in Delphi (XE2) for FireMonkey apps. Does anyone know how I can determine the cell my mouse is over? OnMouseMove has X & Y values but these are screen coordinates and not cell coordinates.

Many thanks.


回答1:


There's actually a MouseToCell method in TCustomGrid, which the StringGrid descends, but it's private. Looking at its source, it makes use of ColumnByPoint and RowByPoint methods, which are fortunately public.

The 'column' one returns a TColumn, or nil if there's no column. The 'row' one returns a positive integer, or -1 when there's no row. Furthermore, the row one does not care the row count, it just accounts for row height and returns a row number based on this, even if there are no rows. Also, I should note that, behavior on grid header is buggy. Anyway, sample example could be like:

procedure TForm1.StringGrid1MouseMove(Sender: TObject; Shift: TShiftState; X,
  Y: Single);
var
  Col: TColumn;
  C, R: Integer;
begin
  Col := StringGrid1.ColumnByPoint(X, Y);
  if Assigned(Col) then
    C := Col.Index
  else
    C := -1;
  R := StringGrid1.RowByPoint(X, Y);

  Caption := Format('Col:%d Row:%d', [C, R]);
end;



回答2:


TStringGrid has a ColumnByPoint and RowByPoint method.

ColumnByPoint and RowByPoint go by the coordinates of the string grid. So, if you use the OnMouseOver of the string grid, the X and Y parameters will already be in the string grid's cooridnates.

Here's how to display the row and column (0 based) in the string grid's OnMouseOver:

var
  row: Integer;
  col: TColumn;
  colnum: Integer;
begin
  row := StringGrid1.RowByPoint(X, Y);
  col := StringGrid1.ColumnByPoint(X, Y);
  if Assigned(col) then
  begin
    colnum := col.Index;
  end
  else
  begin
    colnum := -1;
  end;
  Label1.Text := IntToStr(row) + ':' + IntToStr(colnum);
end;

Note that -1 will be displayed when outside the bounds of the rows and columns.



来源:https://stackoverflow.com/questions/18993066/firemonkey-mousetocell-equivalent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!