PDA

View Full Version : QTextLayout draws text outside the widget



alpinista
22nd October 2009, 09:50
Hi all,

Working on simple CAD application using QGraphicsView/QGraphicsScene, I'm trying to implement a 'text entity' derived from QGraphicsItem. (something like the QGraphicsSimpleTextItem).
Inside this item I'm using the QTextLayout::draw() to draw the text. And this is the problem. The text is drawn also outside the view widget (QGraphicsView) as shows the attached image.

Has anybody an idea how to solve this? I can also post a code ...
Thans a lot

Tomas

Lykurg
22nd October 2009, 12:52
WTF? Wow, what have you done to achieve that? :D

I can also post a code ...
That would be the easiest way, because I can imagine some errors...

alpinista
23rd October 2009, 06:25
yeah, it's pretty strange :)

here's the code:


/**
*
*
*/
void CTextItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
if (isSelected())
painter->setPen(_sel_pen);
else
painter->setPen(_std_pen);


_layout->draw(painter, QPointF(0, -_line_height));


// draw cursor
if (_draw_cursor)
{
painter->setPen(_cur_pen);
painter->drawLine(_lastline_width, boundingRect().bottom(), _lastline_width + Lexo2D::Const::DEFAULT_TEXT_SIZE, boundingRect().bottom());
}


// for debugging purposes ...
if (Lexo2D::Debug::show_bounding_rectangles)
{
// draw bounding rectangle
painter->setPen(QColor(255, 0, 0));
painter->drawRect(boundingRect());

// draw shape
painter->setPen(QColor(255, 255, 0));
painter->drawPath(_shape);
}
}



/**
*
*
*/
void CTextItem::setText(QString & str)
{
_layout->setText(str);

setupLayout();
}




/**
*
*
*/
void CTextItem::setupLayout()
{
_layout->beginLayout();

while (_layout->createLine().isValid())
;

_layout->endLayout();

_shape = QPainterPath();
qreal height = 0;
qreal width = 0;

for (int i = 0; i < _layout->lineCount(); ++i)
{
QTextLine line = _layout->lineAt(i);
width = qMax(width, line.naturalTextWidth());
_lastline_width = line.naturalTextWidth();

line.setPosition(QPointF(0, height));
height += line.height();

_shape.addRect(line.naturalTextRect().translated(0 , -line.height()));
}


if (_layout->lineCount() > 0)
_line_height = _layout->lineAt(0).height();

prepareGeometryChange();

_bounding_rect = _layout->boundingRect();
_bounding_rect.setWidth(width + Lexo2D::Const::DEFAULT_TEXT_SIZE);
_bounding_rect.translate(0, -_line_height);

update();
}