根据字符串长度大小QGraphicsItem
Size QGraphicsItem based on string length
本文关键字:QGraphicsItem 字符串 更新时间:2023-10-16
我正在寻找基于给定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);
}
我可以添加什么代码到构造函数使我的需求工作?根据字符串的总长度设置宽度,假设每个字符占用多少像素空间是最明显的解决方案,但我正在寻找更优雅的方法。什么好主意吗?提前感谢您的帮助
QFontMetrics类有一个叫做boundingRect的函数,它接受你想要打印的字符串,并根据你用来初始化QFontMetrics的QFont返回字符串的QRect。
如果你想换行,那么你需要计算出字符串中允许boundingRect返回符合QGraphicsItem的boundingRect的QRect的最大单词数
看一下QFontMetrics
你可以向你的小部件询问字体
检查QFontMetrics文档
中的代码片段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 &文本)const所以:
int pixelwide = fm。boundingRect(" text的width是多少").width();
相关文章:
- 当套接字连接断开时检测C/C++Unix
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 将结构字段的类型展开为可变模板参数
- 如何通过套接字将文本文件的内容从服务器发送到客户端
- 如何在C/C++中用FD_set Unix设置套接字文件描述符
- 套接字读取后,我在缓冲区中看到意外输入
- 将位字段导出到数组
- 为了方便起见,我应该避免公开私有字段变量吗
- 将QGraphicsItem的移动区域限制在多边形区域内
- 当字段可以为null时,如何使用C++接口在Avro中写入数据
- 在java中读取c++字节的位字段
- 如何在CPP中创建应该在Windows和Linux上运行的套接字?
- 链接器找不到在虚拟类 c++ 中访问的静态字段的符号
- 我可以与 python 服务器而不是 c++ 客户端建立 tcp/ip 套接字吗?
- 我是 c++ 的新手.学习基本知识后,我想做井字游戏.对于印刷板,我在下面写代码,但它显示错误
- 私有字段对象与私有继承?
- 套接字连接"Operation not permitted"错误,甚至使用升压/平发器根.cpp
- 当我从下面的代码中删除关键字 virtual 时,它可以正常工作,否则会出现错误。在这里"virtual"字的意义是什么?
- 声明没有默认构造函数的字段
- WINAPI 注册应用程序重新启动时不清除打开的套接字