QGraphicsView and QGraphicsItem: don´t scale item when scaling the view rect


Question

I am using Qt´s QGraphicsView - and QGraphicsItem-subclasses. is there a way to not scale the graphical representation of the item in the view when the view rectangle is changed, e.g. when zooming in. The default behavior is that my items scale in relation to my view rectangle.

I would like to visualize 2d points which should be represented by a thin rectangle which should not scale when zooming in the view. See a typical 3d modelling software for reference where vertex points are always shown at the same size.

Thanks!

1
9
9/11/2018 12:15:26 AM

Accepted Answer

Set the QGraphicItem's flag QGraphicsItem::ItemIgnoresTransformations to true does not work for you?

10
9/11/2018 5:07:17 AM

I got into the same problem, and it took me a while to figure it out. This is how I solved it.

Extend a QGraphicsItem class, override paint(). Inside the paint(), reset the transformation's scaling factor to 1(which are m11 and m22), and save the m11(x scaling factor) and m22(y scaling factor) before the reset. Then, draw like you would normally do but multiply your x with m11 and y with m22. This avoids drawing with the default transformation, but explicitly calculates the positions according to the scene's transformation.

void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *item, QWidget *widget)
{
    QTransform t = painter->transform();
    qreal m11 = t.m11(), m22 = t.m22();
    painter->save(); // save painter state
    painter->setTransform(QTransform(m11, t.m12(), t.m13(),
                                     t.m21(), 1, t.m23(), t.m31(),
                                     t.m32(), t.m33()));
    int x = 0, y = 0; // item's coordinates
    painter->drawText(x*m11, y*m22, "Text"); // the text itself will not be scaled, but when the scene is transformed, this text will still anchor correctly
    painter->restore(); // restore painter state
}

The following code block is drawing with default transformation

void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *item, QWidget *widget)
{
    int x = 0, y = 0;
    painter->drawText(x, y, "Text"); 
}

You can try both to see the difference. Hope this helps.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon