PDA

View Full Version : TextDocumentLayout problem with registerHandler



'milimoj
9th June 2015, 20:04
Hi,
I have a problem with handler for custom item in my QTextDocument. I created a handler which should draw one item with some text "XX" at the begining of the block. When block has only one line or more then one words in first line it is OK like this:

XX some text

but when block has only one long word broken into multiple lines XX item does not stay inline with text. Like this:

XX
somelargertextthatisb
brokeninmorethanone
lineinblock

I wanth it to look something like this:

XX somelargertextth
atisbrokeninmoretha
nonelineinblock

or XX can be on left margin of the block inline with first block line.

My handler code is:


QSizeF MyHandler::intrinsicSize(QTextDocument * doc, int posInDocument,
const QTextFormat &format)
{
QTextCharFormat charFormat = format.toCharFormat();
QFont font(charFormat.font());

QTextBlock blk = doc->findBlock(posInDocument);

if(!blk.isValid()){
qDebug() << "IS Block Not Valid";
return QSize();
} else {
QTextLayout* layout = blk.layout();
if(layout->lineCount()==0){
qDebug() << "IS lineCount: " << layout->lineCount();
return QSize();
}
}

QFontMetrics fontMetrics(font);

QSize size;
size.setHeight(fontMetrics.height());
size.setWidth(fontMetrics.width(QLatin1Char('0'))* 3);
return QSizeF(size);
}



void MyHandler::drawObject(QPainter *painter, const QRectF &rect,
QTextDocument * doc, int posInDocument,
const QTextFormat &format)
{
QTextBlock blk;
QTextCursor* cursor = new QTextCursor(doc);
cursor->setPosition(posInDocument);

if(posInDocument<0){
qDebug() << "DO posInDocument: " << posInDocument;
return;
} else {
blk = doc->findBlock(posInDocument);
if(!blk.isValid()){
qDebug() << "DO Block Not Valid";
return;
}
}

if(blk.blockNumber() < 0)
return;

QString imageText = "XX "; // I put just XX for simlicity , but in fact this two characters are created here with call to function createText();

if(imageText.isEmpty())
return;

QTextCharFormat charFormat = format.toCharFormat();
QFont font(charFormat.font());

QTextLayout *layout = blk.layout();
if (layout->lineCount() == 0)
return;

QTextLine firstLine = layout->lineAt(0);
QRectF lineRect = firstLine.rect();
QRectF naturalRect = firstLine.naturalTextRect();
QRectF blockRect = doc->documentLayout()->blockBoundingRect(blk);

QRectF rect1(rect);
rect1.moveBottom(lineRect.bottom()+blockRect.y());
rect1.moveLeft(naturalRect.x());

painter->setFont(font);
painter->drawText(rect1, Qt::AlignBottom, imageText);
}



I used QChar::ObjectReplacementCharacter to insert item:



...
QTextCharFormat crFormat = charFormat;
cFormat.setObjectType(MyItem::Type);
cFormat.setProperty(HeaderItemProperty, QString(""));

cursor->insertText(QString(QChar::ObjectReplacementCharact er), svgCharFormat);

...



And registered handler in my QGraphicTextItem with:


...
document()->documentLayout()->registerHandler( MyItem::Type, myHandlerObject);
...



What I did wrong?