There are two possible approaches:
1.
You could store a pointer to the bars instance in your parent class (e.g. your QMainWindow). So you declare a member variable
QCPBars *myBars;
and while generating the bars, store a pointer to it in that variable:
myBars = new QCPBars(customPlot->xAxis, customPlot->yAxis);
customPlot->addPlottable(myBars);
...
Now you can access myBars
in any method of QMainWindow. Note that QCustomPlot takes ownership of the bars instance, so you shouldn't externally delete myBars
. Further, if the bars plottable is removed from the QCustomPlot, e.g. via QCustomPlot::removePlottable
, the instance will be deleted and turn your external myBars
pointer invalid. Using/dereferencing it after the deletion will crash your program. To avoid that, you'll either need to use some extra care-taking code to make sure myBars
is never accessed after the deletion of the bars, or you could use a QPointer<QCPBars>
variable type for storing the pointer. Search for safe pointer if you don't know what that is.
2.
The alternative way is casting the QCPAbstractPlottable
base class pointer, which is returned by customPlot->plottable(i)
, to a pointer of type QCPBars*
, like so:
QCPBars *b = qobject_cast<QCPBars*>(customPlot->plottable(i));
if (b != 0)
{
b->setData(...)
...
}
// the first two lines are usually combined to the idiom:
// if (QCPBars *b = qobject_cast<QCPBars*>(customPlot->plottable(i)))
Note that checking the validity (i.e. != 0) of the return value of qobject_cast
is vital, because if the returned plottable is not a QCPBars (but a different subclass of QCPAbstractPlottable, like QCPGraph or QCPCurve), it returns 0. And of course, calling setData on a 0 pointer will crash your program once again.