Sample easy and good work alignment in QGraphicsTextItem

Qt Code:
  1. class DiagramTextItem : public QGraphicsTextItem
  2. {
  3. Q_OBJECT
  4.  
  5. public:
  6. enum { Type = UserType + 3 };
  7. DiagramTextItem(QGraphicsItem *parent = 0, QGraphicsScene *scene = 0);
  8. void setBoundingRect( qreal x, qreal y, qreal w, qreal h);
  9. void setText( const QString &inText );
  10.  
  11. signals:
  12.  
  13. protected:
  14. void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0);
  15. QRectF boundingRect() const;
  16.  
  17. private:
  18. QRectF myBoundRect;
  19. QTextOption textOp;
  20. QString text;
  21. };
To copy to clipboard, switch view to plain text mode 

Qt Code:
  1. DiagramTextItem::DiagramTextItem(QGraphicsItem *parent, QGraphicsScene *scene)
  2. : QGraphicsTextItem(parent, scene)
  3. {
  4. myBoundRect.setRect( 0, 0, 0, 0 );
  5.  
  6. textOp.setAlignment( Qt::AlignCenter );
  7. textOp.setWrapMode( QTextOption::WrapAtWordBoundaryOrAnywhere );
  8. }
  9.  
  10. void DiagramTextItem::paint(QPainter *painter, const QStyleOptionGraphicsItem
  11. *option, QWidget *widget)
  12. {
  13. //painter->drawRect( boundingRect() );
  14.  
  15. painter->drawText( boundingRect(),
  16. text,
  17. textOp);
  18.  
  19. QGraphicsTextItem::paint(painter, option, widget);
  20. }
  21.  
  22. QRectF DiagramTextItem::boundingRect() const
  23. {
  24. return myBoundRect;
  25. }
  26.  
  27. void DiagramTextItem::setBoundingRect( qreal x, qreal y, qreal w, qreal h)
  28. {
  29. myBoundRect.setRect( x, y, w, h );
  30. }
  31.  
  32. void DiagramTextItem::setText( const QString &inText )
  33. {
  34. text = inText;
  35. update();
  36. }
To copy to clipboard, switch view to plain text mode