TStringGrid/ru

From Free Pascal wiki
Revision as of 12:59, 6 October 2018 by Useroflazarus (talk | contribs)
Jump to navigationJump to search

English (en) français (fr) русский (ru)



ENG: AT THE MOMENT THIS PAGE IS UNDER TRANSLATION.
RUS: В НАСТОЯЩИЙ МОМЕНТ СТРАНИЦА НАХОДИТСЯ В ПРОЦЕССЕ ПЕРЕВОДА.




--Zoltanleo 00:38, 6 October 2018 (CEST) Ввиду сложности дословного перевода текста с английского на русский слова, требующиеся по смыслу, но отсутствующие в английской версии, указаны в квадратных скобках.



TStringGrid tstringgrid.png это компонент с вкладки Additional tab палитры компонент Component Palette. Stringgrid обеспечивает табличное представление текстовой информации, которая может быть отредактирована.


Пример программы StringGrid

Чтобы создать этот пример, создайте новый проект в Lazarus. Выберите TStringGrid, чтобы добавить на форму, щелкнув компонент TStringGrid из области меню или окна компонента, затем нажмите на форму. В этом случае, как показано [на рисунке], также были выбраны и брошены на форму две кнопки TButton. В этом примере также необходимо выбрать компонент TOpenDialog и поместить его в форму.

TStringGrid02.png

Настройка столбцов и изменение их свойств

Столбцы могут быть легко добавлены щелчком правой кнопки мыши 'Columns: TGridColumns':

TStringGrid09.png

При выборе AddItem, новый столбец отобразится ниже. На вкладке Properties [в окне] Object Inspector отображается новый список Properties[(свойств)] и Events[(событий)], относящихся к этому столбцу. Отсюда имена столбцов задаются вместе с шириной. Когда закончите [добавлять столбцы], TreeView будет выглядеть так:

TStringGrid10.png

В этом примере имя Button1 было изменено на ButtonAddFiles, а имя Button2 было изменено на ButtonExit. StringGrid1 был растянут и кнопки были выровнены, как показано [на рисунке]. Обратите внимание, что есть строка и столбец другого цвета. Это состояние иллюстрирует концепцию, что эта строка и столбец могут быть [предназначена] для ярлыков заголовков соответствующего столбца или строки. Конечно, это состояние по умолчанию можно изменить, просто изменив 'FixedCols' или 'FixedRows' в Object Inspector.

TStringGrid03.png

В этом случае вы можете увидеть, что строки заголовков изменены, а компонент StringGrid1 привязан [к краям формы]. Это было достигнуто путем выполнения двух шагов. Первый включает в себя просмотр Object Inspector и выбор различных свойств по мере необходимости. Один шаг, который следует предпринять при запуске, - это внимательно посмотреть свойства по умолчанию. Когда вы внесли многочисленные изменения и вам нужно [отменить изменения] , [то сделать] это намного проще, если вы знаете, каково было их состояние в начале или на различных этапах [изменений]. Состояние этих свойств на последнем изображении иллюстрирует только одну фиксированную строку с заголовками столбцов. Это состояние иллюстрируется [следующим кодом]

                 FixedCols[0], 
                 FixedRows[1], 
                 HeaderHotZones[gzFixedCols], 
                 HeaderPushZones[gzFixedCols], 
                 Options[goFixedVertLine,goFixedHorzLine,goVertLine,goHorzLine,goRangeSelect,goSmoothScroll], 
                 TitleFont[Color[clPurple]], 
                 Style[fsBold], and 
                 RowCount = 1. 


После просмотра [результатов] вашей работы путем нажатия кнопки Run в Lazarus, возможно вы пожелаете изменить эти свойства. В этом случае были выбраны дополнительные свойства ColClickSorts и AlternateColor.

Второе, что можно сделать, это использовать Редактор Привязок (View -> AnchorEditor), чтобы привязать стороны StringGrid к основной формой.

Using Available Predefined Properties

At the bottom of the Object Inspector you can find useful information about the properties shown as seen in this example:

TStringGrid04.png

To add information to the StringGrid1 component, it is necessary to either add data from a TStream, LoadCVSFile, link the grid to a database or other similar actions. If linking to a database there are other components that should be considered like the TDBGrid. Other components such as the OpenDialog may also assist using methods like the LoadCVSFile. In many cases, it is necessary to either directly link data to given cells or ranges. In our example, we will use the InsertRowWithValues method. It is now necessary to add to the ButtonAddFiles an Event by clicking the Events tab of the Object Inspector and selecting the 'OnClick' event.

TStringGrid05.png

Program Block To Add Data To The StringGrid

By clicking on the OnClick the SourceEditor should have added a code block for the ButtonAddFilesClick procedure. To this you should add the following code:

 uses
   Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
   Grids, LazFileUtils, LazUtf8; 
 . . . .
 types
     { TForm1 }
 TForm1 = class(TForm)
   ButtonAddFiles : TButton;
 . . . .
   procedure ButtonAddFilesClick(Sender : TObject);
   procedure ButtonExitClick(Sender : TObject); 
 . . . .
 var
   Form1 : TForm1;
 implementation
 {$R *.lfm}
 { TForm1 }  
 procedure TForm1.ButtonExitClick(Sender : TObject);
 begin
   Close;
 end;
 .
 procedure TForm1.ButtonAddFilesClick(Sender : TObject);
 var
   FilePathName : string;
 begin
   if OpenDialog1.Execute then
     FilePathName := OpenDialog1.Filename;
   AddFilesToList(FilePathName);
 end; 

