Difference between revisions of "TListBox/fr"

From Lazarus wiki
Jump to navigationJump to search
m (Fixed syntax highlighting)
 
(8 intermediate revisions by one other user not shown)
Line 8: Line 8:
  
 
= Remplir une ListBox =
 
= Remplir une ListBox =
 +
 
== Avec l'inspecteur d'objet ==
 
== Avec l'inspecteur d'objet ==
 +
 
* Sélectionnez le ListBox sur votre fiche avec un clic.
 
* Sélectionnez le ListBox sur votre fiche avec un clic.
 
* Allez dans l'inspecteur d'objet, dans l'onglet Propriétés et sur la propriété ''Items''.
 
* Allez dans l'inspecteur d'objet, dans l'onglet Propriétés et sur la propriété ''Items''.
Line 15: Line 17:
  
 
== Par code via un clic de bouton ==
 
== Par code via un clic de bouton ==
Add your form a [[TButton]] with the name ''btnFill'' and caption ''fill ListBox''. In the event handler ''OnClick'' of the button, you write the following code:
+
 
<source>
+
Ajoutez sur votre fiche une [[TButton/fr|TButton]] nommé ''btnFill'' et un intitulé ''Remplir la liste''. Dans le gestionnaire d'événement ''OnClick'' du bouton, vous écrivez le code suivant :
 +
 
 +
<syntaxhighlight lang=pascal>
 
procedure TForm1.btnFillClick(Sender: TObject);
 
procedure TForm1.btnFillClick(Sender: TObject);
 
begin
 
begin
Line 25: Line 29:
 
   ListBox1.Items.Add('Even a random number '+IntToStr(Random(100)));
 
   ListBox1.Items.Add('Even a random number '+IntToStr(Random(100)));
 
end;
 
end;
</source>
+
</syntaxhighlight>
  
 
= Affectation d'une StringList =
 
= Affectation d'une StringList =
Add your form a [[TButton]] with the name ''btnFill'' and caption ''fill ListBox''. In the event handler ''OnClick'' of the button, you write the following code:
+
Ajoutez sur votre fiche un [[TButton/fr|TButton]] nommé ''btnFill'' intitulé ''Remplir la liste''. Dans le gestionnaire d'événement ''OnClick'' du bouton, vous écrivez le code suivant :
<source>
+
 
 +
<syntaxhighlight lang=pascal>
 
procedure TForm1.btnFillClick(Sender: TObject);
 
procedure TForm1.btnFillClick(Sender: TObject);
 
var
 
var
Line 35: Line 40:
 
begin
 
begin
 
   myStringList:=TStringList.Create;              //Create my StringList
 
   myStringList:=TStringList.Create;              //Create my StringList
   myStringList.Add('This is the first line.');  //This add a row
+
   try
  myStringList.Add('This is the second first line.');
+
    myStringList.Add('This is the first line.');  //This add a row
  myStringList.Add('This is the third line.');
+
    myStringList.Add('This is the second first line.');
  myStringList.Add('etc.');
+
    myStringList.Add('This is the third line.');
  ListBox1.Items.Assign(myStringList);            //assign the ListBox1 the text content of my StringList
+
    myStringList.Add('etc.');
   myStringList.Free;                              //Free my StringList in memory  
+
    ListBox1.Items.Assign(myStringList);            //assign the ListBox1 the text content of my StringList
 +
   finally
 +
    myStringList.Free;                              //Free my StringList in memory  
 +
  end;
 
end;
 
end;
</source>
+
</syntaxhighlight>
 +
 
 +
= Ajout d'une chaîne =
 +
 
 +
* Etendez l'exemple [[TListBox/fr#Par_code_via_un_clic_de_bouton|Remplir un ListBox dans un clic de bouton]] en ajoutant un [[TEdit/fr|TEdit]] et un [[TButton/fr|TButton]] nommé ''btnAdd'' et intitulé ''Ajouter une chaîne''. Effacez la propriété ''Text''.
 +
