Recent

Author Topic: Why label.caption is not changed?  (Read 1945 times)

Gosh

  • Jr. Member
  • **
  • Posts: 72
Why label.caption is not changed?
« on: April 27, 2015, 02:21:05 pm »
I'm a newbie with Lazarus and now I'm trying to understand main principles how it works. I made a small program which draws filled rectangles inside of paintbox control. This code works fine.

Code: [Select]
var

  Rec: TRect;
  x: integer;

begin
         for x := 0 to 100000 do
         begin
          rec.Left:=Random(300);
          rec.Top:=Random(200);
          rec.Right:=Random(300);
          rec.Bottom:=Random(200);

          Paintbox1.Canvas.Brush.Color:= RGBToColor(Random(255),Random(255),Random(255));
          PaintBox1.Canvas.FillRect(rec);

          Form1.label1.Caption:= IntToStr(x);
         end;
               

by idea, program should show number of iterations inside of a label control (the last line before end). From some reason, caption property of this control stays unchanged for  all time of program's execution. Can someone explain what's wrong here?

ChrisF

  • Hero Member
  • *****
  • Posts: 542
Re: Why label.caption is not changed?
« Reply #1 on: April 27, 2015, 02:24:41 pm »
Because when your code is running (i.e. your loop), the OS can't update immediately your text.

Add "Application.ProcessMessages;" after your label caption update.

Gosh

  • Jr. Member
  • **
  • Posts: 72
Re: Why label.caption is not changed?
« Reply #2 on: April 27, 2015, 02:41:49 pm »
I didn't know for that before.

It works. Thank you!

but... this code is much slower with that command inserted. In my case it takes 42sec now instead of 24sec as it was previously.

I'm a little bit disappointed with this ))
« Last Edit: April 27, 2015, 02:50:24 pm by Gosh »

ChrisF

  • Hero Member
  • *****
  • Posts: 542
Re: Why label.caption is not changed?
« Reply #3 on: April 27, 2015, 03:16:09 pm »
Of course.

You can use a StaticText instead of a Label; it's a little bit more faster. And remove the Application.ProcessMessages in this case (the "update text job" is already done implicitly for it).

instead of
Code: [Select]
Form1.label1.Caption:= IntToStr(x);
Application.ProcessMessages;

use
Code: [Select]
Form1.StaticText1.Caption:= IntToStr(x);
« Last Edit: April 27, 2015, 03:52:49 pm by ChrisF »

wp

  • Hero Member
  • *****
  • Posts: 11858
Re: Why label.caption is not changed?
« Reply #4 on: April 27, 2015, 05:24:46 pm »
And you can skip most of the label updates, you won't be able to read them anyway. With a loop going up to 100 000 why don't you update the label only after every 1000th pass of the loop?
Code: [Select]
  for x := 0 to 100000 do begin
    // ...
    if (x mod 1000 = 0) then Label1.Cpation := IntToStr(x);
  end;

Gosh

  • Jr. Member
  • **
  • Posts: 72
Re: Why label.caption is not changed?
« Reply #5 on: April 27, 2015, 07:19:05 pm »
Thanks for wise suggestions, guys.

 

TinyPortal © 2005-2018