#include <QGraphicsWidget>#include <QString>class QGraphicsLabel : public QGraphicsWidget{ QString ftext; Qt::Alignment ftextAligment;protected: void changeEvent(QEvent *event); QRectF boundingRect() const; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);public: QGraphicsLabel(QGraphicsItem * parent = 0, Qt::WindowFlags wFlags = 0); QString text() const; void setText(QString Text); Qt::Alignment textAligment() const; void setTextAligment(Qt::Alignment TextAligment);};
#include <QPainter>#include "qgraphicslabel.h"QGraphicsLabel::QGraphicsLabel(QGraphicsItem * parent, Qt::WindowFlags wFlags) :QGraphicsWidget(parent,wFlags){ ftextAligment = Qt::AlignLeft|Qt::AlignVCenter;}QString QGraphicsLabel::text() const{ return ftext;}void QGraphicsLabel::setText(QString Text){ if(ftext!=Text) { ftext = Text; QFontMetrics metrics(font()); QSize _size = metrics.size(ftextAligment,ftext); resize(_size.width(),_size.height()); update(); }}Qt::Alignment QGraphicsLabel::textAligment() const{ return ftextAligment;}void QGraphicsLabel::setTextAligment(Qt::Alignment TextAligment){ if(ftextAligment!=TextAligment) { ftextAligment = TextAligment; update(); }}void QGraphicsLabel::changeEvent(QEvent *event){ switch(event->type()) { case QEvent::Resize: break; case QEvent::FontChange: update(); break; default: return; }}QRectF QGraphicsLabel::boundingRect() const{ return QRectF(0,0,size().width(),size().height());}void QGraphicsLabel::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){ painter->setPen(Qt::white); painter->drawText(rect(),ftextAligment,ftext);}