Wolfgang Bures
Wolfgang Bures

Reputation: 707

Creating visual components at runtime with designtime template?

I am thinking of building objects with their own config UI that gets returned on TPanel. But playing around earlier I know that coding a visual design is quite tideous. Is there any way I can design a form in the IDE Designer and then load this "code" in my component?

TMyObject=class(TObject)
public
 procedure ShowCfg(APanel:TPanel);
end;

procedure TMyObject.ShowCfg(APanel:TPanel);

begin
  with TEdit.Create(APanel) do begin
    Left:=20;
    Top:=20;
    Width:=100;
    Height:=20;

  end;
end;

should be something like

procedure TMyObject.ShowCfg(APanel:TPanel);

begin
  ImportDFM(APanel);
end;

or a way to export a DFM into Delphi code?

Upvotes: 0

Views: 125

Answers (3)

DelphiCoder
DelphiCoder

Reputation: 2009

The GExperts plugin has a feature called "Components to Code". It copies all marked components on a form to the clipboard in Pascal code format, in which all properties with non-standard values are included.

Example form:

object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form1'
  ClientHeight = 204
  ClientWidth = 305
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -12
  Font.Name = 'Segoe UI'
  Font.Style = []
  TextHeight = 15
  object Panel1: TPanel
    Left = 0
    Top = 91
    Width = 305
    Height = 113
    Align = alBottom
    TabOrder = 0
    object Edit1: TEdit
      AlignWithMargins = True
      Left = 4
      Top = 4
      Width = 297
      Height = 23
      Align = alTop
      TabOrder = 0
    end
  end
end

Select the panel and the edit component, then do a right click and click "Components to Code" in the context menu. After that you should have the following code in the clipboard:

var
  Panel1: TPanel;
  Edit1: TEdit;

  Panel1 := TPanel.Create(Self);
  Edit1 := TEdit.Create(Self);

  Panel1.Name := 'Panel1';
  Panel1.Parent := Self;
  Panel1.Left := 0;
  Panel1.Top := 91;
  Panel1.Width := 305;
  Panel1.Height := 113;
  Panel1.Align := alBottom;
  Panel1.TabOrder := 0;
  Edit1.Name := 'Edit1';
  Edit1.Parent := Panel1;
  Edit1.AlignWithMargins := True;
  Edit1.Left := 4;
  Edit1.Top := 4;
  Edit1.Width := 297;
  Edit1.Height := 23;
  Edit1.Align := alTop;
  Edit1.TabOrder := 0;

Now do with it whatever you want...

Upvotes: 2

dummzeuch
dummzeuch

Reputation: 11217

There is an (rather old) project that was originally on Borland code central called "Custom Containers Pack".

https://blog.dummzeuch.de/delphi-custom-containers-pack/

This creates a component that is basically a panel with some controls on it. Not sure how useful this is nowadays.

Upvotes: 0

Uli Gerhardt
Uli Gerhardt

Reputation: 13981

Yes, use a frame. A frame is designable like a form and you can create an instance in code, see https://stackoverflow.com/a/1499646/1431618.

Upvotes: 3

Related Questions