如何截断包裹在 Qt 边界矩形中的字符串?

How to truncate a string wrapped in a bounding rect in Qt?

我有一个简单的 QGraphicsView,上面写有文字。该文本被包裹在 bounding rect 下。我想 truncate 文本的前导字符根据边界矩形的宽度。
如果我的字符串是 "I am loving Qt" 并且我的边界矩形允许 7 chars 那么它应该显示为 ...g Qt。文本不应写成多行。根据宽度,可以容纳更多的字符。
我很想知道如何对齐文本?

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

您可能希望使用 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 选项进行选择。