Building Your First Custom Lazarus Component

Creating a Custom Lazarus Component

edit

1. Create a Package

edit
  1. In Lazarus, go to: Package → New Package
  2. Lazarus will ask for a folder.
  The folder name will become your package name.
  1. Save the package file (.lpk) inside this folder.
  2. Give the package a clear name (e.g., Tutorial).

2. Create or Add a Unit

edit

You need a Pascal unit that defines your component class.

Important:

  • The **Pascal unit filename** must match the **class name** (minus the leading "T").
 For example:  
 * Class name: TSimpleLED → Unit file: SimpleLED.pas
  • This ensures Lazarus and the package system can find your component correctly.

Option A – Create a new unit

edit
  • In the package editor:
    • Click Add → New Component (wizard).
    • Select a base class (e.g., TCustomControl).
    • Set the unit name (e.g., SimpleLED.pas).
    • Set the class name (e.g., TSimpleLED).
  • The wizard will create a template unit for you.

Option B – Add an existing unit

edit
  • In the package editor:
    • Click Add → Add Files from File System.
    • Choose an existing .pas file with your component code.

3. Write Your Component Code

edit

Inside your unit:

  • Define your class inheriting from an existing control or component.
  • Override needed methods (e.g., Paint).
  • Add properties/events.
type
  TSimpleLED = class(TCustomControl)
  private
    FState: Integer;
  public
    constructor Create(AOwner: TComponent); override;
  published
    property State: Integer read FState write FState;
  end;

4. Register Your Component

edit

At the end of your unit, add a Register procedure:

procedure Register;
begin
  RegisterComponents('Samples', [TSimpleLED]);
end;

Samples is the palette tab where it will appear.

5. Add the Unit to the Package

edit
  • Open the Package Editor for your package.
  • Click Add → Add Files from Editor if you just created the file.
  • Make sure the unit containing your component is listed as a Component file type (not just a dependency).

6. Install the Package

edit
  1. In the Package Editor, click Compile.
  2. Click Use → Install.
  3. Lazarus will recompile and restart.
  4. Your component should appear in the Component Palette under the category you chose.

7. (Optional) Add an Icon

edit
  • Create a .lrs resource file or use Lazarus Image Editor.
  • Link it in your unit:
{$R simpleled_icon.lrs}
  • Assign the icon to your component via Lazarus’s image list.

8. Test Your Component

edit
  • Start a new project.
  • Drop your component on a form.
  • Run the project and see if it behaves as intended.

Naming Conventions

edit
  • Folder name = package name (e.g., Tutorial)
  • Unit filename = Pascal file matching the class name without the "T" prefix
 * Example: Class TSimpleLED → File SimpleLED.pas
  • Class name = starts with T (e.g., TSimpleLED)