2

フォームにがTGridPanelあり、クリックされた特定の「セル」にコントロールを追加したいと思います。

私は簡単にポイントを得ることができます:

procedure TForm1.GridPanel1DblClick(Sender: TObject);
var
  P : TPoint;
  InsCol, InsRow : Integer;
begin
  P := (Sender as TGridPanel).ScreenToClient(Mouse.CursorPos);
  if (Sender as TGridPanel).ControlAtPos(P) = nil then
    begin
      InsCol := ???;
      InsRow := ???;
      (Sender as TGridPanel).ControlCollection.AddControl(MyControl, InsCol, InsRow)
    end;
end;

おそらくif ControlAtPos(P) = nil then行は必要ありませんが、すでにコントロールが含まれているセルにコントロールを挿入しないようにしたいのです。

では...InsColとInsRowを取得するためにどのコードを使用しますか?クラスコードを上下に移動しましたがTGridPanelTControlCollectionマウス座標から列または行の値を取得できるものが見つかりません。また、。以外に使用する関連イベントではないようですOnDblClick()

どんな助けでも大歓迎です。

編集:混乱を避けるために、変数ResultをMyControlに変更しました。

4

2 に答える 2

3
procedure TForm1.GridPanel1Click(Sender: TObject);
var
  P: TPoint;
  R: TRect;
  InsCol, InsRow : Integer;
begin
  P := (Sender as TGridPanel).ScreenToClient(Mouse.CursorPos);
  for InsCol := 0 to GridPanel1.ColumnCollection.Count - 1 do
  begin
    for InsRow := 0 to GridPanel1.RowCollection.Count - 1 do
    begin
      R:= GridPanel1.CellRect[InsCol,InsRow];
      if PointInRect(P,R) then
      begin
        ShowMessage (Format('InsCol = %s and InsRow = %s.',[IntToStr(InsCol), IntToStr(InsRow)]))
      end;
    end;
  end;


end;

function TForm1.PointInRect(aPoint: TPoint; aRect: TRect): boolean;
begin
  begin
    Result:=(aPoint.X >= aRect.Left  ) and
            (aPoint.X <  aRect.Right ) and
            (aPoint.Y >= aRect.Top   ) and
            (aPoint.Y <  aRect.Bottom); 
  end;
end;
于 2011-11-30T15:14:41.170 に答える
0

これがRavaut123のアプローチの最適化です(より大きなグリッドの場合ははるかに高速である必要があります)。この関数は、TPointのX/Yグリッド位置を返します。ユーザーが有効な列をクリックしたが有効な行はクリックしなかった場合でも、有効な列情報が返され、同じことが行にも当てはまります。したがって、「オールオアナッシング」(有効なセルまたは無効なセル)ではありません。この関数は、グリッドが「通常」であることを前提としています(すべての列の行の高さは最初の列と同じであり、同様にすべての行の列の幅は最初の行と同じです)。グリッドが規則的でない場合は、Ravaut123のソリューションがより適切な選択です。

// APoint is a point in local coordinates for which you want to find the cell location.
function FindCellInGridPanel(AGridPanel: TGridPanel; const APoint: TPoint): TPoint;
var
  ICol, IRow : Integer;
  R : TRect;
begin
  Result.X := -1;
  Result.Y := -1;
  for ICol := 0 to AGridPanel.ColumnCollection.Count - 1 do
    begin
      R := AGridPanel.CellRect[ICol, 0];
      if (APoint.X >= R.Left) and (APoint.X <= R.Right) then
        begin
          Result.X := ICol;
          Break;
        end;
    end;
  for IRow := 0 to AGridPanel.RowCollection.Count - 1 do
    begin
      R := AGridPanel.CellRect[0, IRow];
      if (APoint.Y >= R.Top) and (APoint.Y <= R.Bottom) then
        begin
          Result.Y := IRow;
          Break;
        end;
    end;
end;
于 2011-12-02T16:01:39.927 に答える