How can I wrap text in a QGraphicsItem?

1) How can I wrap the text in QGraphicsTextItem

to set a fixed rectangle with width and height?

I am currently experimenting with creating text, getting its bounding box and resizing it to fit the margin, but I cannot wrap it.

class TTT: public QGraphicsTextItem {
    TTT() {
    {
        setPlainText("abcd");
        qreal x = m_itemSize.width()/boundingRect().width();
        qreal y = m_itemSize.height()/boundingRect().height();
        scale(x, y);
    }
    void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) {
        // experiment with clip regions
        // text gets covered by hole in clip
        QRegion r0(boundingRect().toRect());
        QRegion r1(QRect(5, 5, 10, 10), QRegion::Ellipse);
        QRegion r2 = r0.subtracted(r1);
        painter->setClipRegion(r2);
        painter->setBrush(Qt::yellow);
        painter->drawRect(boundingRect());
        QGraphicsTextItem::paint(painter, option, widget);
    }
}

      

What does the packaging do, how can I call it?

Now, when I continue to type, the window expands automatically.

2) Is it possible to wrap text in a subclass QGraphicsItem

/ QGraphicTextItem

in a shape that is not a rectangle? enter image description here

(Something like in the image above)
I tried to use clipRegion

, see the code above, but I think this is not the correct way, the clipping cuts the text but does not complete.

Maybe it would be ... If I could figure out how to wrap the text in the first place?

Qt 4.8

+3


source to share


2 answers


You didn't specify the Qt version, but try:



void QGraphicsTextItem :: setTextWidth (qreal width)

Sets the preferred width for the element's text. If the actual text is wider than the> specified width, it will be split across multiple lines.

If the width is -1, the text will not be split across multiple lines> unless it is forced through an explicit line break or new paragraph.

The default is -1.

+3


source


In response to 1), I would rather not use a QGraphicsTextItem, but draw the text directly in your QGraphicsItem draw function using drawText , which takes a QTextOption .

Using this, you can set WrapMode, for example with a call

QTextOption::setWrapMode(QTextOption:: WordWrap)

      



As for 2) with a non-rectangular shape, I don't think Qt will do it for you.

Once you've done this yourself, you can use QFontMetrics to determine how much text will fit on each line, depending on where it lies within its bounding point.

Alternatively, you can adapt the concept of the text-to-path method .

+3


source







All Articles