PDA

View Full Version : QGraphicsTextItem Vertical text alignment



mbra
16th October 2009, 18:43
My label creator application requires to align text(QGraphicsTextItem) horizontaly and vertically within a given boundingRect.
So far I'm NOT able to come up with a way to make vertical alignment work for Qt::AlignTop, Qt::AlignBottom, and Qt::AlignVCenter.
Horizontal alignment works ok.

Any suggestion for making vertical alignment work in a QGraphicsTextItem?:confused:


QRectF BaseTextItem::boundingRect() const
{
return QRectF(0,0,310,100);

}
void BaseTextItem::alignVerticalTest()
{
QTextDocument *text_document = this->document();
QTextOption alignment_option(Qt::AlignBottom);
text_document->setDefaultTextOption(alignment_option);
this->setDocument(text_document);
}

Lykurg
16th October 2009, 19:08
Wouldn't it be easier if you use a normal item and do the painting yourself? then you could use QPainter::drawText().
QPainter painter(this);
painter.drawText(boundingRect(), Qt::AlignCenter, tr("Qt by\nNokia"));

If you have to use a text item I think (it's long time ago) you have to set the page size of the document to the bounding rect: QTextDocument::setPageSize().

Jarikus
15th October 2011, 04:12
Sample easy and good work alignment in QGraphicsTextItem



class DiagramTextItem : public QGraphicsTextItem
{
Q_OBJECT

public:
enum { Type = UserType + 3 };
DiagramTextItem(QGraphicsItem *parent = 0, QGraphicsScene *scene = 0);
void setBoundingRect( qreal x, qreal y, qreal w, qreal h);
void setText( const QString &inText );

signals:

protected:
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0);
QRectF boundingRect() const;

private:
QRectF myBoundRect;
QTextOption textOp;
QString text;
};




DiagramTextItem::DiagramTextItem(QGraphicsItem *parent, QGraphicsScene *scene)
: QGraphicsTextItem(parent, scene)
{
myBoundRect.setRect( 0, 0, 0, 0 );

textOp.setAlignment( Qt::AlignCenter );
textOp.setWrapMode( QTextOption::WrapAtWordBoundaryOrAnywhere );
}

void DiagramTextItem::paint(QPainter *painter, const QStyleOptionGraphicsItem
*option, QWidget *widget)
{
//painter->drawRect( boundingRect() );

painter->drawText( boundingRect(),
text,
textOp);

QGraphicsTextItem::paint(painter, option, widget);
}

QRectF DiagramTextItem::boundingRect() const
{
return myBoundRect;
}

void DiagramTextItem::setBoundingRect( qreal x, qreal y, qreal w, qreal h)
{
myBoundRect.setRect( x, y, w, h );
}

void DiagramTextItem::setText( const QString &inText )
{
text = inText;
update();
}