PDA

View Full Version : Positioning QGraphicsWidget



jasper_ferrer
21st September 2009, 15:59
I've recently started playing around with the Graphics View Framework.

With this code:


void ButtonWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
painter->setPen( Qt::NoPen );
painter->setBrush( QBrush( QColor(255, 0, 0)) );
painter->drawRoundedRect(0, 0, 50, 50, 25, 25);
}

I am able to position an instance of ButtonWidget, using ButtonWidget::setPos(), anywhere exactly I want it to appear on the view (top-right corner for one).

However, when I start drawing multiple shapes I can no longer position an instance of ButtonWidget properly.

Here is the code:


void ButtonWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
painter->setPen( Qt::NoPen );
painter->setBrush( QBrush( QColor(255, 0, 0)) );
painter->drawRoundedRect(-20, -20, 50, 50, 25, 25);

painter->setBrush( QBrush( QColor(0, 0, 255)) );
painter->drawRoundedRect(-10, -10, 30, 30, 15, 15);
}

With this I get the exact appearance of the widget as I want it to be, but no matter what I do I can't position it properly on the view.

I've been reading the docs, tutorials and a couple of books over and over gain but because 2D drawing is so new to me I can't seem to figure out what I am doing wrong.

jasper_ferrer
22nd September 2009, 01:24
Ok, after waking up this morning and seeing no replies, I did some experiment.

I did not positioned the ButtonWidget instance after adding it to the scene and the answer was right there on the screen!

scascio
22nd September 2009, 08:42
What is your ButtonWidget::boundingRect() like?

Remember that geometry is relative to position. And position is relative to parent item.

jasper_ferrer
22nd September 2009, 14:34
scascio, I have already solved this problem but I'll answer your question anyway.

In the first sample code it is:



QRectF ButtonWidget::boundingRect()
{
return QRectF(0, 0, 50, 50);
}


In the second:



QRectF ButtonWidget::boundingRect()
{
return QRectF(-20, -20, 50, 50);
}


Edit: spelling correction