Forum > LCL
Highlighting row in TSTringGrid on mouse hover
(1/1)
bruce.button:
Is there a (relatively) easy way of highlighting a row in a TStringGrid when the mouse cursor hovers over it? I'm sure it must be possible, but I can't even find an event for mouseover on the TStringGrid.
Thank you in advance!
Handoko:
Short answer:
Easy.
Long answer:
Basically it can be divided into 2 parts:
- Converting mouse position to row:col values
- Coloring the grid.
I wrote the code for converting mouse position to grid's row:col values.
--- Code: Pascal [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Grids, StdCtrls; type { TForm1 } TForm1 = class(TForm) Label1: TLabel; StringGrid1: TStringGrid; procedure StringGrid1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); end; var Form1: TForm1; implementation {$R *.lfm} { TForm1 } procedure TForm1.StringGrid1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);var R, C: Integer; Start, Size: Integer; i: Integer;begin // Row R := -1; Start := 0; for i := 0 to StringGrid1.RowCount-1 do begin Size := StringGrid1.RowHeights[i]; if (Y > Start) and (Y < Start + Size) then begin R := i; Break; end; Inc(Start, Size); end; // Column C := -1; Start := 0; for i := 0 to StringGrid1.ColCount-1 do begin Size := StringGrid1.ColWidths[i]; if (X > Start) and (X < Start + Size) then begin C := i; Break; end; Inc(Start, Size); end; // Show result Caption := 'Mouse X:Y = ' + X.ToString + ':' + Y.ToString; case (R < 0) or (C < 0) of True: Label1.Caption := 'Mouse is outside the grid'; False: Label1.Caption := 'Row:Col = ' + R.ToString + ':' + C.ToString; end;end; end.
For the second part, you can study and use the code of the demo for doing coloring in the link below ( Searchable StringGrid, category "User Interface) :
https://wiki.freepascal.org/Portal:HowTo_Demos#User_Interface
wp:
Use OnPrepareCanvas to highlight the row under the mouse. It is fired immediately before a specific cell is painted. To get the row index under the mouse query Mouse.CursorPos (which is relative to the screen) and convert it to grid pixels by the grid's ScreenToClient method. Finally call MouseToCell to determine the col and row indices of the mouse-over point. Compare them with the arguments passed to OnPreparecanvas to determine whether the currently requested cell needs a different color. Finally, in order to update the color whenever the mouse moves handle the OnMouseMove event and request the grid to repaint itself (Grid.Invalidate).
See attached demo.
bruce.button:
Thank you so much, Handoko and wp. That is extremely helpful.
Navigation
[0] Message Index