Home > Blockchain >  QGraphicsScene draw a non transformable circle
QGraphicsScene draw a non transformable circle

Time:02-18

I am trying to draw a 10 pixel radius circle on a QGraphicsScene that is anchored on the center and doesn't transform (change size) when the scene is zoomed.

I have tried using the QGraphicsEllipseItem with the QGraphicsItem::ItemIgnoresTransformations flag, but it still transforms when the scene is zoomed.

Is this possible with standard graphics items, or do I need to create my own and do the paint event manually?

CodePudding user response:

The following code does what I think you're looking for. It creates a single 10 pixel immutable circle that anchors itself to the centre of the scene as well as 10 larger, movable, circles that obey the scaling transform applied...

#include <iostream>
#include <QApplication>
#include <QGraphicsEllipseItem>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QPainter>

int main (int argc, char **argv)
{
  QApplication app(argc, argv);
  QGraphicsView view;
  QGraphicsScene scene;
  view.setScene(&scene);
  QGraphicsEllipseItem immutable(0, 0, 20, 20);
  immutable.setFlag(QGraphicsItem::ItemIgnoresTransformations);
  immutable.setPen(Qt::NoPen);
  immutable.setBrush(Qt::blue);
  scene.addItem(&immutable);
  QObject::connect(&scene, &QGraphicsScene::sceneRectChanged,
                   [&](const QRectF &rect)
                     {
                       immutable.setPos(rect.center() - 0.5 * immutable.boundingRect().center());
                     });
  for (int i = 0; i < 10;   i) {
    auto *e = new QGraphicsEllipseItem(20, 20, 50, 50);
    e->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
    scene.addItem(e);
  }
  view.show();
  view.setTransform(QTransform::fromScale(5, 2));
  return app.exec();
}
  • Related