[Qt-interest] aspect-ratio for graphs

Murphy, Sean M. sean.murphy at gd-ais.com
Thu Jul 15 22:18:17 CEST 2010


>   I've got to do a bit more testing and tidying up, but I think that I
> have a solution that seems to work reasonably well. I re-implemented the
> resizeEvent() i.e.
> 
> void VIwindow::resizeEvent ( QResizeEvent * event ) {
>   //qDebug("%d,%d\n", m_graph[0]->width(),m_graph[0]->height());
>   if(m_graph[0]->height() != m_graph[0]->width())
>   {
>     for(int i = 0; i < 6; i++)
>       m_graph[i]->setMinimumHeight(m_graph[i]->width());
>   }
> }
> 
> I tried looking at the link you sent me but could not download the
> tarfile; got error:- The requested URL /qt-interest/2004-
> 10/binPP1WN90x4o.bin was not found on this server.

Sorry about that, I found the discussion and didn't bother to check if the tarball was still available.

Basically what I did was I created a widget that inherited from a QFrame and overrode the resizeEvent() function as follows:

void QSquareFrame::resizeEvent(QResizeEvent *e)
{
	int width, height, pWidth, pHeight;
	width = e->size().width();
	height = e->size().height();
	pWidth = parentWidget()->width();
	pHeight = parentWidget()->height();

	//qDebug("Parent size, %d x %d", pWidth, pHeight);
	//qDebug("New size: %d x %d", width, height);

	// resize frame to smallest dimension
	if (width < height)
	{
		//qDebug("width < height, resize(width,width)");
		resize(width, width);
		move((int)(0.5*( pWidth - width )),(int)(0.5*(pHeight-width)));
	}
	else if (height < width)
	{
		//qDebug("width > height, resize(height,height)");
		resize(height, height);
		move((int)(0.5*(pWidth - height)),(int)(0.5*(pHeight-height)));
	}

	QFrame::resizeEvent(e);
}

A couple of notes:
1) As you can see in the above code, I move this widget relative to its parent widget as things get resized.  I think I may have had to lay this widget out in a layout on the parent widget with some QSpacerItems on either side of it so the spacers absorbed/released space as this widget resized itself.
2) This was written in Qt3, so you may have to tweak it a little to get it to work under Qt4.
3) I've always wished that I generalized it a bit more to make it keep a fixed aspect ratio, but not limited to 1:1.  I only needed a square in my application, but it would be a lot more flexible if you could set it to arbitrary ratios (2:1, 4:3 or 16:9 for example).

I think this is something that should really be put into QWidget in Qt, so that all descendants get it built in, a set of functions like:
setFixedAspectRatio(bool)
setAspectRatio(int width, int height)
setAspectRatio(float ratio)

If I ever have free time, and learn git, maybe I'll try to add it and commit it to QWidget...
Sean





More information about the Qt-interest-old mailing list