* Dans le gestionnaire d'événement ''OnClick'' du bouton, vous écrivez le code suivant :
  
= Ajouter une chaîne =
+
<syntaxhighlight lang=pascal>
* Extend the example [[TListBox#by code in button click|Fill ListBox by code in button click]] to a [[TEdit]] and a [[TButton]] with the name ''btnAdd'' and caption ''add string''. Change of ''Edit1'' the property ''Text'' to "" - empty string.
 
* In the event handler ''OnClick'' of the button, you write the following code:
 
<source>
 
 
procedure TForm1.btnAddClick(Sender: TObject);
 
procedure TForm1.btnAddClick(Sender: TObject);
 
begin
 
begin
Line 53: Line 63:
 
   Edit1.Text:='';
 
   Edit1.Text:='';
 
end;  
 
end;  
</source>
+
</syntaxhighlight>
  
 
= Supprimer une chaîne =
 
= Supprimer une chaîne =
By default is set that you can select only one row in your list box. Do you want to select several of the lines in your ListBox, you would have the property ''MultiSelect'' to make ''True''.
+
Par défaut, vous pouvez seulement sélectionner une seule ligne dans la liste. En passant la propriété ''MultiSelect'' à True, vous pouvez sélectionner plusieurs lignes de la liste.
 +
 
 +
== Un ItemIndex ==
  
== A ItemIndex ==
+
* Etendez l'exemple [[TListBox/fr#Ajout_d.27une_cha.C3.AEne|Ajout d'une chaîne]] en ajoutant un [[TButton/fr|TButton]] nommé "btnDel" et intitulé "Supprimer la chaîne".
 +
* Dans le gestionnaire d'événement ''OnClick'' du bouton, vous écrivez le code suivant :
  
