Jump to content
Sign in to follow this  
IElite

Tw3TabControl's OnPrepareTab ?

Recommended Posts

It is my understanding that the following code should produce 3 tabs with the captions ("one', 'two', 'three')...however, it does not. It seems that the OnPrepareTab when run on the third time through overwrites all three tabs with "three"

  for i:= 1 to 3 do
  begin
   str:= getStr(i); 
   tab:= W3TabControl1.AddTab(str);
   tab.AutoSize:=True;
   tab.OnPrepareTab:= procedure (sender: TObject)
   begin
    lbl:= TW3Label.Create(TW3Tab(Sender));
    lbl.Caption:= str;
   end;
  end;

 In order to make it work, I have had to use the TagId property to store the value

for i:= 1 to 3 do
begin
   str:= getStr(i);
   tab:= W3TabControl1.AddTab(str);
   Tab.TagId:= str;
   tab.AutoSize:=True;
   tab.OnPrepareTab:= procedure (sender: TObject)
   begin
     lbl:= TW3Label.Create(TW3Tab(Sender));
     lbl.Caption:= TW3Tab(Sender).TagId;
   end;
end;

am I too tired? What am I not seeing in the first code block?

Share this post


Link to post
Share on other sites

I tried it in a different manner with OnPrepareTab

 

procedure TForm1.W3Button1Click(Sender: TObject);
var str : string;
begin
  for var i:= 1 to 5 do
  begin
   str:= IntToStr(i);
   var tab : tw3tab;
   var lbl : tw3label;
   tab:= W3TabControl1.AddTab(str);
   tab.AutoSize:=True;

   lbl:= TW3Label.Create(tab);
   lbl.Caption:= str;
  end;
end;

 

Share this post


Link to post
Share on other sites

Yeah, let me explain what OnPrepareTab does:

Imagine that you have tens of tabs. If all of them were built at once, it would take a lot of time and slow down your code. Also, building most of them might be for no good, if most of the tabs were never shown.

So, when you add a tab, nothing happens unless the tab you added is the one showing or just next to it. In your example:

Add tabs one, two and three. Tab "one" is showing, so OnPrepareTab is called for it and OnShowTab right away after it.

Tab "two" is right next to it, so OnPrepareTab is called for it too.

If the user changes to tab "two", OnShowTab is called for it and OnPrepareTab for tab "three".

So, the function of OnPrepareTab is that you have the possibility to build the tab before it's showing. That way you'll most likely have it looking good before it's going to be visible.

@lynkfs also explained what went wrong in your example. When you're using anonymous procedures and you're using variables from outside of it, you very often have no control over what the values of the outside variables are.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×