5
votes

I want to draw a filled ellipse in QT that would not change its size when zooming in and out. For now I have the following:

QPen pen = painter->pen();
pen.setCosmetic(true);
pen.setWidth(5);
painter->setPen(pen);
QBrush brush = painter->brush();
brush.setStyle(Qt::SolidPattern);
painter->setBrush(brush);
painter->drawEllipse(p, 2, 2);

When I zoom out a gap between the boundary and the filling appear. So it looks like 2 concentric circles. And when I zoom in the filling overgrows the boundary and the disk gets bigger and bigger. Any idea how to fix this? Thanks!

1

1 Answers

3
votes

I would instead look to the ItemIgnoresTransformations flag, which will make the item itself "cosmetic", rather than just the pen. Here's a working example:

#include <QtGui>

class NonScalingItem : public QGraphicsItem
{
public:
    NonScalingItem()
    { setFlag(ItemIgnoresTransformations, true); }

    QRectF boundingRect() const
    { return QRectF(-5, -5, 10, 10); }

    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
    {
        QPen pen = painter->pen();
        pen.setCosmetic(true);
        pen.setWidth(5);
        pen.setColor(QColor(Qt::red));
        painter->setPen(pen);
        QBrush brush = painter->brush();
        brush.setStyle(Qt::SolidPattern);
        painter->setBrush(brush);
        painter->drawEllipse(QPointF(0, 0), 10, 10);
    }
};

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QGraphicsScene *scene = new QGraphicsScene;
    QGraphicsView *view = new QGraphicsView;
    NonScalingItem *item = new NonScalingItem;

    scene->addItem(item);
    view->setScene(scene);

    /* The item will remain unchanged regardless of whether
       or not you comment out the following line: */
     view->scale(2000, 2000);

    view->show();
    return app.exec();
}