【问题标题】:Size QGraphicsItem based on string length大小 QGraphicsItem 基于字符串长度
【发布时间】:2013-06-19 22:54:49
【问题描述】:

我正在寻找根据给定QString 的长度调整QGraphicsItem 大小的最有效方法,以便文本始终包含在 QGraphicsItem 的边界内。我们的想法是使QGraphicsItem 尽可能小,同时仍以清晰的大小包含文本。以一定的宽度阈值缠绕到多条线上也是理想的。例如,

TestModule::TestModule(QGraphicsItem *parent, QString name) : QGraphicsPolygonItem(parent)
{
    modName = name;
    // what would be the best way to set these values?
    qreal w = 80.0; 
    qreal h = 80.0;
    QVector<QPointF> points = { QPointF(0.0, 0.0),
                                QPointF(w, 0.0),
                                QPointF(w, h),
                                QPointF(0.0, h) };
    baseShape = QPolygonF(points);
    setPolygon(baseShape);
}

void TestModule::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    QBrush *brush = new QBrush(Qt::gray, Qt::SolidPattern);
    painter->setBrush(*brush);
    painter->drawPolygon(baseShape);
    painter->drawText(QPointF(0.0, 40.0), modName);
}

我可以在构造函数中添加什么代码来满足我的需求?根据字符串的总长度设置宽度,假设每个字符占用多少像素空间是最明显的解决方案,但我正在寻找更优雅的东西。有任何想法吗?提前感谢您的帮助。

【问题讨论】:

    标签: c++ qt qgraphicsitem


    【解决方案1】:

    QFontMetrics 类有一个名为 boundingRect 的函数,它接收您要打印的字符串并根据您用于初始化 QFontMetrics 的 QFont 返回该字符串的 QRect。

    如果要换行,则需要计算出字符串中允许 boundingRect 返回适合 QGraphicsItem 的 boundingRect 的 QRect 的最大字数。

    【讨论】:

      【解决方案2】:

      看看QFontMetrics

      您可以向您的小部件询问font

      并从 QFontMetrics 文档中检查这个 sn-p

      QFont font("times", 24);
       QFontMetrics fm(font);
       int pixelsWide = fm.width("What's the width of this text?");
       int pixelsHigh = fm.height();
      

      编辑:正如梅林在评论中所说,使用

      QRect QFontMetrics::boundingRect ( const QString & text ) const 所以:

      int pixelWide = fm.boundingRect("这个文本的宽度是多少?").width();

      【讨论】:

      • width() 不返回文本占用的像素,而是定义为返回“到下一个字符串应该绘制的距离”,这可能是也可能不是正确的值,特别是如果它被用来包装文本,根据要求。
      猜你喜欢
      • 2020-05-03
      • 2017-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-10
      • 1970-01-01
      相关资源
      最近更新 更多