The procedure for closing the application is shown for completeness. In the ButtonAddFilesClick procedure we now use the OpenDialog1 and select the Execute method. If is shown in a if - then statement where the boolean property of execute is tested. This method by default is true so the following line then when executed gives the OpenDialog1 property 'FileName' to our variable 'FilePathName'.

In the last line of procedure a new procedure is shown for 'AddFilesToList'. We now need to create this procedure. In the type declaration under either 'Public' or 'Private' we need to add this new procedure. Under implementation, the code block for the procedure is created. In this example we are going to use the files of a DVD as can be seen in this illustration:

TStringGrid06.png

We want these files to be listed upon StringGrid1.

 Type
 . . . .
 private
 procedure AddFilesToList(FilePathName : String);
 . . . .
  procedure TForm1.AddFilesToList(FilePathName : String);
  var
    D, R, K : integer;
    FileName, FilePath : string;
    SearchRec1, SearchRec2 : TSearchRec;
    FileListVideo, FileListVst : TStringList;
  begin
    FileListVideo := TStringList.Create;
    FileListVst := TStringList.Create;
    FileName := ExtractFileName(FilePathName);
    FilePath := ExtractFilePath(FilePathName);
    FileListVideo := FindAllFiles(FilePath,'VIDEO_TS.*',true, faDirectory);
    R := 1;
    K := 0;
    for D := 0 to FileListVideo.Count -1 do
    begin
      if FindFirstUtf8(FilePath, faAnyFile and faDirectory, SearchRec1)=0 then
      begin
        repeat
          With SearchRec1 do
          begin
            FileName := ExtractFileName(FileListVideo.Strings[D]);
            K := FileSizeUtf8(FileListVideo.Strings[D]);
            StringGrid1.InsertRowWithValues(R,['0', FileName, IntToStr(K)]);
            R := R + 1;
        end;
      until FindNextUtf8(SearchRec1) <> 0;
    end;
    FindCloseUtf8(SearchRec1);
  end;
  .
  FileListVst := FindAllFiles(FilePath, 'VTS_*.*', true, faDirectory);
  K := 0;
  for D := 0 to FileListVst.Count -1 do
  begin
    if FindFirstUtf8(FilePath, faAnyFile and faDirectory,SearchRec2)=0 then
    begin
      repeat
        With SearchRec2 do
        begin
          FileName := ExtractFileName(FileListVst.Strings[D]);
          K := FileSizeUtf8(FileListVst.Strings[D]);
          StringGrid1.InsertRowWithValues(R,['1', FileName, IntToStr(K)]);
          R := R + 1;
         end;
       until FindNextUtf8(SearchRec2) <> 0;
     end;
     FindCloseUtf8(SearchRec2);
   end;
   StringGrid1.SortColRow(true, 1,1,StringGrid1.RowCount-1);
   FileListVst.Free;
   FileListVideo.Free;
 end;

This example uses the methods 'FindAllFiles' from 'FileUtils' and 'FindFirstUtf8', 'FindNextUtf8' and 'FindCloseUtf8' from 'LazFileUtils'.


CheckBox Column

One feature that can be very helpful in applications of the TStringGrid is having a checkbox column that either a user can click to signify their selection or used to show a certain state for some property. Adding this type of column is illustrated in this code. In the method 'InsertRowWithValues', the first column has '0' shown in the first part of the code when files containing 'VIDEO_TS*' are being selected. The '0' is illustrating the boolean state of a checkbox with 1 being checked and 0 unchecked. In selecting from the Object Inspector under StringGrid1-->Columns: TGridColumns-->0-Select in the TreeView, the ValueChecked and ValueUnchecked are shown. You can use other numbers, or have added code to change the state.

InsertRowWithValues Method

In this example the method InsertRowWithValues is used to add data to our StringGrid1 component. Each column's data is entered followed by a comma. It may be necessary to use typecasting functions to get data into a string format. Variables can be referenced, or simply shown as text as our '0' and '1' are for checkbox column.

TStringGrid08.png

Upon running our new application and clicking the button 'AddFiles' a dialog box opens allowing us to select file(s) to be added. If you click on a column header, StringGrid1 is sorted in the direction as shown by the green arrow. The result should be as shown in the following illustration:

TStringGrid07.png

Depending on your needs other properties can be selected to allow editing, resizing columns, etc.

См. также


