QCustomPlot Discussion and Comments

Zoom to screen sizeReturn to overview

Hi,

in our application I would like to implement a fuctionality that enables zoom to screen size. That means, if I click on a button, the plot widget is zoomed in a way that all data and all plottables and all items fit on screen.

The rescale() function of the QCPAxis only considers plottables. That means if I use the rescale() function of X and Y axes, I can scale the plot in a way that all plottables fit on screen. But rescale() ignores the items like QCPItemRect or QCPItemText. Is there any function to get the bounding rectangle for all QCPLayerables including plottables and items to zoom the plot including all elements to screen size?

Thank you.

Uwe

This is my solution so far. Maybe someone has a better one?

void CExtendedCustomPlot::scaleToFitOnScreen()
{
	xAxis->rescale();
	yAxis->rescale();

	auto YRange = yAxis->range();
	auto XRange = xAxis->range();
	for (int i = 0; i < itemCount(); ++i)
	{
		auto Item = item(i);
		if (!Item->visible())
		{
			continue;
		}

		for (const auto Anchor : Item->anchors())
		{
			double y = yAxis->pixelToCoord(Anchor->pixelPosition().y());
			YRange.upper = qMax(y, YRange.upper);
			YRange.lower = qMin(y, YRange.lower);

			double x = xAxis->pixelToCoord(Anchor->pixelPosition().x());
			XRange.upper = qMax(x, XRange.upper);
			XRange.lower = qMin(x, XRange.lower);
		}
	}

    // now increase the ranges by 10% to ensure all items are really visible
	double Offset = (XRange.size() * 0.1) / 2.0;
	XRange.upper += Offset;
	XRange.lower -= Offset;

	Offset = (YRange.size() * 0.1) / 2.0;
	YRange.upper += Offset;
	YRange.lower -= Offset;

	yAxis->setRange(YRange);
	xAxis->setRange(XRange);

	replot();
}