How to truncate a string wrapped in a bounding rect in Qt?
-
I have a simple QGraphicsView with text written over it. That text is wrapped under a bounding rect. I want to truncate the leading characters of text according to width of the bounding rect.
If my string is "I am loving Qt" and if my bounding rect is allowing 7 chars then it should show like ...g Qt. Text should not be written in multiple lines. According to width, more chars can be fit.
Along with I am interested to know, how the text can be aligned ?widget.cpp
Widget::Widget(QWidget *parent) : QGraphicsView(parent) , ui(new Ui::Widget) { ui->setupUi(this); scene = new QGraphicsScene(this); view = new QGraphicsView(this); view->setScene(scene); } void Widget::on_textButton_clicked() { Text* t = new Text() ; QString s = "I am loving Qt"; QGraphicsTextItem* text = t->drawText(s); scene->addItem(text); }
Text.h
class Text : public QGraphicsTextItem { public: explicit Text(const QString &text); Text(); QGraphicsTextItem* drawText(QString s); virtual void paint (QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override; }
Text.cpp
QGraphicsTextItem* Text::drawText(QString s) { QGraphicsTextItem *t = new Text(s); t->setTextWidth(8); return t; } void Text::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { painter->setPen(Qt::black); painter->setBrush(QColor(230,230,230)); painter->drawRect(option->rect); QGraphicsTextItem::paint(painter, option, widget); }
-
Set the proper clipRect on the painter.
-
Hi,
Since you want to do elision, you have to test your string's width with regard to your item bounding rect. QFontMetrics can be used to test that.
See the Elided label example for some other inspiration.
-
@Christian-Ehrlicher I have added line in paint()
painter->setClipRect(QRect(2, 2, 100, 40), Qt::ReplaceClip);
Now it is clipping the text according to size set in setTextWidth().
But if I want to truncate starting characters and put 3 dots in final string at starting position, how to do that ?
Is alignment (left/right/center) possible in wrapped text ? -
As I suggested you need to calculate the size of your string with regard to your item. Then if it does not fit, use a loop to append your string from the end to the "..." until it reaches the required size.
-
As already written: QFontMetrics.
As for the alignement, it's the responsibility of QPainter::drawText.
That said, the bounding rect calculation through QFontMetrics also gives you the alignement as flags to be used.
-
@SGaist I found one method in QFontMetrics.
QString QFontMetrics::elidedText(const QString &text, Qt::TextElideMode mode, int width, int flags = 0) const
but I did not get how to calculate width here ?
The width is specified in pixels, not characters.
-
In your case, it's the width of your item.