Компоненты LCL
Вкладка Компоненты
Standard TMainMenu • TPopupMenu • TButton • TLabel • TEdit • TMemo • TToggleBox • TCheckBox • TRadioButton • TListBox • TComboBox • TScrollBar • TGroupBox • TRadioGroup • TCheckGroup • TPanel • TFrame • TActionList
Additional TBitBtn • TSpeedButton • TStaticText • TImage • TShape • TBevel • TPaintBox • TNotebook • TLabeledEdit • TSplitter • TTrayIcon • TControlBar • TFlowPanel • TMaskEdit • TCheckListBox • TScrollBox • TApplicationProperties • TStringGrid • TDrawGrid • TPairSplitter • TColorBox • TColorListBox • TValueListEditor
Common Controls TTrackBar • TProgressBar • TTreeView • TListView • TStatusBar • TToolBar • TCoolBar • TUpDown • TPageControl • TTabControl • THeaderControl • TImageList • TPopupNotifier • TDateTimePicker
Dialogs TOpenDialog • TSaveDialog • TSelectDirectoryDialog • TColorDialog • TFontDialog • TFindDialog • TReplaceDialog • TOpenPictureDialog • TSavePictureDialog • TCalendarDialog • TCalculatorDialog • TPrinterSetupDialog • TPrintDialog • TPageSetupDialog • TTaskDialog
Data Controls TDBNavigator • TDBText • TDBEdit • TDBMemo • TDBImage • TDBListBox • TDBLookupListBox • TDBComboBox • TDBLookupComboBox • TDBCheckBox • TDBRadioGroup • TDBCalendar • TDBGroupBox • TDBGrid • TDBDateTimePicker
Data Access TDataSource • TBufDataset • TMemDataset • TSdfDataSet • TFixedFormatDataSet • TDbf
System TTimer • TIdleTimer • TLazComponentQueue • THTMLHelpDatabase • THTMLBrowserHelpViewer • TAsyncProcess • TProcessUTF8 • TProcess • TSimpleIPCClient • TSimpleIPCServer • TXMLConfig • TEventLog • TServiceManager • TCHMHelpDatabase • TLHelpConnector
Misc TColorButton • TSpinEdit • TFloatSpinEdit • TArrow • TCalendar • TEditButton • TFileNameEdit • TDirectoryEdit • TDateEdit • TTimeEdit • TCalcEdit • TFileListBox • TFilterComboBox • TComboBoxEx • TCheckComboBox • TButtonPanel • TShellTreeView • TShellListView • TXMLPropStorage • TINIPropStorage • TIDEDialogLayoutStorage • TMRUManager • TStrHolder
LazControls TCheckBoxThemed • TDividerBevel • TExtendedNotebook • TListFilterEdit • TListViewFilterEdit • TLvlGraphControl • TShortPathEdit • TSpinEditEx • TFloatSpinEditEx • TTreeFilterEdit • TExtendedTabControl •
RTTI TTIEdit • TTIComboBox • TTIButton • TTICheckBox • TTILabel • TTIGroupBox • TTIRadioGroup • TTICheckGroup • TTICheckListBox • TTIListBox • TTIMemo • TTICalendar • TTIImage • TTIFloatSpinEdit • TTISpinEdit • TTITrackBar • TTIProgressBar • TTIMaskEdit • TTIColorButton • TMultiPropertyLink • TTIPropertyGrid • TTIGrid
SQLdb TSQLQuery • TSQLTransaction • TSQLScript • TSQLConnector • TMSSQLConnection • TSybaseConnection • TPQConnection • TPQTEventMonitor • TOracleConnection • TODBCConnection • TMySQL40Connection • TMySQL41Connection • TMySQL50Connection • TMySQL51Connection • TMySQL55Connection • TMySQL56Connection • TSQLite3Connection • TIBConnection • TFBAdmin • TFBEventMonitor • TSQLDBLibraryLoader
Pascal Script TPSScript • TPSScriptDebugger • TPSDllPlugin • TPSImport_Classes • TPSImport_DateUtils • TPSImport_ComObj • TPSImport_DB • TPSImport_Forms • TPSImport_Controls • TPSImport_StdCtrls • TPSCustomPlugin
SynEdit TSynEdit • TSynCompletion • TSynAutoComplete • TSynMacroRecorder • TSynExporterHTML • TSynPluginSyncroEdit • TSynPasSyn • TSynFreePascalSyn • TSynCppSyn • TSynJavaSyn • TSynPerlSyn • TSynHTMLSyn • TSynXMLSyn • TSynLFMSyn • TSynDiffSyn • TSynUNIXShellScriptSyn • TSynCssSyn • TSynPHPSyn • TSynTeXSyn • TSynSQLSyn • TSynPythonSyn • TSynVBSyn • TSynAnySyn • TSynMultiSyn • TSynBatSyn • TSynIniSyn • TSynPoSyn
Chart TChart • TListChartSource • TRandomChartSource • TUserDefinedChartSource • TCalculatedChartSource • TDbChartSource • TChartToolset • TChartAxisTransformations • TChartStyles • TChartLegendPanel • TChartNavScrollBar • TChartNavPanel • TIntervalChartSource • TDateTimeIntervalChartSource • TChartListBox • TChartExtentLink • TChartImageList
IPro TIpFileDataProvider • TIpHttpDataProvider • TIpHtmlPanel