TLabel

From Lazarus wiki
Jump to navigationJump to search

Deutsch (de) English (en) suomi (fi) français (fr) 日本語 (ja) русский (ru)

tlabel 150.png TLabel is a component that creates a text-item with one or more lines on another component. A TLabel is a descendant of TGraphicControl and is available under the Standard tab of the Component Palette.

Usage

A TLabel is one of the most basic components that can be used on forms. Most labels are the marking of other components, such as Edit fields, Memos, StringGrids and so on. TLabel provides a variety of events but they are not required in most cases.

You can add a label to your form, by clicking the TLabel (palette icon Abc) on the Standard component palette and place it with a click on your form.

Caption

To change the default caption of a newly inserted TLabel on a form, you can proceed as follows:

  • On your form with one click, select the TLabel.
  • Go on properties in the Object Inspector tab.
  • Select the property Caption and change it in the adjacent edit field.
  • In the same way, you can select the property Name and give the label a better name.

Changing the caption at run time

Of course, you can change the caption (the text displayed) during run time.

The following example demonstrates this:

  • Create a new GUI application with the form Form1. Add this form still a TButton Button1 and a TLabel Label1 by selecting the appropriate components on the Standard Component Tab and clicking on Form1 (the label should be above the button).
  • Create now a event handler for Button1, by simply double clicking on Button1.
  • Insert following lines of code in the OnClick event handler of Button1:
procedure TForm1.Button1Click(Sender: TObject);
const Cnt: Integer = 0;                     //Counter to determine how many times the button has been clicked
begin
  inc(Cnt);                                 //Increment the counter by 1
  Label1.Caption:='Button was clicked ' +   //Write the text on the caption of Label1
    IntToStr(Cnt) + ' times';
end;
  • Start your program and test the change of the label caption by clicking the button.

Text placement

Alignment

The horizontal position of the label text within the enclosing bounds is determined by the Alignment property:

  • taLeftJustify - the text begins at the left side of the control
  • taRightJustify - the text is moved to the right so that it ends at the right side of the control
  • taCenter - the text is centered horizontally within the width of the writing block.

In case of multi-lined or word-wrapped text (see below) the individual lines are positioned accordingly.

Layout

The Layout property refers to the vertical alignment of the caption text. It has the options

  • tlTop - the text begins at the top edge of the control
  • tlCenter - the text is centered vertically within the height of the control.
  • tlBottom - the text is moved downward so that it ends at the bottom edge of the control.

Delphi incompatibility for right-aligned labels

  • In Delphi, autosized labels with Alignment=taRightJustify but Anchors=[akLeft,...] grow to the left. In LCL they grow to to right, starting with Lazarus 2.3.0.
  • Reason: It wasn't possible to implement the behavior also for hidden labels without significant extensions in the LCL. The LCL has a different and more generic feature of control-based anchoring that delivers the same effect (see Remedy down), so it is not needed and wanted to double this feature and make the LCL code more complex and prone to bugs.
  • Remedy: Use the LCL anchoring to a secondary control. Anchor the right side of the label to another control. Then the autosized label will grow to the left but won't move to the right when the parent is resized like it is done with a simple akRight anchor without a reference control.

Multi-lined labels

Labels can be multi-lined in two ways

Hard-coded line-breaks

This can be achieved by inserting a LineEnding string as line-break indicator into the Caption text. As this is the default behaviour, no special property needs to be set for this to occur.

Example:

  Label1.Caption := 'This is line 1,' + LineEnding + 'and here is the line 2.';

WordWrap

Automatic wordwrap occurs when the Caption is longer than a given pixel length and when the Wordwrap property of the label has been switched to true. The length limit beyond which the text is wrapped can be defined in several ways:

  • by the width of the label's Parent when the label has the Align property set to taTop or taBottom
  • by Constraints.MaxWidth being non-zero
  • by anchoring to other controls
  • In Laz 4.99, a further restriction by the WordWrapLength has been introduced which is important especially when a label is rotated (see below). It becomes active when it has a positive, non-zero value.

Without such restrictions, the label width increases with the caption text, even when WordBreak=true.

Label rotation

A label can be rotated in any direction when the Orientation property of the label's Font is set to a non-zero value. The value given is given in units of 1/10 degree with positive numbers in counter-clockwise direction and with zero indicating the horizontal 3 o'clock direction.

When the WordWrap property is set to true for rotated text the position at which word-breaks are introduced is defined by the property WordWrapLength (in pixels).

AutoSize

When the AutoSize property of the label is set to true the Width and Height values are adjusted to fit the size of the text. In case of a rotated label the smallest rectangle is calculated which tightly encloses the text.

Advanced demo: A LinkLabel

Sometimes a click on a label should open a specific URL in the browser. Here are the steps required to open the Lazarus homepage by a label click:

  • Drop the label on the form, it will be named "LinkLabel" subsequently (set the Name property to "LinkLabel").
  • Set its Caption to "Lazarus".
  • Specify the URL of the Lazarus site in the Hint property, 'https://www.lazarus-ide.org/'. To see the hint at mouse-over, make sure that the label's ShowHint is true (or the form's ShowHint=true and the label's ParentHint=true).
  • Now provide an OnClick event handler to open this URL in the brower:
uses
  LCLIntf;  // for OpenURL

procedure TForm1.LinkLabelClick(Sender: TObject);
begin
  if Sender is TLabel then
    OpenURL(TLabel(Sender).Hint);
end;
  • Usually URL links are painted in blue color: In the Object Inspector, set the label's Font.Color to clBlue.
  • And when the mouse hovers over the label, the caption should become underlined. This can be achieved by providing handlers for the OnMouseEnter and OnMouseLeave events:
procedure TForm1.LinkLabelMouseEnter(Sender: TObject);
begin
  with (Sender as TControl).Font do
    Style := Style + [fsUnderline];
end;

procedure TForm1.LinkLabelMouseLeave(Sender: TObject);
begin
  with (Sender as TControl).Font do
    Style := Style - [fsUnderline];
end;
  • Finally, the mouse cursor should change to the "hand-point" shape when the mouse is over the label: Set the label's Cursor to crHandPoint.
  • The following code block summarizes all changes that can be made in the object inspector:
procedure TForm1.FormCreate(Sender: TObject);
begin
  LinkLabel.Caption := 'Lazarus';
  LinkLabel.Hint := 'https://www.lazarus-ide.org/';
  LinkLabel.ShowHint := true;
  LinkLabel.Font.Color := clBlue;
  LinkLabel.Cursor := crHandPoint;
  LinkLabel.OnClick := @LinkLabelClick;
  LinkLabel.OnEnter := @LinkLabelMouseEnter;
  LinkLabel.OnEnter := @LinkLabelMouseLeave;
end;

See also


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