Search code examples
delphivariablespropertiestimage

DELPHI Change Property of Object stored in Variable


Is there a way to change the property of a TImage which is stored in a variable?

I have a function that writes the Name propery of a TImage in the FigureSelectedName variable, and it writes the field Name in the FieldSelected variable.

Now my problem is:

FieldSelectedName.top
FieldSelectedName.left

This gives a error in Delphi (Illegal qualifier)

function moveFigure(FigName:String; FieldName:String):boolean;
var
  x:Integer;
  y:Integer;
begin
  if (FigureSelected=true) and (FieldSelected=true) then
   begin
     x := strtoint(FieldSelectedName[2]);
     y := Ord(FieldSelectedName[1])-64;

     FigureSelectedName.top  := 80 + (x * 70);
     FigureSelectedName.left := 80 + (y * 70);
   end;
end;

Solution

  • System.Classes.TComponent.FindComponent can be used to find a component in a form knowing its name.

    • check if what was found is really a TImage

    • use the TImage properties and methods


    procedure TForm1.Button1Click(Sender: TObject);
    var
      comp: TComponent;
      img: TImage;
    begin
      comp := FindComponent('Image1');
      if comp is TImage then begin
        img := TImage(comp);
        img.Left := 0;
        img.Top := 0;
      end;
    end;
    

    Your method should be written like this, for the FindComponent method to work.

    function moveFigure(FigName:String; FieldName:String): Boolean;
    var
      x:Integer;
      y:Integer;
      comp: TComponent;
      img: TImage;
    begin
      //Result := False;
      if FigureSelected and FieldSelected then
      begin
        x := strtoint(FieldSelectedName[2]);
        y := Ord(FieldSelectedName[1])-64;
    
        comp := Form1.FindComponent(FieldSelectedName);
        if comp is TImage then begin
          img := TImage(comp);
          img.Left := 80 + (y * 70);
          img.Top := 80 + (x * 70);
          //Result := True;
        end;
      end;
    end;
    

    But the method has many issues:

    • the method's arguments FigName:String and FieldName:String are never used in the method body

    • are you sure the coordinates you're looking for in the image's name will be ever only one digit long?

    • Ord(FieldSelectedName[1]): an ordinal of a Char looks like a strange value for the Y-axis

    • the method is declared returning Boolean but doesn't provide a value for the Result