How to center text in QGraphicsSimpleTextItem?

1.4k views Asked by At

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!

3

There are 3 answers

0
George On BEST ANSWER

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.

0
scopchanov On

QGraphicsSimpleTextItem is just big enough to hold the text, so alignment of the text within the item does not make sense.

That, what you might do, is to position the whole item with respect to other items. You do not need to subclass QGraphicsSimpleTextItem. Instead, use QGraphicsItem::setPos to accomplish that. As a result the text will appear to be aligned in some way, e.g. centered.

0
MBV On

For anybody trying to do this for PyQt5 this is simple way to center text and set a hover event. Hope it helps.

class SimpleText(QtWidgets.QGraphicsSimpleTextItem):
    def __init__(self, parent=None):
        super(SimpleText, self).__init__(parent)
        self.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True)
        self.setFlag(QtWidgets.QGraphicsItem.ItemIsSelectable, True)
        self.setAcceptHoverEvents(True)
        self.font_family = 'Arial'
        self.font_size = 2.1


    def hoverLeaveEvent(self, event):
        self.setBrush(QtGui.QColor("black"))

    def mousePressEvent(self, event):
        self.setBrush(QtGui.QColor("gray"))

    def paint(self, painter: QtGui.QPainter, option: 'QStyleOptionGraphicsItem', widget: QtWidgets.QWidget) -> None:
        custom_font = QtGui.QFont(self.font_family)
        custom_font.setPointSizeF(self.font_size)
        painter.setFont(custom_font)
        painter.drawText(self.boundingRect(), QtCore.Qt.AlignCenter, self.text())