qt - QPainter.drawText 斜体写在矩形之外

标签 qt

我正在使用QPainter::drawText ... 好吧... 绘制一些文本,但是在使用斜体字体时遇到问题,其中文本写在给定的 QRectF 之外.

这里是一个示例代码:

    void TestApplication::paintEvent(QPaintEvent *)
    {
        QPainter painter(this);
        QRectF rect(100,100,100,100);
        QRectF necessary;
        QFont font("Times New Roman", 30);

        font.setItalic(true);   
        painter.setFont(font);  

     
        painter.fillRect(rect, QColor(0,255,0));
        painter.drawText(rect, Qt::AlignLeft|Qt::AlignVCenter, "ff",&necessary);
    }

这样,产生的输出是:

enter image description here

如您所见,第一个 f 写在定义的 QRectF 之外。 。如果我写了足够多的文字,右侧也会发生同样的情况。我已经尝试添加 Qt::TextDontClip到标志,但没有产生任何效果。

有人可以帮助我吗?

编辑:

正如答案中所解释的,这是预期的行为。我已经能够通过使用 leftBearing 来解决这个问题(解释在答案中)就像这样:

    void TestApplication::paintEvent(QPaintEvent *)
    {
        QPainter        painter(this);
        QRectF          rect(20,20,100,100);
        QRectF          textRect;
        QFont           font("Times New Roman", 40,0,true);
    
        font.setItalic(true);   
        painter.setFont(font);
    
        QFontMetrics    fontMetrics(font);  
    
        textRect = rect.adjusted(-fontMetrics.leftBearing('f'), 0, fontMetrics.leftBearing('f'), 0);
    
        painter.fillRect(rect, QColor(0,255,0));
        painter.drawText(textRect, Qt::AlignLeft|Qt::AlignTop, "ff");
    }

产生预期结果:

enter image description here

最佳答案

处理这个问题的最简单方法是在绘制文本之前缩小矩形,如果文本是斜体的话:-

QRectF rect(100,100,100,100);

QRectF textRect = rect.adjusted(8, 0, -8, 0);

painter.drawText(textRect, Qt::AlignLeft|Qt::AlignVCenter, "ff",&necessary);

作为Qt documentation状态,当传入boundingRect 矩形作为最后一个参数时:-

The boundingRect (if not null) is set to the what the bounding rectangle should be in order to enclose the whole text.

因此,它不一定受您传入的矩形的约束。

请注意,QFontMetrics 类允许您获取渲染字符串所需的boundingRect:-

QFont font("Times New Roman", 30);
QFontMetrics fontMetrics(font);

fontMetrics.boundingRect("ff");

但是,documentation for QFontMetrics状态:-

Note that the bounding rectangle may extend to the left of (0, 0), e.g. for italicized fonts, and that the width of the returned rectangle might be different than what the width() method returns.

所以您所看到的是预期的行为。

关于qt - QPainter.drawText 斜体写在矩形之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23737591/

相关文章:

c++ - fork() 和 execv() 之后的 QProcess 问题

css - 为什么 padding-left 样式会导致 QComboBox 菜单拉伸(stretch)到屏幕高度?

c++ - 快捷方式触发时的 Lambda 表达式 (Qt)

python-3.x - PyQt5 - 如何在鼠标点击位置画一个点?

c++ - 在几个可变的 lambda 中更改同一个 vector

c++ - 转发从 QCoreApplication::postEvent 收到的 QEvent 是否安全

c++ - 获取 QSqlError ("", "", "") 但数据已插入

windows - 如何安装 Thrift 以与 Qt-Windows 一起工作

qt - 在短时间内发送许多QUdpSockets时,它们会被丢弃

qt - 部署 qt 应用程序及其所有依赖项