* Extend the example [[TListBox#Add string|Add string]] to a [[TButton]] with the name "btnDel" and caption "delete string".
+
<syntaxhighlight lang=pascal>
* In the event handler ''OnClick'' of the button, you write the following code:
 
<source>
 
 
procedure TForm1.btnDelClick(Sender: TObject);
 
procedure TForm1.btnDelClick(Sender: TObject);
 
begin
 
begin
Line 68: Line 79:
 
     ListBox1.Items.Delete(ListBox1.ItemIndex);
 
     ListBox1.Items.Delete(ListBox1.ItemIndex);
 
end;  
 
end;  
</source>
+
</syntaxhighlight>
  
 
== Toutes les chaînes sélectionnées ==
 
== Toutes les chaînes sélectionnées ==
* Extend the example [[TListBox#Add string|Add string]] to a [[TButton]] with the name "btnDel" and caption "delete string".
+
 
* In the event handler ''OnClick'' of the button, you write the following code:
+
* Etendez l'exemple [[TListBox/fr#Ajout_d.27une_cha.C3.AEne|Ajout d'une chaîne]] en ajoutant un [[TButton/fr|TButton]] nommé "btnDel" et intitulé "Supprimer la chaîne".
<source>
+
* Dans le gestionnaire d'événement ''OnClick'' du bouton, vous écrivez le code suivant :
 +
 
 +
<syntaxhighlight lang=pascal>
 
procedure TForm1.btnDelClick(Sender: TObject);
 
procedure TForm1.btnDelClick(Sender: TObject);
 
var
 
var
Line 83: Line 96:
 
         ListBox1.Items.Delete(i);              //...delete the item (String)
 
         ListBox1.Items.Delete(i);              //...delete the item (String)
 
end;
 
end;
</source>
+
</syntaxhighlight>
  
 
= ListBox dessinée par le propriétaire =
 
= ListBox dessinée par le propriétaire =
In general, it is advantageous to let the ListBox follow the  [http://en.wikipedia.org/wiki/Skin_%28computing%29 theme] set by the user. In some cases (for example, to program a game with a colorful surface), you can deviate from this standard and draw the control according to your own choice. You can try this now:
+
 
* You can modify the previous sample or create a new application with a TListBox ''ListBox1''.
+
En général, il est préférable de laisser le ListBox suivre le [http://en.wikipedia.org/wiki/Skin_%28computing%29 thème] défini par l'utilisateur. Dans certains cas (par exemple to programmer un jeu avec une surface toute colorée), vous pouvez vous détourner de ce standard et dessiner le contrôle selon votre propre choix. Vous pouvez essayer ceci maintenant :
* In the Object Inspector, change ''ListBox1'' property ''Style'' to ''lbOwnerDrawFixed''.
+
 
* With the Object Inspector, tab events, create the event handler for the event ''OnDrawItem'', by clicking on the button [...].
+
* Vous pouvez modifier l'exemple précédent ou créer une nouvelle application avec un TListBox ''ListBox1''.
* You add the following code to the handler:
+
* Dans l'inspecteur d'objet, modifiez la propriété ''Style'' de ''ListBox1'' vers ''lbOwnerDrawFixed''.
<source>
+
* Créez depuis l'inspecteur d'objet, onglet événements, le gestionnaire d'événement de ''OnDrawItem'', en cliquant sur le bouton [...].
 +
* Vous ajoutez le code suivant dans le gestionnaire :
 +
 
 +
<syntaxhighlight lang=pascal>
 
procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer;
 
procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer;
 
   ARect: TRect; State: TOwnerDrawState);
 
   ARect: TRect; State: TOwnerDrawState);
Line 107: Line 123:
 
   ListBox1.Canvas.TextRect(ARect, 2, ARect.Top+2, ListBox1.Items[Index]);  //Draw Itemtext
 
   ListBox1.Canvas.TextRect(ARect, 2, ARect.Top+2, ListBox1.Items[Index]);  //Draw Itemtext
 
end;
 
end;
</source>  
+
</syntaxhighlight>  
{{Note|'''Parameters of ListBoxDrawItem:'''<br><br>
+
{{Note|'''Paramètres deListBoxDrawItem:'''<br/><br/>
'''Control:'''<br> If multiple controls (E.g. multiple ListBoxes) access this event handle, you know which threw this event. You could in our example, instead of '''<code>ListBox1.Canvas.FillRect(ARect)</code>''' also '''<code>TListBox(Control).Canvas.FillRect(ARect)</code>''' write, where you should query still possible before, whether it is a TListBox:
+
'''Control:'''<br/> Si plusieurs contrôles (p.ex. de multiples ListBox) ont accès à ce gestionnaire, vous savez lequel a déclenché l'événement. Vous pouvez dans votre exemple au lieu de '''<code>ListBox1.Canvas.FillRect(ARect)</code>''' écrire aussi '''<code>TListBox(Control).Canvas.FillRect(ARect)</code>''', où vous devriez vérifier s'il s'agit d'un ListBox :
<source>
+
 
 +
<syntaxhighlight lang=pascal>
 
   if Control is TListBox then
 
   if Control is TListBox then
 
     TListBox(Control).Canvas.FillRect(ARect);     
 
     TListBox(Control).Canvas.FillRect(ARect);     
</source>
+
</syntaxhighlight>
'''Index:'''  
+
 
Specifies the item location, so you have access to the string '''<code><ListBox>.Items[Index]</code>'''.<br>
+
'''Index:''' <br/>
'''ARect:'''
+
Spécifie l'emplacement de l'article, vous avez ainsi accès à la chaîne '''<code><ListBox>.Items[Index]</code>'''.<br>
Describes the rectangle, which is necessary for drawing the background.<br>
+
'''ARect:''' <br/>
'''State:'''
+
Décrit le rectangle, ce qui est nécessaire pour le dessin du fond.<br/>
Status of the items, whether normal, focused, selected etc.
+
'''State:'''<br/>
 +
Etat de l'article, soit normal, mis en évidence (focus), sélectionné etc.
 
}}
 
}}
* Your example could look like:
+
* Votre exemple pourrait ressembler à ceci :
 
[[image:ListBoxBsp1.png]] -> [[image:ListBoxBsp2.png]]
 
[[image:ListBoxBsp1.png]] -> [[image:ListBoxBsp2.png]]
  
 
= Voir aussi =
 
= Voir aussi =
 +
 
* [[doc:lcl/stdctrls/tlistbox.html|Doc. TListBox]]  
 
* [[doc:lcl/stdctrls/tlistbox.html|Doc. TListBox]]  
 
* [[TDBListBox/fr|TDBListBox]] Ce composant rendu sensible aux données.
 
* [[TDBListBox/fr|TDBListBox]] Ce composant rendu sensible aux données.
  
 
{{LCL Components/fr}}
 
{{LCL Components/fr}}

Latest revision as of 07:51, 1 March 2020

Deutsch (de) English (en) suomi (fi) français (fr) 日本語 (ja)

Une TListBox tlistbox.png est un composant qui montre une liste défilable de chaîne (courtes) dans laquelle l'utilisateur peut en sélectionner une. Il est disponible depuis l'onglet Standard de la palette de composants.

Dans la TListBox, les chaînes sont enregistrées dans la propriété Items, qui est du type TStrings. donc vous pouvez affecter ou retirer des chaînes dans la ListBox comme dans TStringList ou son parent TStrings

Voici quelques exemples de comment utiliser une TListBox ListBox1 sur une fiche Form1 :

Remplir une ListBox

Avec l'inspecteur d'objet

  • Sélectionnez le ListBox sur votre fiche avec un clic.
  • Allez dans l'inspecteur d'objet, dans l'onglet Propriétés et sur la propriété Items.
  • Cliquez sur le bouton avec les trois points. L'éditeur de liste de chaînes s'ouvre.
  • Entrez votre texte et confirmez le tout avec OK.

Par code via un clic de bouton

Ajoutez sur votre fiche une TButton nommé btnFill et un intitulé Remplir la liste. Dans le gestionnaire d'événement OnClick du bouton, vous écrivez le code suivant :

procedure TForm1.btnFillClick(Sender: TObject);
begin
  ListBox1.Items.Clear;             //Delete all existing strings
  ListBox1.Items.Add('First line');
  ListBox1.Items.Add('Line with random number '+IntToStr(Random(100)));
  ListBox1.Items.Add('Third line');
  ListBox1.Items.Add('Even a random number '+IntToStr(Random(100)));
end;

Affectation d'une StringList

Ajoutez sur votre fiche un TButton nommé btnFill intitulé Remplir la liste. Dans le gestionnaire d'événement OnClick du bouton, vous écrivez le code suivant :

procedure TForm1.btnFillClick(Sender: TObject);
var
  myStringList: TStringList;
begin
  myStringList:=TStringList.Create;               //Create my StringList
  try
    myStringList.Add('This is the first line.');   //This add a row
    myStringList.Add('This is the second first line.');
    myStringList.Add('This is the third line.');
    myStringList.Add('etc.');
    ListBox1.Items.Assign(myStringList);            //assign the ListBox1 the text content of my StringList
  finally
    myStringList.Free;                              //Free my StringList in memory 
  end;
end;

Ajout d'une chaîne

procedure TForm1.btnAddClick(Sender: TObject);
begin
  ListBox1.Items.Add(Edit1.Text);
  Edit1.Text:='';
end;

Supprimer une chaîne

Par défaut, vous pouvez seulement sélectionner une seule ligne dans la liste. En passant la propriété MultiSelect à True, vous pouvez sélectionner plusieurs lignes de la liste.

Un ItemIndex

  • Etendez l'exemple Ajout d'une chaîne en ajoutant un TButton nommé "btnDel" et intitulé "Supprimer la chaîne".
  • Dans le gestionnaire d'événement OnClick du bouton, vous écrivez le code suivant :
procedure TForm1.btnDelClick(Sender: TObject);
begin
  if ListBox1.ItemIndex > -1 then    //Delete only when a string in the listbox is selected
    ListBox1.Items.Delete(ListBox1.ItemIndex);
end;

Toutes les chaînes sélectionnées

  • Etendez l'exemple Ajout d'une chaîne en ajoutant un TButton nommé "btnDel" et intitulé "Supprimer la chaîne".
  • Dans le gestionnaire d'événement OnClick du bouton, vous écrivez le code suivant :
procedure TForm1.btnDelClick(Sender: TObject);
var
  i: Integer;
begin
  if ListBox1.SelCount > 0 then                 //Delete only if at least one string in the list box is selected
    for i:=ListBox1.Items.Count - 1 downto 0 do //Iterate through all the items
      if ListBox1.Selected[i] then              //If selected...
        ListBox1.Items.Delete(i);               //...delete the item (String)
end;

ListBox dessinée par le propriétaire

En général, il est préférable de laisser le ListBox suivre le thème défini par l'utilisateur. Dans certains cas (par exemple to programmer un jeu avec une surface toute colorée), vous pouvez vous détourner de ce standard et dessiner le contrôle selon votre propre choix. Vous pouvez essayer ceci maintenant :

  • Vous pouvez modifier l'exemple précédent ou créer une nouvelle application avec un TListBox ListBox1.
  • Dans l'inspecteur d'objet, modifiez la propriété Style de ListBox1 vers lbOwnerDrawFixed.
  • Créez depuis l'inspecteur d'objet, onglet événements, le gestionnaire d'événement de OnDrawItem, en cliquant sur le bouton [...].
  • Vous ajoutez le code suivant dans le gestionnaire :
procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer;
  ARect: TRect; State: TOwnerDrawState);
var
  aColor: TColor;                       //Background color
begin
  if (Index mod 2 = 0)                  //Index tells which item it is
    then aColor:=$FFFFFF                //every second item gets white as the background color
    else aColor:=$EEEEFF;               //every second item gets pink background color
  if odSelected in State then aColor:=$0000FF;  //If item is selected, then red as background color
  ListBox1.Canvas.Brush.Color:=aColor;  //Set background color
  ListBox1.Canvas.FillRect(ARect);      //Draw a filled rectangle

  ListBox1.Canvas.Font.Bold:=True;      //Set the font to "bold"
  ListBox1.Canvas.TextRect(ARect, 2, ARect.Top+2, ListBox1.Items[Index]);  //Draw Itemtext
end;

Light bulb  Remarque: Paramètres deListBoxDrawItem:

Control:
Si plusieurs contrôles (p.ex. de multiples ListBox) ont accès à ce gestionnaire, vous savez lequel a déclenché l'événement. Vous pouvez dans votre exemple au lieu de ListBox1.Canvas.FillRect(ARect) écrire aussi TListBox(Control).Canvas.FillRect(ARect), où vous devriez vérifier s'il s'agit d'un ListBox :

  if Control is TListBox then
    TListBox(Control).Canvas.FillRect(ARect);

Index:
Spécifie l'emplacement de l'article, vous avez ainsi accès à la chaîne <ListBox>.Items[Index].
ARect:
Décrit le rectangle, ce qui est nécessaire pour le dessin du fond.
State:
Etat de l'article, soit normal, mis en évidence (focus), sélectionné etc.

  • Votre exemple pourrait ressembler à ceci :

ListBoxBsp1.png -> ListBoxBsp2.png

Voir aussi


Composant LCL
Onglet de palette Composants
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 • TTreeFilterEdit • TShortPathEdit • TLvlGraphControl
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