View Full Version : QGraphicsView "un"scale text

2nd February 2009, 09:37

I have a graphicsview that gets scaled. I want a line + text that always stays in the top left corner whatever the scaling or scrollbar position is.

I managed (with the help of some previous threads) to draw a line but the font is always scaled. Setting a pixelsize depending on scaling factor did not work. If I rescale the painter (e.g. resetTransform()) I get always the same fontsize but then I lose the point's position where to draw the text ...

void GraphicsView::drawForeground(QPainter *painter, const QRectF &rect)

QRectF scenerect = QRectF(mapToScene(0,0), mapToScene(width(), height()));

QPointF p1(scenerect.topLeft().x() + (10/matrix().m11()), scenerect.topLeft().y() + (10/matrix().m22()));
QPointF p2(p1.x() + (50/matrix().m11()), p1.y() + (10/matrix().m22()));
QRectF r(p1, p2);

painter->drawLine(r.topLeft(), r.topRight()); //ok
painter->drawText(r, QString::number(10)); //?


2nd February 2009, 09:51
drawForeground works in terms of scene coordinates and you want viewport coordinates. It would be easiest to apply an event filter on the view's viewport() and override its paintEvent using the event filter or put your own widget as the viewport and change its paintEvent so that you both call the base class implementation and draw something on it yourself. You can also position a QLabel object in the view (but not in the scene).

2nd February 2009, 12:25
thx, i added a lable and installed the eventfilter on the it.

label = new QLabel(ui.graphicsView->viewport());
label->resize(50, 15);


bool ViewWidget::eventFilter(QObject *obj, QEvent *event)

qDebug() << obj << event;
if (obj == label) {
if (event->type() == QEvent::Paint) {
QPainter painter(label);
painter.drawLine(QPointF(label->rect().bottomLeft().x() + 5, label->rect().bottomLeft().y()), label->rect().bottomRight());
painter.drawText(QPointF(label->rect().bottomLeft().x() + 5, label->rect().bottomLeft().y() -2), "test");

return true;

return QWidget::eventFilter(obj, event);


2nd February 2009, 14:52
If you add a label then you can simply call its functions instead of using an event filter. If you want the event filter, there is no point is using QLabel - use QWidget instead.