PDA

View Full Version : QGraphicsItem : keep position when zoom changes



nilot
9th February 2018, 12:40
Hello,

In the code below, I create a QGraphicsRectItem and I want to display its name with a QGraphicsSimpleTextItem. I want the size of the text to be unaffected by the zoom, so I use the flag QGraphicsItem::ItemIgnoresTransformations. I also want the position of the text to be centered on the QGraphicsRectItem.
Unfortunately you can see on the capture that when I unzoom ( on the right ), the text doesn't stay inside the rectangle 12766 .
How to keep the text inside the rectangle and centered ?



#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsRectItem>
#include <QPen>
#include <QWheelEvent>
#include <cmath>
#include <QDebug>

class MainView : public QGraphicsView {
public:
MainView(QGraphicsScene *scene) : QGraphicsView(scene) { setBackgroundBrush(QBrush(QColor(255, 255, 255)));}
protected:
void wheelEvent(QWheelEvent *event) {
double scaleFactor = pow(2.0, event->delta() / 240.0);
scale(scaleFactor, scaleFactor);
}
};

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsScene scene;
scene.setSceneRect(0, 0, 800, 800);
QGraphicsRectItem* rectItem = new QGraphicsRectItem(QRectF(0, 0, 400, 200));
rectItem->setPos(200, 200);
rectItem->setBrush(QColor(255, 0, 0));
scene.addItem(rectItem);

QGraphicsSimpleTextItem *nameItem = new QGraphicsSimpleTextItem("name", rectItem);
QFont f = nameItem->font();
f.setPointSize(12);
nameItem->setFont(f);
nameItem->setFlag(QGraphicsItem::ItemIgnoresTransformations) ;
nameItem->setPos(rectItem->rect().center());

MainView view(&scene);
view.show();

return a.exec();
}

Thank you