QCustomPlot Discussion and Comments

iterating QCustomPLots inside a QGridLayoutReturn to overview

Hey, I had an idea on how I can manage my plots by dividing them into four different QGridLayouts and then iterate the plots in each QGridLayout separately.

My wish would have been to use findchildren to find the grids, then from each grid look for the plots by using findchildren in there. This is where it doesn't work since the plots are not children but rather "items" as I have understood.

Here's how that looked like:

        QGridLayout* grid = this->findChild<QGridLayout*>(gridLayout1");
        QCustomPlot* plots = grid->findChildren<QCustomPlot*>(); // <- DOES NOT WORK

But I can work around this I think. I count the items in the grid and iterate the items using QGridLayout::ItemAt(int index). My problem here is I get an QLayoutItem* in return, how can I "convert" it to QCustomPlot so that I can use it as a plot?

my current code:

        QGridLayout* grid = this->findChild<QGridLayout*>("gridLayout1");
        for (int i= 0; i < grid->count(); i++)
        {
            QLayoutItem* plot = grid->itemAt(i) // How to get this item as a QCustomPlot instead?
        }

You can use the QLayoutItem::widget() function to get the widget associated with a QLayoutItem. Since QCustomPlot is a subclass of QWidget, you can check if the widget returned by QLayoutItem::widget() is a QCustomPlot using qobject_cast. Here's an example of how you can modify your code to achieve this:

QGridLayout* grid = this->findChild<QGridLayout*>("gridLayout1");
for (int i = 0; i < grid->count(); i++)
{
  QLayoutItem* item = grid->itemAt(i);
  if (QCustomPlot* plot = qobject_cast<QCustomPlot*>(item->widget())) // this checks that plot is not nullptr
   {
         // Use plot as a QCustomPlot
   }
}

This code retrieves the QLayoutItem at index i, gets its associated widget using QLayoutItem::widget(). Then it is checked if it can be cast to a QCustomPlot using qobject_cast. If the cast is successful, plot is a pointer to the QCustomPlot widget and can be used accordingly.

Thank you DerManu, I tried your solution and it works!