Canvas becomes empty after input file is closed

Hi,

In the following macro, my canvas becomes empty after I close the file. I have check and made sure that the file does contain data, so it should not be blank:

void mollyIntegration()
{
    TFile* file = TFile::Open("./histo_29P.root");
    if (!file || file->IsZombie()) {
        std::cout << "Error opening file" << std::endl;
        return;
    }

    // Get the histogram
    TH1F* hx260_261 = (TH1F*)file->Get("hx260_261");
    if (!hx260_261) {
        std::cout << "Histogram 'hx260_261' could not be found." << std::endl;
        file->Close();
        return;
    }
    
    // Create a canvas
    TCanvas *canvas = new TCanvas("c", "c", 800, 600);

    // Draw the histogram on the canvas
    hx260_261->Draw();

    // Update the canvas
    canvas->Update();

    // Close the file
    file->Close(); 
}

My current method of “fixing the issue” is to add canvas->WaitPrimitive() before closing the file. Is this an “expected” behavior?

Hello @Pete ,

yes that’s not ideal but it’s the expected behavior: the objects drawn need to be “alive” in order for the canvas to display them, and file->Close() causes the file to delete all objects it owns, including hx260_261.

There are several ways to work around this, probably the simplest is to call hx260_261->SetDirectory(nullptr); after retrieving the histogram from the file to detach it from it (you will then be responsible of the deletion of the histogram).

@pcanal or @couet might have better suggestions.

Cheers,
Enrico

1 Like

Try to use DrawClone instead of Draw.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.