Dynamic/runtime Controls: Did I set it up correctly? lazarus / 21-General ---------------------------------------------------------------------- local-vision · 2021-02-10 17:56 Did I set it all up correctly?...Let me know please. So I made a small application that uses a Form with a Panel. At runtime I create controls. These controls are place onto the Panel which serves as the parent control. I can also delete created controls during runtime. I have placed the Constructor Create and Event routines/methods in a separate unit. In my view all is ShivaCorrect, meaning that what is created and maintained is also properly destroyed. During runtime I can free any runtime created Controls and all other controls are freed by the parent control when the application closes. Hopefully No memory leaks? Did I do this correctly? Any input/comment is much appreciated! Here is the code for the main Form: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i unit Unit1; {$mode objfpc}{$H+} interface uses  Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls; type   { TForm1 }   TForm1 = class(TForm)    Button1: TButton;    Button2: TButton;    Panel1: TPanel;    procedure Button1Click(Sender: TObject);    procedure Button2Click(Sender: TObject);  private   public   end; var  Form1: TForm1; implementation {$R *.lfm} { TForm1 } uses RTCRoutines; procedure TForm1.Button1Click(Sender: TObject);begin  { Panel1 is passed as the Parent Control.    The runtime control  is freed when Panel1 is freed? }  TDyn.CreateButton(Panel1);end; procedure TForm1.Button2Click(Sender: TObject);begin  { Panel1 is passed as the Parent Control.    The runtime control  is freed when Panel1 is freed? }  TDyn.CreateLabel(Panel1);end; end.   And here is the code for the Create/Event routines: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i unit RTCRoutines; {$mode objfpc}{$H+} interface uses  Classes, SysUtils, Forms, StdCtrls, Dialogs, Controls; {  Is all of this Shiva Correct? IOW am I creating, maintaining and   destroying the dynamic controls correctly? The is no destructor declared   as the Panel of the main Form frees the dynamnic control when it is freed?  } type  TDyn = Class  private    procedure MouseUp(Sender: TObject; Button: TMouseButton;Shift: TShiftState; X, Y: Integer);  public    Constructor CreateButton(WinCntrl:TWinControl); overload;    Constructor CreateLabel(WinCntrl:TWinControl); overload;  end; implementation procedure TDyn.MouseUp(Sender: TObject; Button: TMouseButton;Shift: TShiftState; X, Y: Integer);begin  if (Sender is TButton) then  begin    TButton(Sender).Free;    exit;  end;   if Sender is TLabel then  begin    TLabel(Sender).Free;  end;end; constructor TDyn.CreateButton(WinCntrl:TWinControl);var dynButton: TButton;begin  inherited;   dynButton            := TButton.Create(WinCntrl);   dynButton.Caption    := 'Button Caption';  dynButton.Parent     := WinCntrl;  dynButton.AutoSize   := True;  dynButton.SetBounds(Random(WinCntrl.Width), Random(WinCntrl.Height), 72, 24);   dynButton.OnMouseUp  :=@MouseUp;end; constructor TDyn.CreateLabel(WinCntrl:TWinControl);var dynLabel: TLabel;begin  inherited;   dynLabel              := TLabel.Create(WinCntrl);   dynLabel.Caption      := 'Label Caption';  dynLabel.Parent       := WinCntrl;  dynLabel.AutoSize     := True;  dynLabel.SetBounds(Random(WinCntrl.Width), Random(WinCntrl.Height), 60, 24);   dynLabel.OnMouseUp    :=@MouseUp;end; end. ---------------------------------------------------------------------- lucamar · 2021-02-10 19:32 There doesn't seem to be anything wrong, though I'd place the event handlers in the form unit and pass their address to the CreateXXX routines. In fact, since all the code deals with UI, I would put all of it in the form's unit and forget all about TDyn. But that is a personal preference for clean(er) architectures; there is nothing esentially "wrong" with your code. ---------------------------------------------------------------------- howardpc · 2021-02-10 19:45 There are several things wrong! You don't need the TDyn class at all, which is not freed, so creates a memory leak. The positioning code will also lead to clipped controls. Try something like this, which still needs more intelligent positioning code: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i unit Unit1; {$mode objfpc}{$H+} interface uses  Classes, Forms, Controls, StdCtrls, ExtCtrls; type   { TForm1 }   TForm1 = class(TForm)    CreateButtonButton: TButton;    CreateLabelButton: TButton;    Panel1: TPanel;    procedure CreateButtonButtonClick(Sender: TObject);    procedure CreateLabelButtonClick(Sender: TObject);    procedure FormCreate(Sender: TObject);  private    procedure ButLabMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);  end; var  Form1: TForm1; implementation {$R *.lfm} procedure TForm1.ButLabMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);begin  if Sender is TButton then    Application.ReleaseComponent(TButton(Sender))  else if Sender is TLabel then    Application.ReleaseComponent(TLabel(Sender));end; procedure TForm1.CreateButtonButtonClick(Sender: TObject);begin  with TButton.Create(Panel1) do    begin      Caption := 'Button Caption';    AutoSize := True;      SetBounds(Random(Succ(Panel1.Width)), Random(Succ(Panel1.Height)), 72, 24);      OnMouseUp := @ButLabMouseUp;      Parent := Panel1;    end;end; procedure TForm1.CreateLabelButtonClick(Sender: TObject);begin  with TLabel.Create(Panel1) do    begin      Caption := 'Label Caption';    SetBounds(Random(Succ(Panel1.Width)), Random(Succ(Panel1.Height)), 60, 24);      OnMouseUp := @ButLabMouseUp;      Parent := Panel1;    end;end; procedure TForm1.FormCreate(Sender: TObject);begin  Randomize;end; end. ---------------------------------------------------------------------- local-vision · 2021-02-10 21:39 Lucamar and HowardPC thanks for the quick response and info! Keeping the events in the main form is typically a better idea. This as these are GUI related routines/methods. However, having these routines in a separate unit rather than the main form is much desired. For one thing I already have many 1000s of lines that will be in the main form. Having things in separate units making things easy to replace/exchange/overview.  howardpc Application.Releasecomponent  and  TButton.Create(wincontrol) are indeed a more appropriate to use. howardpc you mentioned that memory leak would occur since TDyn is not freed. How would I do this? Or do you have other approach how to have these dynamic routines used within separate unit? Many thanks. ---------------------------------------------------------------------- howardpc · 2021-02-10 23:13 Here is one approach to moving functionality to a separate unit. Using a record as a container avoids the need for memory management, creating and freeing a TDyn class (though that is simple enough to do - you just need to remember to clean up any classes you manually instantiate). Have a separate unit such as this: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i unit UDyn; {$mode objfpc}{$H+}{$ModeSwitch advancedrecords} interface uses  Classes, Controls, StdCtrls; type   RDyn = record  private    FParent: TWinControl;    procedure MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);  public    procedure Init(aParent: TWinControl);    function CreateButton(const aCaption: String): TButton;    function CreateLabel(const aCaption: String): TLabel;  end; implementation uses  Forms; function RDyn.CreateButton(const aCaption: String): TButton;begin  Result := TButton.Create(FParent);  Result.Caption := aCaption;  Result.SetBounds(Random(Succ(FParent.Width)), Random(Succ(FParent.Height)), 72, 24);  Result.AutoSize := True;  Result.OnMouseUp := @MouseUp;  Result.Parent := FParent;end; function RDyn.CreateLabel(const aCaption: String): TLabel;begin  Result := TLabel.Create(FParent);  Result.Caption := aCaption;  Result.SetBounds(Random(Succ(FParent.Width)), Random(Succ(FParent.Height)), 72, 24);  Result.OnMouseUp := @MouseUp;  Result.Parent := FParent;end; procedure RDyn.Init(aParent: TWinControl);begin  Randomize;  FParent := aParent;end; procedure RDyn.MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);begin  if Sender is TButton then    Application.ReleaseComponent(TButton(Sender))  else if Sender is TLabel then    Application.ReleaseComponent(TLabel(Sender));end; end.You change your main unit then to be something like this: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i unit Unit1; {$mode objfpc}{$H+} interface uses  Classes, Forms, Controls, StdCtrls, ExtCtrls, UDyn; type   TForm1 = class(TForm)    CreateButtonButton: TButton;    CreateLabelButton: TButton;    Panel1: TPanel;    procedure CreateButtonButtonClick(Sender: TObject);    procedure CreateLabelButtonClick(Sender: TObject);    procedure FormCreate(Sender: TObject);  private    Dyn: RDyn;  end; var  Form1: TForm1; implementation {$R *.lfm} procedure TForm1.CreateButtonButtonClick(Sender: TObject);begin  Dyn.CreateButton('Button Caption');end; procedure TForm1.CreateLabelButtonClick(Sender: TObject);begin  Dyn.CreateLabel('Label Caption');end; procedure TForm1.FormCreate(Sender: TObject);begin  Dyn.Init(Panel1);end; end. ---------------------------------------------------------------------- local-vision · 2021-02-11 01:26 Did not realize that I could declare a record in that way. Fantastic! So much more clean and sensible code. As a record I dont have to worry about any freeing things at the end. Since your init method binds the panel parent to all child controls. Based on your previous posting I went about creating the class and destroying it as follows: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i unit Unit1; {$mode objfpc}{$H+} interface uses  Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls; type   { TForm1 }   TForm1 = class(TForm)    Button1: TButton;    Button2: TButton;    Memo1: TMemo;    Panel1: TPanel;    procedure Button1Click(Sender: TObject);    procedure Button2Click(Sender: TObject);    procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);    procedure FormCreate(Sender: TObject);  private   public   end; var  Form1: TForm1; implementation {$R *.lfm} { TForm1 } uses RTCRoutines; var DynamicCntrls:TDynCtrl; procedure TForm1.Button1Click(Sender: TObject);begin  DynamicCntrls.CreateButton(Panel1);end; procedure TForm1.Button2Click(Sender: TObject);begin  DynamicCntrls.CreateButton(Panel1);end; procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);begin  DynamicCntrls.Free;end; procedure TForm1.FormCreate(Sender: TObject);begin  DynamicCntrls:=TDynCtrl.Create;end; end.                                       And then I added the destructor in the RTCRoutines unit Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i type  TDynCtrl = Class  private    procedure MouseUp(Sender: TObject; Button: TMouseButton;Shift: TShiftState; X, Y: Integer);  public    Constructor CreateButton(WinCntrl:TWinControl); overload;    Constructor CreateLabel(WinCntrl:TWinControl); overload;    destructor Destroy; override;  end; implementation destructor TDynCtrl.Destroy;begin  inherited;end;       But again your approach in using a record type negates having to use a class. So I will record. Thanks again! ---------------------------------------------------------------------- egsuh · 2021-02-11 03:50 Even though you separate the functions from the unit containing form, aren't global functions enough?  I don't see any reason for containing them in class or record. Anyway they need to allocate/deallocate memories, while what is needed is just function/procedure. If containing them within class/record is definitely necessayr, I will check the possibility of defining tham as class methods so that creating any instance of the class is not necessary. ---------------------------------------------------------------------- local-vision · 2021-02-11 12:32 Hi Egsuh, Thanks for your input. It seems that using stand-alone "global functions" from a separate unit as you state are not sufficient. These were tried and failed at the event assignment declarations. The runtime components need to have some inheritance that goes beyond just parenting them to a panel control such a panel on the main form. In fact when attempting to compile the record approach as provided by howardpc I get a compiler error at the event statement: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i Result.OnMouseUp:=@RDyn.MouseUp;  The error relates to the types being incompatible. Also I am confused why in Delphi (If I remember correctly) you do not need to use @ while in Lazarus you do. Again, I will also get the same compiler error if I use global functions. That is why I tried using class approach. I have checked the class version that I presented in my previous post. This works and after heaptrc I discovered no memory leaks. ---------------------------------------------------------------------- howardpc · 2021-02-11 13:24 To use advanced records in {$Mode objfpc} you need to add the {$ModeSwitch advancedrecords} - see the code I offered earlier. Classic Pascal records cannot contain methods. The requirement for @ when assigning method event types is nothing to do with Lazarus. It is merely that FPC's objfpc mode  (deliberately) adopts a stricter syntax, requiring the "@". If you use {Mode Delphi} there is no requirement for "@" - in fact you must not use it, just as in Delphi itself. In Delphi mode the compiler does the equivalent internally of adding the @ for you. ---------------------------------------------------------------------- egsuh · 2021-02-11 13:28 Ah.. right. I did not notice you are assigning     dynButton.OnMouseUp  :=@MouseUp; In this case, OnMouseUp is a variable of method type (procedure of object), and then the right hand side of the assignment must be a method of object (i.e. class).  Haven't checked advanced record's method will do. But, can't we use class method there? This is my question. ---------------------------------------------------------------------- local-vision · 2021-02-11 17:21 Hi Egsuh, Correct, we can use class method here for the event assignment, and that works. Hi Howardpc, Also correct, as soon as I saw your code with methods being used in records I looked it up. I used your compiler directive {$ModeSwitch advancedrecords} as you presented. However, the (advanced) record approach does not work with events assignment. At least, I am not able to get it to work. The compiler error reads : Incompatible Types and refers to the event assignment as the error. ---------------------------------------------------------------------- howardpc · 2021-02-11 18:44 Is the error message not more specific than "incompatible types"? Usually the compiler details the incompatibilities it finds. However, perhaps this functionality depends on a recent FPC. I compiled and ran the code I showed using a recent trunk version with no problem. ---------------------------------------------------------------------- local-vision · 2021-02-11 19:44 Hmm. I am using the most recent versions of Lazarus and FPC. The full error message is: Compile Project, Target: project1: Exit code 1, Errors: 2 rtcroutines.pas(34,23) Error: Incompatible types: got "
" expected "" rtcroutines.pas(43,23) Error: Incompatible types: got "" expected "" ---------------------------------------------------------------------- howardpc · 2021-02-11 20:03 Did you declare your MouseUp procedure as a method of the advanced record? It cannot be a stand-alone procedure, it must be a "procedure of object" i.e. a method. ---------------------------------------------------------------------- local-vision · 2021-02-11 20:30 The code I used is a copy paste from your post of: Reply #4 on: Today at 12:13:09 am Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i unit UDyn; {$mode objfpc}{$H+}{$ModeSwitch advancedrecords} interface uses  Classes, Controls, StdCtrls; type   RDyn = record  private    FParent: TWinControl;    procedure MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);  public    procedure Init(aParent: TWinControl);    function CreateButton(const aCaption: String): TButton;    function CreateLabel(const aCaption: String): TLabel;  end; implementation   So yes, the MouseUp procedure is declared as a method of the advanced record. ---------------------------------------------------------------------- howardpc · 2021-02-12 13:13 I don't know what to suggest, since the code compiles and runs flawlessly here (Linux Mint, 64-bit). Perhaps a Run -> Clean up and Build... helps? ---------------------------------------------------------------------- egsuh · 2021-02-13 01:53 Hi local-vision, This subject is quite interesting to me and I confirmed it myself. Following codes works fine. I defined all procedures/functions as "class method", and this works. This means I do not need instantiate the class, and this has wide applicability to my projects.  Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   { TMethods }   TMethods = class    class procedure MouseUp(Sender: TObject; Button: TMouseButton;            Shift: TShiftState; X, Y: Integer);     class function CreateButton(Parent: TWinControl): TButton;    class function CreateLabel(Parent: TWinControl): TLabel;  end; var  Form1: TForm1; implementation { TMethods } class procedure TMethods.MouseUp(Sender: TObject; Button: TMouseButton;  Shift: TShiftState; X, Y: Integer);begin   showmessage('your mouse is up');end; class function TMethods.CreateButton(Parent: TWinControl): TButton;begin   Result:= TButton.Create(Parent);   Result.Parent := parent;   Result.Caption := 'auto-created';   Result.OnMouseUp:= MouseUp;    // if defined as record, error occurs here.           // I do not need @ prefix as this is under {$mode delphi}. end; class function TMethods.CreateLabel(Parent: TWinControl): TLabel;begin   Result:= TLabel.Create(Parent);   Result.Parent := parent;   Result.OnMouseUp:= MouseUp;end; { TForm1 } procedure TForm1.Button2Click(Sender: TObject);var   BTn2: TButton;begin   btn2 := TMethods.CreateButton(notebook1.Page[0]);end; @howardpc, I was impressed by ingenuity of your idea collecting the methods within record. I tested it but it failed to be compiled (Windows 10 - 32 bit).  Following is the compilor's error message. Quotebasetest_u1.pas(86,23) Error: Incompatible types: got "TMethods.MouseUp(TObject;TMouseButton;TShiftState;LongInt;LongInt);" expected "" ---------------------------------------------------------------------- howardpc · 2021-02-13 09:16 This seems to be a bug, then. If the compiler refuses Object Pascal code on Windows which it accepts on Linux. Perhaps there is some further $IfDef or $ModeSwitch that needs to be used? Or is it a 32/64 bit glitch? Maybe Sven can shed some light on this discrepancy. ---------------------------------------------------------------------- local-vision · 2021-02-14 16:57 Both howardpc and now egush builds on top with some truly amazing approaches using records. These postings are of significant value to me as they deal with some pascal coding fundamentals. Howardpc, I too run Linux Mint 64. But both egush and I get the same compiler error at the event assignment code section. Could indeed be some compiler directive/setting? Would like to find out what it is. Will try again. Any ideas, Id like to hear of them. Egush, Your added approach is really interesting. It opens up new ways to code and handle Shiva correct coding using records. Will test asap. Have you done a heaptrc check for any memory leaks? Just to make sure. Howardpc and Egush, could you provide your code as a zipped project for download? ---------------------------------------------------------------------- howardpc · 2021-02-14 22:02 Well, the code is in my reply #5. But here is the zipped project. ---------------------------------------------------------------------- egsuh · 2021-02-15 01:40 @local-vision QuoteIt opens up new ways to code and handle Shiva correct coding using records. I'm really sorry.  This is class, not record.  I corrected the code. It used be           TMethods = class record                 ...           end;   This will not compile. "record" remained there because i) I tested with class,  ii) I changed them to record commenting "class" ({class}) and confirmed that it causes error,  and then iii) I removed braces ( {,  } ) but I did not delete "record" at the type definition of TMethods. I cannot zip the project because I tested this code within my preexisting project which has much other codes. But that's all..  I did not do anything further. ---------------------------------------------------------------------- local-vision · 2021-02-15 03:45 Many thanks howardpc and egush. Will review. Reasoning for a download is to try and understand why howardpc approach is leading to compiler errors. Also, Egush code was not compiling either. But now clear as Egush explained why. Will also review. ---------------------------------------------------------------------- local-vision · 2021-02-15 05:34 Ok. So I have put together some examples (see download) thus far: A. 2 examples based on egush code that create runtime controls using class approach but without inheritance. In the second example same but with the control creation code and events in a separate unit. B. 1 example of contemporary approach using class and involving inheritance. Control creation code and events in a separate unit. Total file size limitation is severe so I had to create 3 posts and 3 downloads. ---------------------------------------------------------------------- local-vision · 2021-02-15 05:34 Here is the next example to download ---------------------------------------------------------------------- local-vision · 2021-02-15 05:35 Here is the last example