Sign in Join
Wiki copytemporary

Grids Reference Page/de: what changed

Revision 2 to 3. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
11Zurück zu den [[Additional information/de|Zusätzlichen Informationen]].\
22
33== Die Zielsetzung == Dieser Text will versuchen, dem Benutzer einige Aspekte der Grid-Komponenten in Lazarus zu zeigen. Es ist auch vorgesehen, als ein Handbuch für Benutzer zu dienen, die noch nie zuvor Grids benutzt haben (während erfahrene Benutzer im Allgemeinen nur eine Referenz benötigen für neue Funktionalitäten). Daher will dieser Text versuchen, die folgenden Ziele zu erreichen:
44
551. Die Grid-Komponenten den Menschen mit geringem oder gar keinem Delphi Kontakt vorzustellen.
662. Die Unterschiede hinsichtlich der Delphi Grid-Komponenten zu dokumentieren.
773. Die neuen Funktionalitäten in Lazarus Grids zu dokumentieren.
884. Referenzen und Beispiele für die Komponenten zu erstellen.
99
1010## Überblick
1111
1212Ein Grid ist eine Komponente, die hauptsächlich zur Anzeige von Daten in einem tabellarischen Format dient. Die offensichtlichste Charakteristik von Grids ist, dass sie aus Zellen bestehen, Zeilen und Spalten bildend.
1313
1414Der Informationstyp, der in einem Grid angezeigt werden kann, ist sehr weitläufig, hauptsächlich abhängig von dem, was der Benutzer anzeigen möchte. Gewöhnlich wird diese Information in Text, Farben, Bilder oder eine Kombination daraus übersetzt.
1515
1616In Anbetracht der großen Vielfalt von Informationen, die repräsentiert werden können, existiert eine Reihe von Grids, deren Zweck darin besteht, den Benutzer zu unterstützen, eine spezifische Art von Informationen zu zeigen.
1717
1818## Vererbungsbaum
1919
2020 [TCustomControl]
2121 |
2222 |
2323 TCustomGrid
2424 |
2525 +-------------+------------+
2626 | |
2727 TCustomDrawGrid TCustomDbGrid
2828 | |
2929 +--------+--------+ |
3030 | | TDbGrid
3131 TDrawGrid TCustomStringGrid
3232 |
3333 |
3434 TStringGrid
3535
3636## Ein Anfangsbeispiel
3737
3838Eine Zielsetzung dieses Textes soll die Benutzerfreundlichkeit sein, insbesondere für diejenigen, die keine oder wenig Erfahrung mit Lazarus haben. Fangen wir also mit einem einfachen Beispiel an, in dem wir die Grids-Komponente in Aktion sehen und beginnen mit dem traditionellen "Hallo Welt" Beispiel unter Verwendung der TStringGrid Komponente.
3939
40401. Erstellen sie eine neue Anwendung.
4141 - Im Hauptmenü wählen sie: Projekt -\> Neues Projekt
4242 - Im Erzeuge neues Projekt Dialog drücken sie den "Erzeuge Button"
4343 - Ein neues leeres Formular wird angezeigt.
44442. Platzieren sie ein Grid auf dem Formular.
4545 - In der Komponentenpalette wählen sie den "Additional" Tab.
4646 - Klicken sie auf das TStringGrid Icon ![](/wiki-images/6/67/Tstringgrid.png).
4747 - Klicken sie auf das Formular, in der Nähe der oberen linken Ecke. Ein neues leeres Grid erscheint.
48483. Platzieren sie einen Button auf dem Formular.
4949 - In der Komponentenpalette wählen sie den "Standard" Tab.
5050 - Klicken sie auf das TButton Icon ![](/wiki-images/b/b2/Tbutton.png).
5151 - Klicken sie auf einen freien Bereich im Formular. Ein neuer Button erscheint.
52524. Klicken sie doppelt auf den Button von Schritt 3, und schreiben sie den folgenden Code in den click button handler:
5353 - ``` Pascal
5454 StringGrid1.Cells[1,1] := 'Hi World!';
5555 ```
56565. Starten sie das Programm durch klicken auf das Start Icon ![](/wiki-images/8/85/Menu_run.png).
5757 - Durch Drücken von Button1, sollte der hello world Text in der Zelle Spalte 1, Zeile 1 erscheinen.
5858
5959## Unterschiede zwischen Lazarus und Delphi Grids
6060
6161Die momentanen Grid-Komponenten haben mehrere Unterschiede im Vergleich zu den Delphi Grid-Komponenten. Dies kommt vor allem daher, dass die Lazarus Grid-Komponenten komplett neu geschrieben wurden und dabei nicht zwingend auf die Kompatibilität geachtet wurde.
6262
6363Die Kompatibiliät wurde erst zu einem späteren Zeitpunkt zu einem Ziel. Die Grid-Komponenten passten sich immer mehr dem Interface der Delphi Grid-Komponenten an, aber dabei wurde nicht jede einzelne Methode und jede Eigenschaft 1:1 übernommen.
6464
6565Weil die Grid-Komponenten intern recht unterschiedlich sind, gibt es Dinge die nicht möglich sind oder anders als bei einer Delphi Grid-Komponente funktionieren. Im Laufe der Entwicklung der Grid-Komponenten, wurde die Kompatibilität jedoch immer besser was durchaus auch wünschenswert ist.
6666
6767### Unterschiede
6868
6969An dieser Stelle werden die bekannten Unterschiede aufgeführt ohne spezielle Reihenfolge.
7070
7171- Zelleneditoren
7272- Entwicklungszeitverhalten
7373- Es gibt einige Unterschiede beim Zeichnen der Zellen, siehe Abschnitt Customizing grids
7474
7575### Neue Funktionsweise
7676
7777- Spalten
7878- Ereignisse
7979- Grid Editor
8080
8181### Anpassungen zur Verbesserung der Delphi grids Kompatibilität
8282
8383Hier ist eine Liste von Eigenschaften und Anpassungen die vorgenommen werden können, damit Lazarus grids wie Delphi grids aussehen oder sich so verhalten. This adjustments are based in a newly created grid. Einträge mit \[Code\] müssen im Quellcode gesetzt werden, \[Design\] Einträge können zur Entwicklungszeit geändert werden.
8484
8585- \[Design\] TitleStyle:=tsStandard;
8686- \[Design\] DefaultRowHeight:=24;
8787- \[Code\] EditorBorderStyle:=bsNone; // dies dürfte nur unter Windows funktionieren.
8888- \[Code\] UseXORFatures:=true;
8989- \[Code\] AllowOutBoundClicks:=False; (r10992 oder später)
9090- \[Code\] FastEditing:=False; (unterstützt in dbgrid. StringGrid benötigt r10992 oder später)
9191- \[Design\] AutoAdvance:=aaNone;
9292
9393## Grids Referenz
9494
9595### Information
9696
9797Der Ausgangspunkt für eine Referenz über TCustomGrid, TDrawGrid, TCustomDrawGrid, TCustomStringGrid und TStringGrid ist die [Unit grids.pas Referenz](http://lazarus-ccr.sourceforge.net/docs/lcl/grids/index.html).
9898
9999Für TCustomDBGrid und TDBgrid ist es die [Unit dbgrids.pas Referenz](http://lazarus-ccr.sourceforge.net/docs/lcl/dbgrids/index.html).
100100
101101Gegenwärtig enthalten diese Links noch nicht viel Inhalt, teilweise wegen des Fehlens eines Werkzeugs, das eine einfache Wartung ihres Inhalts erlaubt. Aber ein solches Werkzeug ist im Aufbau befindlich und irgendwann werden die Lücken gefüllt werden.
102102
103103Im Allgemeinen, jede Delphi Referenz über Grids sollte helfen, die Lazarus Grids zu verwenden (don't forget that there are several differences between Delphi and Lazarus grids being documented), with this in mind and as a temporal place for reference information, wird dieser Ort genutzt, um Dinge zu dokumentieren, die nicht wie in Delphi funktionieren oder die eine neue Funktionalität darstellen.
104104
105105\[TODO: the rest of this section will dissapear, it's content will be moved to [unit grids.pas reference](http://lazarus-ccr.sourceforge.net/docs/lcl/grids/index.html)
106106
107107### TCustomGrid
108108
109109See the full [[doc:lcl/grids/tcustomgrid.html|TCustomGrid Reference]]
110110
111111#### property OnBeforeSelection: TOnSelectEvent
112112
113113#### property OnCompareCells: TOnCompareCells
114114
115115#### property OnPrepareCanvas: TOnPrepareCanvasEvent
116116
117117#### property OnDrawCell: TOnDrawCell
118118
119119#### property OnEditButtonClick: TNotifyEvent
120120
121121#### property OnSelection: TOnSelectEvent
122122
123123#### property OnSelectEditor: TSelectEditorEvent
124124
125125#### property OnTopLeftChanged: TNotifyEvent
126126
127127#### procedure AutoAdjustColumns;
128128
129129#### procedure BeginUpdate;
130130
131131#### procedure Clear;
132132
133133#### procedure DeleteColRow(IsColumn: Boolean; index: Integer);
134134
135135#### function EditorByStyle(Style: TColumnButtonStyle): TWinControl;
136136
137137#### procedure EndUpdate(UO: TUpdateOption); overload;
138138
139139#### procedure EndUpdate(FullUpdate: Boolean); overload;
140140
141141#### procedure EndUpdate; overload;
142142
143143#### procedure ExchangeColRow(IsColumn: Boolean; index, WithIndex:Integer);
144144
145145#### function IscellSelected(aCol,aRow: Integer): Boolean;
146146
147147#### function IscellVisible(aCol, aRow: Integer): Boolean;
148148
149149#### procedure LoadFromFile(FileName: string);
150150
151151#### function MouseToCell(Mouse: TPoint): TPoint; overload;
152152
153153#### function MouseToLogcell(Mouse: TPoint): TPoint;
154154
155155#### function MouseToGridZone(X,Y: Integer): TGridZone;
156156
157157#### function CellToGridZone(aCol,aRow: Integer): TGridZone;
158158
159159#### procedure MoveColRow(IsColumn: Boolean; FromIndex, ToIndex: Integer);
160160
161161#### procedure SaveToFile(FileName: string);
162162
163163#### procedure SortColRow(IsColumn: Boolean; index:Integer); overload;
164164
165165#### procedure SortColRow(IsColumn: Boolean; index,FromIndex,ToIndex: Integer); overload;
166166
167167### TCustomStringGrid
168168
169169TCustomStringGrid dient als Basis für TStringGrid. It can be used for derived TStringGrid components that want to hide published properties. See [[new intermediate grids]] for more information.
170170
171171These properties or methods are public and are also available to TStringGrid.
172172
173173See the full [TCustomStringGrid Reference](http://lazarus-ccr.sourceforge.net/docs/lcl/grids/tcustomstringgrid.html)
174174
175175#### procedure AutoSizeColumn(aCol: Integer);
176176
177177This procedure sets the column width to the size of the widest text it finds in all rows for the column aCol. Tip: see the goDblClickAutoSize option to allow columns to be automatically resized when doubleClicking the column border.
178178
179179#### procedure AutoSizeColumns;
180180
181181Automatically resizes all columns by adjusting them to fit in the longest text in each column. This is a quick method of applying AutoSizeColumn() for every column in the grid.
182182
183183#### procedure Clean; overload;
184184
185185Cleans all cells in the grid, fixed or not.
186186
187187#### procedure Clean(CleanOptions: TCleanOptions); overload;
188188
189189Cleans all cells in the grid subject to the given CleanOptions. see [[TCleanOptions]] for more information. Some examples:
190190
191191- Clean all cells: grid.Clean(\[\]); (the same as grid.clean)
192192- Clean all non fixed cells: grid.Clean(\[gzNormal\]);
193193- Clean all cells but don't touch grid column headers: Grid.Clean\[gzNormal, gzFixedRows\]);
194194
195195#### procedure Clean(StartCol,StartRow,EndCol,EndRow: integer; CleanOptions:TCleanOptions); overload;
196196
197197does the same as Clean(CleanOptions:TCleanOptions) but restricted to the given StartCol,StartRow,EndCol and EndRow. Examples:
198198
199199- Clean column index 4 to 6 but don't touch grid column headers: many variations, Grid.Clean(4,Grid.FixedRows,6,Grid.RowCount-1,\[\]); Grid.Clean(4,0,6,Grid,RowCount-1, \[gzNormal\]); etc.
200200
201201#### procedure Clean(aRect: TRect; CleanOptions: TCleanOptions); overload;
202202
203203The same as Clean(StartCol,StartRow,EndCol,EndRow, CleanOptions), just taking a TRect instead of individual cell coordinates. Useful to clean the selection: grid.Clean(Grid.Selection,\[\]);
204204
205205#### property Cols\[index: Integer\]: TStrings read GetCols write SetCols;
206206
207207Get/set a list of strings from/to the given grid's column index starting from row index 0 to RowCount-1.
208208
209209##### Beispiele
210210
211211- Set Example: Set the content of the third column in the grid from a ListBox:
212212
213-`Grid.Cols[2] := ListBox1.Items;`
213+``` pascal
214+Grid.Cols[2] := ListBox1.Items;
215+```
214216
215217- Get Example: Set the content of a Listbox from the grid's column index 4:
216218
217-`procedure TForm1.FillListBox1;`\
218-`var `\
219-`  StrTempList: TStringList;`\
220-`begin`\
221-`  StrTempList := TStringList(Grid.Cols[4]);`\
222-`  if StrTempList<>nil then begin`\
223-`    ListBox1.Items.Assign(StrTempList);`\
224-`    StrTempList.Free;`\
225-`  end;`\
226-`end;   `
219+``` pascal
220+procedure TForm1.FillListBox1;
221+var
222+ StrTempList: TStringList;
223+begin
224+ StrTempList := TStringList(Grid.Cols[4]);
225+ if StrTempList<>nil then begin
226+ ListBox1.Items.Assign(StrTempList);
227+ StrTempList.Free;
228+ end;
229+end;
230+```
227231
228232##### Anmerkungen
229233
230234This property works in a different way in Lazarus than in Delphi when getting the data from the grid. In Lazarus a temporary TStringList object is created for retrieving the column content. It is the responsibility of the user to free this object after use.
231235
232236This means also that changes in the returned list will not affect the grids content or layout.
233237
234238See the Get Example.
235239
236240#### property Rows\[index: Integer\]: TStrings read GetRows write SetRows;
237241
238242Get/set a list of strings from/to the given grid's row index starting from column index 0 to column ColCount-1.
239243
240244##### Anmerkungen
241245
242246This property works in a different way in Lazarus than in Delphi when getting the data from the grid. In Lazarus a temporary TStringList object is created for retrieving the row content. It is the responsibility of the user to free this object after use.
243247
244248This means also that changes in the returned list will not affect the grids content or layout.
245249
246250##### Beispiele
247251
248252- Set Example: Set the content of the third row in the grid from a ListBox:
249253
250-`Grid.Rows[2] := ListBox1.Items;`
254+``` pascal
255+Grid.Rows[2] := ListBox1.Items;
256+```
251257
252258- Get Example: Set the content of a Listbox from the grid's row index 4:
253259
254-`procedure TForm1.FillListBox1;`\
255-`var `\
256-`  StrTempList: TStringList;`\
257-`begin`\
258-`  StrTempList := TStringList(Grid.Rows[4]);`\
259-`  if StrTempList<>nil then begin`\
260-`    ListBox1.Items.Assign(StrTempList);`\
261-`    StrTempList.Free;`\
262-`  end;`\
263-`end;  `
260+``` pascal
261+procedure TForm1.FillListBox1;
262+var
263+ StrTempList: TStringList;
264+begin
265+ StrTempList := TStringList(Grid.Rows[4]);
266+ if StrTempList<>nil then begin
267+ ListBox1.Items.Assign(StrTempList);
268+ StrTempList.Free;
269+ end;
270+end;
271+```
264272
265273- Not Working Example and Fix: Retrieved string list is read only
266274
267-`// this will not work and will cause memory leak`\
268-`// because returned StringList is not being freed`\
269-`Grid.Rows[1].CommaText := '1,2,3,4,5';`\
270-`Grid.Rows[2].Text := 'a'+#13#10+'s'+#13#10+'d'+#13#10+'f'+#13#10+'g'; `\
275+``` pascal
276+// this will not work and will cause memory leak
277+// because returned StringList is not being freed
278+Grid.Rows[1].CommaText := '1,2,3,4,5';
279+Grid.Rows[2].Text := 'a'+#13#10+'s'+#13#10+'d'+#13#10+'f'+#13#10+'g';
271280
272-`// fixing the first case`\
273-`Lst:=TStringList.Create;`\
274-`Lst.CommaText := '1,2,3,4,5';`\
275-`Grid.Rows[1] := Lst;`\
276-`Lst.Free;`
281+// fixing the first case
282+Lst:=TStringList.Create;
283+Lst.CommaText := '1,2,3,4,5';
284+Grid.Rows[1] := Lst;
285+Lst.Free;
286+```
277287
278288#### property UseXORFeatures;
279289
280290Boolesche Eigenschaft, Vorgabewert: false;
281291
282292This property controls how the dotted focus rectangle appears in the grid. When true, the rectangle is painted using the XOR raster operation. This allow us to see the focus rectangle no matter what the cells' background color is. When false, the user can control the color of the dotted focus rectangle using the [[FocusColor property]]
283293
284294It also controls the look of the column/row resizing. When true, a line shows visually the size that the the column or row will have if the user ends the operation. When false, the column or row resizing takes effect just as the user drags the mouse.
285295
286296## Grids Howto
287297
288298### Customizing grids
289299
290300Grid are components derived from TCustomControl class, and don't have a native widget associated to them which means that grids are not restricted by the look of current interface theme. This can be equally considered an advantage but also a disadvantage because usually programmers want to create a uniform-look application. The good news is that Lazarus grids are flexible enough to get something from both worlds, programmers can easily make grids to look like other native controls or they can customize the grid to the finest detail so they can obtain almost the same look in any platform or widget interface, that is, with the exception of scrollbars because their look is still determined by current theme.
291301
292302### Eigenschaften und Ereignisse für customizing grids
293303
294304Some properties can affect the way the grid looks by acting when the cell is about to be painted in PrepareCanvas/OnPrepareCanvas by changing default canvas properties like brush color or font. Following is a list of such properties:
295305
296306- **AlternateColor.** With this the user can change the background color appears on alternated rows. This is to allow easy reading off of grid rows data.
297307- **Color.** This sets the primary color used to draw non fixed cells background.
298308- **FixedColor.** This is the color used to draw fixed cells background.
299309- **Flat.** this eliminates the 3d look of fixed cells.\
300310- **TitleFont.** Font used to draw the text in fixed cells.\
301311- **TitleStyle.** This property changes the 3D look of fixed cells, there are 3 settings:
302312 - *tsLazarus.* This is the default look
303313 - *tsNative.* This tries to set a look that is in concordance with current widgetset theme.
304314 - *tsStandard.* This style is a more contrasted look, like delphi grids.
305315- **AltColorStartNormal.** boolean, if true alternate color is always in the second row after fixed rows, the first row after fixed rows will be always color, if false default color is set to the first row as if there were no fixed rows.
306316- **BorderColor.** This sets the grid's border color used when Flat:=True and BorderStyle:=bsSingle;
307317- **EditorBorderStyle.** If set to bsNone under windows the cell editors will not have the border, like in delphi, set to bsSingle by default because the border can be theme specific in some widgetsets and to allow a uniform look.\
308318- **FocusColor.** The color used to draw the current focused cell if UseXORFeatures is not set, by default this is clRed.
309319- **FocusRectVisible.** turns on/off the drawing of focused cell.
310320- **GridLineColor.** color of grid lines in non fixed area.
311321- **GridLineStyle.** Pen style used to draw lines in non fixed area, possible choices are: *psSolid*, *psDash*, *psDot*, *psDashDot*, *psDashDotDot*, *psinsideFrame*, *psPattern*,*psClear*. default is *psSolid*.
312322- **SelectedColor.** Color used to draw cell background on selected cells.
313323- **UseXORFeatures.** If set, focus rect is drawn using XOR mode so it should make visible the focus rect in combination with any cell color ackground. It also affects the moving columns look.
314324- **DefaultDrawing.** boolean. Normally the grids prepare the grid canvas using some properties according to the kind of cell is being painted. If user write an OnDrawCell event handler, DefaultDrawing if set also paints the cell background, if user is drawing fully the cell is better turn off this property so painting is not duplicated. In a StringGrid if DefaultDrawing is set it draws the text in each cell.
315325- **AutoAdvance.** where the cell cursor will go when pressing enter or tab/shift tab, or after editing.
316326- **ExtendedColSizing.** If true user can resize columns not just at the headers but along the columns height.
317327
318328Other properties that also affect the grids look.
319329
320330**Options**. Options property is a set with some elements to enable diverse functionality but some are related directly with grid's look. This options can be set at designtime or runtime.
321331
322332- **goFixedVertLine, goFixedHorzLine** it draws a vertical or horizontal line respectively delimiting cells or columns in fixed area, active by default.
323333- **goVertLine, goHorzLine** the same as previous, but for normal browseable area. A listbox can be simulated with a grid by unsetting both of this elements.
324334- **goDrawFocusSelected** if this element is enabled a selection background is painted in focused cell in addition to focused dotted rectangle (note this doesn't work yet when goRowSelect option is set, in such case row is always painted as if goDrawFocusSelected is set)
325335- **goRowSelect** select the full row instead of individual cells
326336- **goFixedRowNumbering** if set, grid will do numbering of rows in first fixed column
327337- **goHeaderHotTracking** if set, the grid will try to show a different look when the mouse cursor is overing any fixed cell. In order for this to work, desired cell zone needs to be enabled with property HeaderHotZones. Try combining this option with property TitleStyle:=tsNative to get themed hot tracking look.
328338- **goHeaderPushedLook** if set, this element enables a pushed look when clicking any fixed cell. The zone of "pushable" cells is enabled using HeaderPusedZones property.
329339
330340(write more)
331341
332342### Description of grid's drawing process
333343
334344Like other custom controls, the grid draws itself in the paint method, in general terms the grid is drawn by painting all rows, and each row by painting it's individual cells. The process is as follow:
335345
336346- First the visible cells area is determined, each row is tested to see if it intersects the canvas clipping region, if it's ok, then visible area is painted by drawing columns of each row.
337347- The column and row values are used to identify the cell that is about to be painted and again each column is tested for intersection with clippling region, if everything is ok, some additional properties like it's rectangualar extent and visual state are passed as arguments to DrawCell method.
338348- As the drawing process is running, the visual state of each cell is adjusted according to grid options and position within grid. The visual state is resumed in a varible of type TGridDrawState which is a set with following elements:
339349 - *gdSelected* The cell will have a selected look.
340350 - *gdFocused* The cell will have a focused look.
341351 - *gdFixed* Cell have to be painted with fixed cell look.
342352 - *gdHot* the mouse is over this cell, so paint it with hot tracking look
343353 - *gdPushed* the cell is being clicked, paint it with pushed look
344354- **DrawCell.** The DrawCell method is virtual and may be overriden in descendant grids to do custom drawing. The information passed to DrawCell method helps to identify the particular cell is being painted, the physical area ocuppied in screen and it's visible status. See DrawCell reference for details. For each cell following occurs:
345355- **PrepareCanvas.** PrepareCanvas method is called, in this method, If DefaultDrawing property es set, the grid canvas is setup with default properties for brush and font based on current visual state and on several design and runtime properties, the text alignment is set to match programmer selection in custom columns if they exists. If DefaultDrawing is false, brush color is set to clWindow and Font color to clWindowText, the text alignment is set with grids defaultTextStyle property value.
346356- **OnPrepareCanvas.** If programmer wrote a event handler for OnPrepareCanvas event, it's called at this point. This event can be used for doing simple customization like changing cell's background color, font's properties like color, fontface and style, Text layout like different combinations of left, center, top, bottom, right alignment, etc. Any change made to the canvas in this event would be lost, because the next cell drawing will reset canvas again to a default state. So it's safe doing changes only for particular cell or cells and forget about it for the rest. Using this event sometimes helps to avoid uusing OnDrawCell grid event where users would be forced to duplicate the grid's drawing code. todo: samples of what can be made and what to leave for OnDrawCell?...
347357- **OnDrawCell.** Next if no handler for OnDrawCell event was specified, the grid calls the DefaultDrawCell method which simply paints the cell background using current canvas brush color and style, if OnDrawCell handler exists, the grid first paints the cell background but only if DefaultDrawing property was set, then it calls OnDrawCell event to do custom cell painting. Usually programmers want to do custom drawing only for particular cells, but standard drawing for others, in this case, they can restrict custom operation to certain cell or cells by looking into ACol,ARow and AState arguments, and for other cells simply call DefaultDrawCell method and let the grid to take care of it.
348358- **Text.** At this point (only for TStringGrid) if DefaultDrawing property is true, the cell's text content is painted.
349359- **Grid lines**. The last step for each cell is to paint the grid lines if grid options goVertLine,goHorzLine, goFixedVertLine and goFixedHorzLine are specified the cell grid is drawn at this point. Grids with only rows or only cols can be obtained by changing these options. If programmer elected to have a "themed" look it's done at this point also (see property TitleStyle).
350360- **FocusRect.** When all columns of current row have been painted it's time to draw the focus rectangle for current selected cell or for the whole row if goRowSelect option is set.
351361
352362### Grid's cell selection
353363
354364Grid's current (focused) cell (or row) can be changed of location using keyboard, mouse or through code, in order a cell focus can be successfully changed to another position, target position need to be tested if it's allowed to receive cell focus. When using keyboard, the property AutoAdvance takes part of the process by finding what should be the next focused cell. When using mouse by clicking or by code, the target cell needs to be allowed to receive focus or currently focused cell will not move.
355365
356366The way the grid knows what cell is focusable is by calling function SelectCell, if this function returns true, then the target cell identified with arguments acol and arow is focusable, current implementation in TCustomGrid simply returns true. TCustomDrawGrid and hence TDrawGrid and TStringGrid override this method to check first if cell is any wider than 0, normally you don't want a 0 width cell selected so a cell with this characteristics is skipped automatically in the process to find a suitable cell. The other thing the overriden method SelectCell does is to call the user configurable event OnSelectCell, this event receive as arguments, the cell coordinates and a default result value of true always.
357367
358368Once a cell is known to be focusable and for sure a movement will take place, first method BeforeMoveSelection is called which in turns triggers OnBeforeSelection event, this method's arguments are the coordinates the new focused cell will have, at this point any visible editor is hidden too. the "before" word means that selection is not yet changed and current focused coordinates can be accessed with grid.Col and grid.Row properties.
359369
360370After that, the internal focused cell coordinates are changed and then method MoveSelection is called, this method purpose is to trigger OnSelection event if set, this is a notification that focused cell has, by this time, already changed and cell coordinates are now available through grid.row and grid.col properties.
361371
362372Note that is not good to use OnSelectCell event to detect cell focus changes, this event will be triggered several times even for the same cell in the process of finding a suitable cell. Is better to use OnBeforeSelection or OnSelection events for this purpose.
363373
364374### Several differences with delphi have been identified
365375
366376- In Lazarus TCustomGrid.DrawCell method is not abstract and it's default implementation do basic cell background filling.
367377- In delphi, the cell's text is drawn before entering the OnDrawCell event see [bug report \#9619](http://www.freepascal.org/mantis/view.php?id=9619)).
368378- SelectCell and OnSelectCell behaviour is probably different, can't really comment on the differences but in lazarus is they are used in functinality like AutoAdvance which afaik doesn't exist in delphi.
369379
370380### When above customizaton is not enough, derived grids
371381
372382Derivd grids usually have to override following methods:\
373383DrawAllRows: Draws all visible rows.\
374384DrawRow: Draw All Cells in a Row.\
375385DrawRow draws all cells in the row by first checking if cell is withing clipping region, and only draws the cell if it is.\
376386DrawCell:\
377387DrawCellGrid:\
378388DrawCellText:\
379389DrawFocusRect:\
380390(write me).\
381391
382392### Ablauf der Methodenaufrufe in `TCustomGrid.Paint`
383393
384394Die folgenden Auflistungen sollen den Ablauf zum Zeichnen eines TCustomGrid-Nachkommen vereinfacht darstellen. Die verschachtelten Aufzählungen bezeichnen jeweils Methodenaufrufe innerhalb eines Grids. Bei der Entwicklung von Nachkommen von TCustomGrid, kann so die richtige Methode zum Überschreiben leichter gefunden werden.
385395
386396- **`DrawEdges`**: Zeichnet den äußeren Rahmen des Grids.
387397- **`DrawAllRows`** (virtual): Hier werden alle sichtbaren Zellen des Gitters gezeichnet.
388398 - **`DrawRow`** (virtual): Zeichnet alle sichtbaren Zellen einer Zeile. Wird für jede Gitterzeile im aktuellen Sichtfenster einmal ausgeführt.
389399 - **`DrawCell`** (virtual): Wird zunächst für jede 'normale' (also nicht fixierte) Zelle der Zeile ausgeführt.
390400 - **`PrepareCanvas`** (virtual): Setzt die Eigenschaften der Zeichenfläche für das Zeichnen der aktuellen Zelle.
391401 - **`DrawFillRect`**: Zeichnet den Hintergrund der Zelle im mit `PrepareCanvas` eingestellten Stil.
392402 - **`DrawCellGrid`** (virtual): Zeichnet die Begrenzungen der Zelle.
393403 - **`DrawFocusRect`** (virtual): In `TCustomGrid` hat diese Methode keine Funktion. In abeleiteten Grid-Klassen wird hier das Focus-Rechteck innerhalb der aktiven Zelle gezeichnet.
394404 - **`DrawCell`** (virtual): (siehe oben) Abschließend wird `DrawCell` für jede fixierte Zelle im Sichtbereich der Zeile einmal ausgeführt.
395405- **`DrawColRowMoving`**: Wird nur während des Verschiebens einer Zeile/Spalte ausgeführt. Es zeichnet die Linie mit welcher die neue Position der verschobenen Zeile/Spalte angedeutet wird.
396406- **`DrawBorder`**: Wenn nötig (`Flat=TRUE` und `BorderStyle=bsSingle`), wird hier ein innerer Rand gezeichnet.
397407
398408#### Weitere Methoden zum Zeichnen in `TCustomGrid`
399409
400410Die folgenden Methoden werden zwar in `TCustomGrid` deklariert, hier aber nicht direkt aufgerufen. Sie werden von abgeleiteten Klassen ausgeführt um den Zelleninhalt zu zeichnen.
401411
402412- **`DrawCellText`** (virtual): Zeichnet den im Parameter übergebenen Text in die Zelle. Verwendet zur Formatierung die in `Canvas.TextStyle` aktiven Einstellungen (siehe `PrepareCanvas`).
403413
404414***`DrawThemedCell`** (virtual): Wird nur für fixierte Zellen verwendet, wenn `TitleStyle=tsNative`. Zeichnet den Hintergrund der Zelle mit den Einstellungen der `ThemeServices`.\
405415***`DrawColumnText`** (virtual): Wird nur für die Zellen der Spaltenüberschriften ausgeführt
406416
407417- - **`DrawColumnTitleImage`**: Wenn eine `TitleImageList` zugewiesen und in `Columns.Title[x].Title.ImageIndex` ein gültiger Wert eingetragen ist, wird das entsprechende Icon gezeichnet.
408418 - **`DrawCellText`** : (siehe oben)
409419
410420***`DrawTextInCell`** (virtual): Wird nur für 'normale' (nicht fixierte) Zellen verwendet. In `TCustomGrid` hat diese Methode keine Funktion. In abeleiteten Grid-Klassen wird hier der Zelleninhalt in die Zelle gezeichnet. In `TStringGrid` ruft diese Methode wiederum `DrawCellText` (siehe oben) auf.
411421
412422#### Erweiterung des Zeichenfunktionen in `TCustomDrawGrid`
413423
414424Wie man sieht, Zeichnet die Basisklasse `TCustomGrid` keinen Inhalt in das Grid. Dies geschieht in **`TCustomDrawGrid`**. Hier wird die Methode `DrawCell` folgendermaßen überschrieben.
415425
416426- **`DrawCell`** (override):
417427 - **`PrepareCanvas`**: Aufruf der von **`TCustomGrid`**geerbten Methode
418428 - **`DefaultDrawCell`** (virtual): Ist eine Ereignisbehandlung für `OnDrawCell` zugewiesen, wird diese Methode **nicht** ausgeführt. Sonst
419429 - **`DrawFillRect / DrawThemedCell`** (von `TCustomGrid`): Zeichnet den Hintergrund der Zelle. Ist `TitleStyle=tsNative`, wird der Hintergrund für fixierte Zellen mit `DrawThemedCell` gezeichnet.
420430 - **`DrawCellAutonumbering`** (virtual): Nur, wenn `goFixedAutonumbering in Options` wird in der ersten fixierten Spalte mit `TCustomGrid.DrawCellText` die Numerierung gezeichnet.
421431 - **`DrawColumnText`** (von `TCustomGrid`): Wird nur für die Zellen der Spaltenüberschriften ausgeführt. Siehe *Weitere Methoden zum Zeichnen in `TCustomGrid`*.
422432 - **`DrawTextInCell`** (von `TCustomGrid`): Wird nur für 'normale' (nicht fixierte) Zellen ausgeführt. Siehe *Weitere Methoden zum Zeichnen in `TCustomGrid`*.
423433 - **`DrawCellGrid`** (virtual): Zeichnet die Begrenzungen der Zelle.
424434
425435### Operationen
426436
427437#### Save and Retrieve Grid Content
428438
429439The **SaveToFile** procedure allows you save the TStringGrid format, attributes & values to a XML file. Previously you must set the SaveOptios property as follow:
430440
431-`soDesign:     Save & Load ColCount,RowCount,FixedCols,FixedRows,`\
432-`              ColWidths, RowHeights and Options (TCustomGrid)`\
433-`soPosition:   Save & Load Scroll Position, Row, Col and Selection (TCustomGrid)`\
434-`soAttributes: Save & Load Colors, Text Alignment & Layout, etc. (TCustomDrawGrid)`\
435-`soContent:    Save & Load Text (TCustomStringGrid)`
441+```text
442+soDesign: Save & Load ColCount,RowCount,FixedCols,FixedRows,
443+ ColWidths, RowHeights and Options (TCustomGrid)
444+soPosition: Save & Load Scroll Position, Row, Col and Selection (TCustomGrid)
445+soAttributes: Save & Load Colors, Text Alignment & Layout, etc. (TCustomDrawGrid)
446+soContent: Save & Load Text (TCustomStringGrid)
447+```
436448
437449The **LoadFromFile** procedure allows you to load into a StringGrid instance, attributes, formats & values, from a **XML** file. First, you must set some of this options of the SaveOptios property (on your TStringGrid instance) [[SaveOptions]]
438450
439-` soDesign:     Save & Load ColCount,RowCount,FixedCols,FixedRows,`\
440-`               ColWidths, RowHeights and Options (TCustomGrid)`\
441-` soPosition:   Save & Load Scroll Position, Row, Col and Selection (TCustomGrid)`\
442-` soAttributes: Save & Load Colors, Text Alignment & Layout, etc. (TCustomDrawGrid)`\
443-` soContent:    Save & Load Text (TCustomStringGrid)`
451+```text
452+ soDesign: Save & Load ColCount,RowCount,FixedCols,FixedRows,
453+ ColWidths, RowHeights and Options (TCustomGrid)
454+ soPosition: Save & Load Scroll Position, Row, Col and Selection (TCustomGrid)
455+ soAttributes: Save & Load Colors, Text Alignment & Layout, etc. (TCustomDrawGrid)
456+ soContent: Save & Load Text (TCustomStringGrid)
457+```
444458
445459------------------------------------------------------------------------
446460
447461**Beispiel:** 1) First Open a new project "Application". 2) Put an empty TStringGrid. 3) Put a TButton. 4) Put a TOpenDialog 5) Add the event OnCreate for the Form 5) Add the event OnClick for the Button
448462
449463``` pascal
450464unit Unit1;
451465
452466{$mode objfpc}{$H+}
453467
454468interface
455469
456470uses
457471 Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, Grids,
458472 Buttons, StdCtrls, XMLCfg;
459473
460474type
461475
462476 { TForm1 }
463477 TForm1 = class(TForm)
464478 StringGrid1: TStringGrid;
465479 Button1: TButton;
466480 OpenDialog1: TOpenDialog;
467481 procedure Button1Click(Sender: TObject);
468482 procedure Form1Create(Sender: TObject);
469483 private
470484 { private declarations }
471485 public
472486 { public declarations }
473487 end;
474488
475489var
476490 Form1: TForm1;
477491
478492implementation
479493
480494{ TForm1 }
481495
482496procedure TForm1.Form1Create(Sender: TObject);
483497begin
484498 //sets the SaveOptions at creation time of the form
485499 stringgrid1.SaveOptions := [soDesign,soPosition,soAttributes,soContent];
486500end;
487501
488502procedure TForm1.Button1Click(Sender: TObject);
489503begin
490504 //Ask if thew Execute method of the OpenDialog was launched
491505 //when this occurs, the user selects an XML file to Load
492506 //wich name was stored in the FileName prop.
493507
494508 if opendialog1.Execute then
495509 Begin
496510 //Clear the grid
497511 StringGrid1.Clear;
498512 //Load the XML
499513 StringGrid1.LoadFromFile(OpenDialog1.FileName);
500514 //Refresh the Grid
501515 StringGrid1.Refresh;
502516 End;
503517end;
504518
505519initialization
506520 {$I unit1.lrs}
507521
508522end.
509523```
510524
511525------------------------------------------------------------------------
512526
513527**Die Beispiel XML-Datei:** (Kopieren sie den text unterhalb in eine .txt Datei. Vergessen sie den XML header nicht :-))
514528
515529``` xml
516530''<?xml version="1.0"?>
517531<CONFIG>
518532 <grid version="3">
519533 <saveoptions create="True" position="True" content="True"/>
520534 <design columncount="2" rowcount="5" fixedcols="1" fixedrows="1" defaultcolwidth="64" defaultRowHeight="20">
521535 <options>
522536 <goFixedVertLine value="True"/>
523537 <goFixedHorzLine value="True"/>
524538 <goVertLine value="True"/>
525539 <goHorzLine value="True"/>
526540 <goRangeSelect value="True"/>
527541 <goDrawFocusSelected value="False"/>
528542 <goRowSizing value="False"/>
529543 <goColSizing value="False"/>
530544 <goRowMoving value="False"/>
531545 <goColMoving value="False"/>
532546 <goEditing value="False"/>
533547 <goTabs value="False"/>
534548 <goRowSelect value="False"/>
535549 <goAlwaysShowEditor value="False"/>
536550 <goThumbTracking value="False"/>
537551 <goColSpanning value="False"/>
538552 <goRelaxedRowSelect value="False"/>
539553 <goDblClickAutoSize value="False"/>
540554 <goSmoothScroll value="True"/>
541555 </options>
542556 </design>
543557 <position topleftcol="1" topleftrow="1" col="1" row="1">
544558 <selection left="1" top="1" right="1" bottom="1"/>
545559 </position>
546560 <content>
547561 <cells cellcount="10">
548562 <cell1 column="0" row="0" text="Title Col1"/>
549563 <cell2 column="0" row="1" text="value(1.1)"/>
550564 <cell3 column="0" row="2" text="value(2.1)"/>
551565 <cell4 column="0" row="3" text="value(3.1)"/>
552566 <cell5 column="0" row="4" text="value(4.1)"/>
553567 <cell6 column="1" row="0" text="Title Col2"/>
554568 <cell7 column="1" row="1" text="value(1.2)"/>
555569 <cell8 column="1" row="2" text="value(2.2)"/>
556570 <cell9 column="1" row="3" text="value(3.2)"/>
557571 <cell10 column="1" row="4" text="value(4.2)"/>
558572 </cells>
559573 </content>
560574 </grid>
561575</CONFIG>''
562576```
563577
564578------------------------------------------------------------------------
565579
566580--Raditz 21:06, 11 Jan 2006 (CET) from **ARGENTINA**
567581
568582### Grid Cell Editors
569583
570584The grid uses cell editors to change the content of cells. For a specilized grid like TStringGrid, the editor is the habitual single line text editor control, sometimes it's desireable to have other means to enter information. For example,
571585
572-`to call the open file dialog to find the location of a file so the user doesn't have to type the full path manually, if `
586+``` pascal
587+to call the open file dialog to find the location of a file so the user doesn't have to type the full path manually, if
588+```
573589
574590the text in the cell represents a date, it would be more friendly if we could popup a calendar so we can choose a specific date easily. Sometimes the information the user should enter in a cell is restricted to a limited list of words, in this case typing the information directly might introduce errors and validating routines might need to be implemented, we can avoid this by using a cell editor that present the user a list with only the legal values. This is also the case of generic grids like TDrawGrid where user have to have some kind of structure to hold the data that will be shown in the grid, in this situation, the information that is entered in the cell editor updates the internal structure to reflect the changes in the grid.
575591
576592#### Builtin cell editors
577593
578594The grids.pas unit already include some of the most used cell editors ready for use in grids, there is also the posibility to create new cell editors (custom cell editors) if the builtin editors are not appropiated for a specific tasks.
579595
580596The builtin cell editors are Button, Edit, and Picklist.
581597
582598#### Using cell editors
583599
584600Users can specify what editor will be used for a cell using one of two methods.
585601
5866021. Using a custom column and selecting the ButtonStyle property of column. In this method the user can select the style of
587603
588604the editor that will be shown. Available values are: cbsAuto, cbsEllipsis, cbsNone, cbsPickList, cbsCheckboxColumn
589605
5906061. Using OnSelectEditor grid event, here the user specify in the Editor parameter which editor to use for a cell identified
591607
592608for column aCol and row ARow in a TCustomDrawGrid derived grid or TColumn in TCustomDBGrid. For this purpose there is a useful public function of grids, EditorByStyle() that takes as parameter one of the following values: cbsAuto, cbsEllipsis, cbsNone, cbsPickList, cbsCheckboxColumn. This method takes precedence over the first one using custom columns. A Custom cell editor can be specified here. This event is also the place to setup the editor with values specific to the cell, row or column.
593609
594610#### Description of editor styles
595611
596612The following is the description of each editor style, they are enumeated values of type TColumnButtonStyle and so they are prefixed by 'cbs'. This type was used so it remains compatible with delphi's dbgrid.
597613
598614- **cbsAuto**
599615
600616
601617This is the default editor style for TCustomGrid derived grids. The actual editor class that will be used to edit the
602618
603619cell content, depends on several factors. For TCustomGrids it uses a TStringCelleditor class derived from TCustomMaskEdit,
604620
605-`this editor is speciallized to edit single line strings. It is then used in TStringGrid and TDrawGrid by default. When `
621+```text
622+this editor is speciallized to edit single line strings. It is then used in TStringGrid and TDrawGrid by default. When
623+```
606624
607625using Custom Columns and programmer filled the Column's PickList property, this behaves as if cbsPickList editor style was set. For a TCustomDBGrid that have a field of type boolean, behaves as if cbsCheckBoxColumn editor style was specified. This is the recomended value for Custom Cell Editors TODO: related OnEditingDone.
608626
609627- **cbsEllipsis**
610628
611629
612630This editor style is the most generic one. When used, a button appears in the editing cell, programmers could use the
613631
614632OnEditButtonClick grid event to detect when user has pressed the button and take any action was programmed for such cell. For example a programmer could use this editor style to pop up a calendar dialog so user can easily pick a specific date, another could be to show a file open dialog to find files, a calculator so user can enter the numeric result of calcs, etc.
615633
616634
617635OnEditButtonClick is just a notification, so to find out which cell a button has been clicked, take a look at grid.Row
618636
619637and grid.Col properties.
620638
621639
622640A DbGrid has specific properties to retrieve the active column or field and because this event occurs in active record,
623641
624642it could update the information in active field.
625643
626644
627645This editor style is implemented using TButtonCellEditor a direct descendant of TButton.
628646
629647- **cbsNone**
630648
631649
632650This editor style instruct the grid to not use any editor for a specific cell or column, it behaves then, as if the grid
633651
634652is readonly for such cell or column.
635653
636654- **cbsPickList**
637655
638656
639657Used to present the user a list of values that can be entered, this editor style is implemented using
640658
641659TPickListCellEditor a component derived from TCustomComboBox. The list of values that are shown, are filled in two ways depending of the method used to select the editor style.
642660
643661:#When using custom columns, programmers can enter a list of values using the column's PickList property. \[FOR BEGINNERS: TODO: exact procedure to edit the list\]
644662
645663:#In OnSelectEditor, programmers get the TPickListCellEditor instance using the function EditorByStyle(cbsPickList), an example would be: var Lst:TPickListCellEditor; begin \[...\] Lst:=TPickListCellEditor(EditorByStyle(cbsPickList)); Lst.clear; Lst.Items.add('One');lst.items.add('Two'); Editor:=Lst; end;
646664
647665
648666The value in a TStringGrid grid will automatically reflect the value selected, if necessary the programmer could detect
649667
650668the moment the value is selected by writing an event handler for grid's OnPickListSelect event, so additional steps can be taken for example, to process the new value. TODO: related OnEditingDone.
651669
652670- **cbsCheckboxColumn**
653671
654672
655673This editor style is at the moment only available in TDbGrid. This editor style can be useful when field content
656674
657675associated with the column are restricted to a pair of values, for example, yes-no, true-false, on-off, 1-0, etc. Instead of forcing the user to type the values for this kind of field in a StringCellEditor or to choose one from a list, cbsCheckboxColumn is used to modify the field content of a column by using a checkbox representation that user can toggle by using a mouse click or pressing the SPACE key.
658676
659677
660678If columns' ButtonStyle property is set to cbsAuto and DbGrid detects that the field associated to the column is a
661679
662680boolean field, then the grid use this editor style automatically, this automatic selection can be disabled or enabled using dbgrid's OptionsExtra property, setting dgeCheckboxColumn element to false disable this feature.
663681
664682
665683The values that are used to recognize the checked or unchecked states are set in column's properties ValueChecked and
666684
667685ValueUnchecked.
668686
669687
670688In any moment, the field value can be in one to three states: Unchecked, checked or grayed. Internally this states are
671689
672690identified by the following values of type TDBGridCheckBoxState: gcbpUnChecked, gcbpChecked and gcbpGrayed.
673691
674692
675693This editor style doesn't use real TCheckbox components to handle user interaction, the visual representation is given
676694
677695by three builtin bitmap images that corresponds to the possible states of checkbox. The used bitmaps can be customized by writing a handler for DBGrid event OnUserCheckboxBitmap, the handler of this event gets the state of the checkbox in parameter CheckedState of type TDbGridCheckboxState and a bitmap parameter that programmer could use to specify custom bitmaps.
678696
679697#### Beispiel: How to set a custom cell editor
680698
681699Siehe lazarus/examples/gridcelleditor/gridcelleditor.lpi
682700
683701### Wie scrollt man ein Grid in "Echtzeit" (während man den Scrollbalken per Maus bewegt)
684702
685703Wenn man ein Grid scrollt, indem man den Scrollbalken per Maus bewegt, dann scrollt das Grid per Default nicht "in Echtzeit", sondern erst, wenn man die Maus los lässt, "springt" das Grid an seine neue Position. Man kann ein scrollen "in Echtzeit" aktivieren, in dem man Option `goThumbTracking` hinzufügt.
686704
687705Beispiel:
688706
689707``` pascal
690708 StringGrid1.Options:=StringGrid1.Options + [goThumbTracking];
691709```
692710
693711Leider ist diese Option weder dokumentiert in `<lazarus-installdir>\lcl\grids.pas` (ver 2.0.6) noch in <https://lazarus-ccr.sourceforge.io/docs/lcl/grids/tgridoptions.html>
694712
695713## Todo
696714
697715- TInplaceEditor Unterstützung
698716
699717### Bekannte Probleme
700718
70171929-März-2005:
702720
703721- mouse autoedit
704722 - linux: clicking a selected cell doesn't trigger the autoedit function (the editor lost focus inmmediatelly)
705723 - windows: it should work only if the grid has the focus, if not it should focus and a second click should autoedit (cannot detect if the grid was previously focused or not)
706724- ColumnWidths: linux, windows: dbgrid start with default column widths instead of calculated ones (it's disabled because early canvas creation causes strange effects if the parent is a notebook page)
707725- Resizing Columns: linux, windows. Resizing a column should not hide the editor (specially in dbgrid if we are inserting)
708726- MouseWheel:
709727 - linux: mousewheel doesn't work as it should, (seems it's calling the default mousewheel handler)
710728 - windows: patch was sent.
711729- Double painting: Apparently dbgrid paints the cell background twice (once with fillrect and once in textRect)
712730- AutoFillColumns: sometimes the clientwidth is evaluated incorrectly (sometimes there are phantom scrollbars)
713731
714732---
715733*From the Free Pascal wiki, page "Grids Reference Page/de", as it stood on 2022-01-21 after a change by Slawek, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*
716734Category: Deutsch
717735Category: Tutorials/de

Back to history