A usefull method to automatically add a TLegend to a TPad?

Hello Root Developpers,
I have added a simple method to a TPad in order to build automatically a TLegend from the primitives in the TPad. Only those deriving from TAttLine, TAttMarker and TAttFill are added, excluding TPave and TFrame derived classes. I have also added a new entry in the context menu of the TPad to build the TLegend from the GUI. I feel this could be useful to everybody and that this method could be added as a “standard” method of the TPad class. Here is the code:

in gpad/inc/TPad.h

......... 
   virtual TVirtualViewer3D *GetViewer3D(Option_t * type = ""); // *MENU*
   virtual void              ReleaseViewer3D(Option_t * type = "");
   // void SetViewer3D(TVirtualViewer3D *v) {fViewer3D = v;}

  virtual TLegend *BuildLegend(void); // *MENU*

   ClassDef(TPad,8)  //A Graphics pad
};

in gpad/src/TPad.cxx

//______________________________________________________________________________
TLegend *TPad::BuildLegend(void)
{
   //
   // Build a legend from the graphical objects in the pad
   //
TList *lop=GetListOfPrimitives();
TLegend *leg=0;
TIter next(lop);
TObject *o=0;
while( (o=next()) )
 {
 if((o->InheritsFrom("TAttLine") || 
    o->InheritsFrom("TAttMarker") || 
    o->InheritsFrom("TAttFill")) && 
    ( !(o->InheritsFrom("TFrame")) &&
      !(o->InheritsFrom("TPave")) ))
  {
  if(!leg)
   {
   leg=new TLegend(0.5,0.67,0.88,0.88,Form("Legend of pad %s",gPad->GetName()));
   }
  TString mes;
  if(o->InheritsFrom("TNamed") && strlen(((TNamed *)o)->GetTitle()))
   mes=((TNamed *)o)->GetTitle();
  else if(strlen(o->GetName()))
   mes=o->GetName();
  else
   mes=o->ClassName();
  TString opt("");
  if(o->InheritsFrom("TAttLine")) opt+="l";
  if(o->InheritsFrom("TAttMarker")) opt+="p";
  if(o->InheritsFrom("TAttFill")) opt+="f";
  leg->AddEntry(o,mes.Data(),opt.Data());
  } 
 }
if(leg)
 {
 leg->Draw();
 }
else
 {
 Info("BuildLegend(void)","No object to build a TLegend...");
 } 
return leg;
}

Friendly

Daniel CUSSOL

Daniel,

This is a good idea. we will add this method.

Rene

Hi Daniel,

Your new code is now in TPad. Thanks.

Olivier

Hello René and Olivier,
Glad to feel useful to the ROOT community! Thanks for adding this method.
Friendly

Daniel