QCustomPlot Discussion and Comments

Clearing qcp->plotlayout and using legendReturn to overview

Hi,
Is there a way of using the legend again after the original axisRect of QCustomPlot.plotLayout() has been clear()-ed? The below code crashes with a seg fault error. I have tried moving the legend->setVisible() to the end of the MainWindow constructor, hoping that it would work as there would then be axisRects for the customplot to look for plottables on, but that also ended in a seg fault.

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QCustomPlot *customPlot = new QCustomPlot();
    this->setCentralWidget(customPlot);
    customPlot->plotLayout()->clear(); // let's start from scratch and remove the default axis rect
    customPlot->legend->setVisible(true);
    // add the first axis rect in second row (row index 1):
    QCPAxisRect *bottomAxisRect = new QCPAxisRect(customPlot);
    customPlot->plotLayout()->addElement(1, 0, bottomAxisRect);
    // create a sub layout that we'll place in first row:
    QCPLayoutGrid *subLayout = new QCPLayoutGrid;
    customPlot->plotLayout()->addElement(0, 0, subLayout);
    // add two axis rects in the sub layout next to each other:
    QCPAxisRect *leftAxisRect = new QCPAxisRect(customPlot);
    QCPAxisRect *rightAxisRect = new QCPAxisRect(customPlot);
    subLayout->addElement(0, 0, leftAxisRect);
    subLayout->addElement(0, 1, rightAxisRect);
    subLayout->setColumnStretchFactor(0, 3); // left axis rect shall have 60% of width
    subLayout->setColumnStretchFactor(1, 2); // right one only 40% (3:2 = 60:40)
    // since we've created the axis rects and axes from scratch, we need to place them on
    // according layers, if we don't want the grid to be drawn above the axes etc.
    // place the axis on "axes" layer and grids on the "grid" layer, which is below "axes":
    QList<QCPAxis*> allAxes;
    allAxes << bottomAxisRect->axes() << leftAxisRect->axes() << rightAxisRect->axes();
    foreach (QCPAxis *axis, allAxes)
    {
      axis->setLayer("axes");
      axis->grid()->setLayer("grid");
    }
}

If you clear the plotLayout, the legend will be deleted with it (because it's owned by the inset layout of the axis rect). When the main legend is deleted, its pointer (QCustomPlot::legend) is set to 0. So when you call setVisible on it, of course it segfaults.

To create a new main legend, simply do something like this:

customPlot->legend = new QCPLegend;
customPlot->axisRect()->insetLayout()->addElement(customPlot->legend, Qt::AlignRight|Qt::AlignTop);
customPlot->axisRect()->insetLayout()->setMargins(QMargins(12, 12, 12, 12));
customPlot->legend->setLayer("legend");

Thanks for the speedy reply!