C++ (Qt)QRectF YourItem::boundingRect(void) const{ QFontMetrics fm(font()); return fm.boundingRect(text()); }
#include <QGraphicsScene>Legend::Legend(QGraphicsItem *parent, QString caption) : QGraphicsItem(parent) { setCacheMode(DeviceCoordinateCache); setZValue(8); //angle=10000.0; this->setFlag(QGraphicsItem::ItemIgnoresTransformations, true); this->caption = caption; QPainter p; QFontMetrics fm(p.font()); QRectF rect=fm.boundingRect(caption); this->myrect=rect;}void Legend::setRect(QRectF rect) { this->myrect = rect;}void Legend::setCaption(QString caption) { this->caption = caption; update();}QString Legend::getCaption() { return this->caption;}QRectF Legend::boundingRect() const { return this->myrect;}QPainterPath Legend::shape() const { QPainterPath path; path.addRect(this->myrect); return path;}void Legend::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { if (this->myrect == QRectF(0, 0, 1000, 30)) { QRectF rect = painter->boundingRect(QRect(0, 0, 1000, 30), this->caption); this->myrect.setWidth(rect.width() + 4); this->myrect.setHeight(rect.height() + 2); } else { painter->setRenderHints(QPainter::Antialiasing, false); painter->setPen(QPen(Qt::black, 0)); painter->setBrush(Qt::white); painter->drawRect(this->myrect); painter->drawText(this->myrect.x() + 3, this->myrect.y() + this->myrect.height() - 3, this->caption); }}
C++ (Qt)....QFontMetrics fm(QApplication::font ());QRectF rect=fm.boundingRect(caption);...