Difference between revisions of "TComboBox/fr"

From Free Pascal wiki
Jump to navigationJump to search
Line 51: Line 51:
  
 
== ComboxBox dessiné par le propriétaire ==
 
== ComboxBox dessiné par le propriétaire ==
In general, it is advantageous to let the ComboBox show in the [http://en.wikipedia.org/wiki/Skin_%28computing%29 theme] the user has chosen in his settings. In some cases (for example, to program a game with a colorful surface), you can deviate from this standard and draw it according to your own choice. This is how this works:
+
En général, il est préférable de laisser le ComboBox 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.
  
{{Note|'''Parameters of ComboBoxDrawItem:'''<br><br>
+
{{Note|'''Paramètres of ComboBoxDrawItem:'''<br><br>
'''Control:'''<br> If multiple controls (e.g. multiple ComboBoxes) access this event handle, you know which control caused the event. In our example, instead of '''<code>ComboBox1.Canvas.FillRect(ARect)</code>''' you could also write '''<code>TComboBox(Control).Canvas.FillRect(ARect)</code>'''. However, you should still check in advance, whether it is a TComboBox:
+
'''Control:'''<br> Si plusieurs contrôles (p.ex. de multiples ComboBox) ont accès à ce gestionnaire, vous savez lequel a déclenché l'événement. Vous pouvez dans votre exemple au lieu de ComboBox1.Canvas.FillRect(ARect) écrire aussi TComboBox(Control).Canvas.FillRect(ARect). Néa,moins, vous devrez vérifier s'il s'agit d'un TComboBox :  
 
<syntaxhighlight>
 
<syntaxhighlight>
 
   if Control is TComboBox then
 
   if Control is TComboBox then

Revision as of 12:29, 11 August 2017

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

Un TComboBox tcombobox.png est la combinaison d'un champ de saisie et d'une liste (déroulante) permettant de choisir une des options proposées.

Emploi

Pour utiliser un TComboBox sur une fiche, vous pouvez simplement le sélectionner dans l'onglet Standard de la palette de composant et le placer en cliquant sur la fiche.

Dans le ComboBox, les chaînes sont enregistrées dans la propriété Items, de type TStrings. Ainsi, vous pouvez affecter ou supprimer des chaînes dans le ComboBox comme dans un TStringList ou son parent TStrings (NdT: cette dernière affirmation est partiellement vrai car TStrings est une classe abstraite).

Voici quelques petits exemple pour utiliser un ComboBox ComboBox1 sur une fiche Form1 :

* * *  A FINIR * * * (reprendre les textes de TListBox

Remplissage du ComboBox

par l'inspecteur d'objet

  • Sélectionnez le ComboBox 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 le code quand vous créez la fiche

  • Créez le gestionnaire d'événement OnCreate sur la fiche en cliquant sur votre fiche, utilisez l'inspecteur d'objet, l'onglet Evénements, choisissez l'événement OnCreate et cliquez sur le bouton [...] ou double-cliquez le bouton sur la fiche.
  • Dans l'éditeur de source, vous pouvez maintenant insérer le texte désiré, pour notre exemple, vous écrivez ce qui suit :
procedure TForm1.FormCreate(Sender: TObject);  
begin
  ComboBox1.Items.Clear;             //Delete all existing choices
  ComboBox1.Items.Add('Red');        //Add an choice
  ComboBox1.Items.Add('Green');
  ComboBox1.Items.Add('Blue');
  ComboBox1.Items.Add('Random Color');  
end;

Faire que quelque chose arrive après la sélection

Comme tous les composants, même le TComboBox fournit divers events, qui sont appelés quand l'utilsiateur agut sur le ComboBox. Pour répondre à une changement de sélection dans le ComboBox, vous pouvez utiliser l'événement OnChange :

  • Double-cliquez sur le ComboBox dans la fiche ou choisissez l'événement OnChange dans l'inspecteur d'objet et cliquez sur le bouton [...].
  • Le gestionnaire d'événement est créé, vous pouvez maintenant insérer votre code, dans notre exemple nous voulons changer la couleur de fond de la fiche :
procedure TForm1.ComboBox1Change(Sender: TObject);
begin
  case ComboBox1.ItemIndex of  //what entry (which item) has currently been chosen
    0: Color:=clRed;
    1: Color:=clGreen;
    2: Color:=clBlue;
    3: Color:=Random($1000000);
  end;
end;
  • Démarrez votre application, la sélection change la couleur de fond de la fiche.

ComboxBox dessiné par le propriétaire

En général, il est préférable de laisser le ComboBox 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.

Light bulb  Remarque: Paramètres of ComboBoxDrawItem:

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

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

Index: Specifies the item location, so you have access to the string <ComboBox>.Items[Index].
ARect: Describes the rectangle, which is necessary for drawing the background.
State: Status of the items, whether normal, focused, selected etc.

Dessiner une rectangle rempli

  • You can modify the example Fill ComboBox by code when you create the form.
  • Change from ComboBox1 in the Object Inspector the property Style to csOwnerDrawFixed.
  • Create in the Object Inspector the event handler for the event OnDrawItem, by clicking on the button [...].
  • Add the following code to the handler:
procedure TForm1.ComboBox1DrawItem(Control: TWinControl; Index: Integer;
  ARect: TRect; State: TOwnerDrawState);
var
  ltRect: TRect;

  procedure FillColorfulRect(aCanvas: TCanvas; myRect: TRect);              //paint random color
  // Fills the rectangle with random colours
  var
    y: Integer;
  begin
    for y:=myRect.Top to myRect.Bottom - 1 do begin
      aCanvas.Pen.Color:=Random($1000000);
      aCanvas.Line(myRect.Left, y, myRect.Right, y);
    end;
  end;

begin
  ComboBox1.Canvas.FillRect(ARect);                                         //first paint normal background
  ComboBox1.Canvas.TextRect(ARect, 22, ARect.Top, ComboBox1.Items[Index]);  //paint item text 

  ltRect.Left   := ARect.Left   + 2;                                        //rectangle for color
  ltRect.Right  := ARect.Left   + 20;
  ltRect.Top    := ARect.Top    + 1;
  ltRect.Bottom := ARect.Bottom - 1;

  ComboBox1.Canvas.Pen.Color:=clBlack;
  ComboBox1.Canvas.Rectangle(ltRect);                                       //draw a border 

  if InflateRect(ltRect, -1, -1) then                                       //resize rectangle by one pixel
    if Index = 3 then
      FillColorfulRect(ComboBox1.Canvas, ltRect)                            //paint random color
    else begin
      case Index of
        0: ComboBox1.Canvas.Brush.Color := clRed;
        1: ComboBox1.Canvas.Brush.Color := clGreen;
        2: ComboBox1.Canvas.Brush.Color := clBlue;
      end;
      ComboBox1.Canvas.FillRect(ltRect);                                    //paint colors according to selection
    end;
end;
  • Your example might look like:

ComboBoxBsp1.png -> ComboBoxBsp2.png

Image en marge

In this example, we load a few images in a TImageList and draw them in front of the items in the combobox. It is a simple example which only generally show what you can do. I don't run explicitly details, such as checking, whether the corresponding image exists etc. in this example. This should be done by you depending on the need.

  • Create an application analogous example Fill ComboBox by code when you create the form.
  • Change from ComboBox1 in the Object Inspector the property Style to csOwnerDrawFixed.
  • Add a TImageList from the component palette Common controls on your form.
  • The Height and Width of 16 pixels is preset in ImageList1. We allow this. To fit neatly the images into our combo box, we make the property ItemHeight from ComboBox1 to 18 in the Object Inspector.
  • Add four images in the ImageList:
    • Doubleclick ImageList1 or leftclick ImageList1 and select ImageList Editor....
    • Click on Add and select an image (see <Lazarus directory>/images/... there are various images or icons in 16x16px size).
    • Have you added four images, confirm your work with [OK].
  • Create in the Object Inspector the event handler for the event OnDrawItem, by clicking on the button [...].
  • Add the following code to the handler:
procedure TForm1.ComboBox1DrawItem(Control: TWinControl; Index: Integer;
  ARect: TRect; State: TOwnerDrawState);
begin
  ComboBox1.Canvas.FillRect(ARect);                                         //first paint normal background
  ComboBox1.Canvas.TextRect(ARect, 20, ARect.Top, ComboBox1.Items[Index]);  //paint item text 
  ImageList1.Draw(ComboBox1.Canvas, ARect.Left + 1, ARect.Top + 1, Index);  //draw image according to index on canvas
end;
  • Your example might look like:

ComboBoxBsp1.png -> ComboBoxBsp3.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