我的表单上有一个 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?我已经上下查看了 TGridPanel
和 TControlCollection
类代码,但找不到任何可以从鼠标坐标为我提供列或行值的内容。除了 OnDblClick()
之外,它们似乎也不是可使用的相关事件。
任何帮助将不胜感激。
编辑:将变量 Result 更改为 MyControl 以避免混淆。
最佳答案
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;
关于delphi - 在 TGridPanel 中单击单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8327381/