Difference between revisions of "TComboBox/es"

From Free Pascal wiki
Jump to navigationJump to search
Line 91: Line 91:
  
 
{{Note|'''Parámetros de un ComboBoxDrawItem:'''<br><br>
 
{{Note|'''Parámetros de un ComboBoxDrawItem:'''<br><br>
'''Control:'''<br> If multiple controls (e.g. multiple ComboBoxes) access this event handle, sabes que control causó el evento. En nuestro ejemplo, en lugar de '<code>ComboBox1.Canvas.FillRect(ARect)</code>''' puedes además escribir '''<code>TComboBox(Control).Canvas.FillRect(ARect)</code>'''. However, you should still check in advance, whether it is a TComboBox:
+
'''Control:'''<br> If multiple controls (e.g. multiple ComboBoxes) access this event handle, sabes que control causó el evento. En nuestro ejemplo, en lugar de '''<code>ComboBox1.Canvas.FillRect(ARect)</code>''' puedes además escribir '''<code>TComboBox(Control).Canvas.FillRect(ARect)</code>'''. However, you should still check in advance, whether it is a TComboBox:
 
<source>
 
<source>
 
   if Control is TComboBox then
 
   if Control is TComboBox then

Revision as of 13:57, 20 July 2016

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

>> LCL Components >> TComboBox

Visión General

Esta página explica como utilizar el componente TComboBox. Cuando mencione hacer click en algo, a menos que diga explícitamente que haga click-derecho, siempre me referiré a realizar un click izquierdo en el elemento en cuestión.

Descripción

Es una combinación de una caja de edición (edit box) y un listado (soltar-abajo(drop-down) permitiendo una o varias opciones a ser escogidas.

Comp Standard TComboBox.png

Modo de uso

Para utilizar un TComboBox en unaform, simplemente lo seleccionas de la paleta de componentes Standardy a continuación lo ubicas en el formulario mediante un click en el mismo.

En el componente ComboBox, las strings se almacenan en la propiedad Items, que es del tipo TStrings. Por tanto puedes asignar o eliminar cadenas en el ComboBox como en un TStringList o su padre TStrings.


Aquí hay unos cuantos ejemplo de uso para combobox ComboBox1 en un formulario Form1:

Llenar el ComboBox

Mediante el Inspector de Objetos

  • Selecciona el ComboBox en tu formulario mediante un click.
  • Ve al Inspector de Objetos en la solapa Propiedades de la propiedad Items.
  • Haz Click en el pulsador que tiene los tres puntos ... que habrirá el editor de cadenas.
  • Escribe las entradas de texto que necesites y confirma el contenido con OK.

Mediante código cuando creas el formulario

  • Crea el manejador del evento OnCreate para el formulario haciendo click en el formulario, luego en el Inspector de Objetos vamos a la solapa events, selecciona el evento OnCreate y haz click en [...] o haz doble click en el pulsador dentro del formulario.
  • En el editor de código fuente ahora insertamos la sección de texto deseada, para nuestro ejemplo, escribiéndola como sigue:


procedure TForm1.FormCreate(Sender: TObject);  
begin
  ComboBox1.Text := 'Esto es un ComboBox';
  ComboBox1.Items.Clear;                  // Elimina todo el contenido previo.
  ComboBox1.Items.Add('Rojo');            // Añade la entrada del elemento 'Rojo'.
  ComboBox1.Items.Add('Verde');           // Añade la entrada del elemento 'Verde'.
  ComboBox1.Items.Add('Azul');            // Añade la entrada del elemento 'Azul'.
  ComboBox1.Items.Add('Color Aleatorio'); // Añade la entrada del elemento 'Color Aleatorio'.
end;


ComboBox 01.PNG


Hacer que suceda algo después de la selección

Como todos los componentes TComboBox también provee varios eventos que son llamados cuando el usuario lo utiliza. Para responder a un cambio en la selección de los elementos podemos utilizar el evento OnChange:

  • Para ello hacemos doble click sobre el componente ComboBox del formulario en el que estemos trabajando o bien escogemos el evento OnChange en el Inspector de Objetos y a continuación click en [...].
  • Con esto se crea el manejador del evento permintiéndonos insertar el código deseado. En nuestro ejemplo queremos cambiar el color del recuadro que muestra el elemento seleccionado:


procedure TForm1.ComboBox1Change(Sender: TObject);
begin
  case ComboBox1.ItemIndex of       // Caso de escoger el elemento de indice ?
    0: ComboBox1.Color:=clRed;                // 0 asigna clRed a Color   (Rojo)
    1: ComboBox1.Color:=clGreen;              // 1 asigna clGreen a Color (Verde)
    2: ComboBox1.Color:=clBlue;               // 2 asigna clBlue a Color  (Azul)
    3: ComboBox1.Color:=Random($1000000);     // 3 asigna un color aleatorio a Color
  end;
end;


  • Arranca tu aplicación, cada una de las selecciones cambia el color de fondo del rectángulo del ComboBox que nos muestra el elemento seleccionado.


ComboBox 02.PNG


Dibujado personalizado del ComboBox

En general, es ventajoso permitir al ComboBox mostrar el tema que ha escogido el usuario en sus configuraciones. En algunos casos (por ejemplo, para programar un juego con una superficie repleta de color), puedes desviarte de este estandar y dibujarlo acorde a tu propia elección. Así es como funciona:

Light bulb  Nota: Parámetros de un ComboBoxDrawItem:

Control:
If multiple controls (e.g. multiple ComboBoxes) access this event handle, sabes que control causó el evento. En nuestro ejemplo, en lugar de ComboBox1.Canvas.FillRect(ARect) puedes además escribir TComboBox(Control).Canvas.FillRect(ARect). However, you should still check in advance, whether it is a TComboBox:

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

Index: Epecifica la localización del elemento, de forma que se tenga acceso a la cadena <ComboBox>.Items[Index].
ARect: Describe el rectángulo, el cual es necesario para dibujar el fondo.
State: Estado de los elementos, nos indica cuando se encuentran en estado normal, enfocado, seleccionado, etc.


Dibujar un rectángulo relleno

  • Puedes modificar el ejemplo Fill ComboBox mediante cógigo cuando se crea el formulario.
  • Cambio para ComboBox1 en el Inspector de Objetos la propiedad Style al valor csOwnerDrawFixed.
  • Crea en el Inspector de Objetos el manejador de evento para el evento OnDrawItem, haciendo click en el pulsador [...].
  • Añade el siguiente código al manejador:
procedure TForm1.ComboBox1DrawItem(Control: TWinControl; Index: Integer;
  ARect: TRect; State: TOwnerDrawState);
var
  ltRect: TRect;

  procedure FillColorfulRect(aCanvas: TCanvas; myRect: TRect); // Pinta un color aleatorio
  // Rellena el rectángulo con un color aleatorio.
  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

Preceded image

En este ejemplo cargamos unas cuantas imágenes en un TImageList y las dibujamos en frente de los elementos del ComboBox. Es un ejemplo que generalmente solo muestra que puedes hacer en el: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


Return To: LCL Components  — Previous: TListBox Next: TScrollBar


LCL Components
Component Tab Components
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 • TTaskDialog • TOpenPictureDialog • TSavePictureDialog • TCalendarDialog • TCalculatorDialog • TPrinterSetupDialog • TPrintDialog • TPageSetupDialog
Data Controls TDBNavigator • TDBText • TDBEdit • TDBMemo • TDBImage • TDBListBox • TDBLookupListBox • TDBComboBox • TDBLookupComboBox • TDBCheckBox • TDBRadioGroup • TDBCalendar • TDBGroupBox • TDBGrid • TDBDateTimePicker
Data Access TDataSource • TCSVDataSet • TSdfDataSet • TBufDataset • TFixedFormatDataSet • TDbf • TMemDataset
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 • TJSONPropStorage • 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 • TMySQL57Connection • 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 • TIpHtmlDataProvider • TIpHttpDataProvider • TIpHtmlPanel
Virtual Controls TVirtualDrawTree • TVirtualStringTree • TVTHeaderPopupMenu


--Michl 22:14, 2 June 2014 (CEST)