Home > Net >  How to truncate a string wrapped in a bounding rect in Qt?
How to truncate a string wrapped in a bounding rect in Qt?

Time:04-13

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);
}

CodePudding user response:

You may want to use QFontMetrics::elidedText by giving the font, width of your Text object and the actual text, and it will return the elided text. There are also a few Qt::TextElideMode options to choose from.

  • Related