Sorry for my English, it's not my native language.
I have a problem - I need to center text in my QGraphicsSimpleTextItem. I inherited my class from QGraphicsSimpleTextItem. Do I need to override the paint()
method or what should I do?
I've read about tightBoundingRect()
in QFontMetrics
. Can I set position of tight bounding rect in QGraphicsSimpleTextItem?
Thanks for your help!
Maybe something like this could work.
void MySimpleTextItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
QFont numberFont = QFont("Helvetica [Cronyx]", 20);
painter->setFont(numberFont);
painter->drawText(boundingRect(), Qt::AlignCenter, QString::number(itemIndex));
}
In my case this piece of code were to draw a number inside a QGraphicsEllipseItem, centered inside ellipse. I shaped my code a bit to fit your case, but essential point here is painter->drawText(boundingRect(), Qt::AlignCenter, QString::number(itemIndex));
, where you use boundingRect() along with flag Qt::AlignCenter.