View Full Version : Subscript text in painter->drawTExt(..)
maverick_pol
7th January 2008, 21:32
Hi,
I have used the subscript text while create a QGraphicsTextItem(using setHTML("<sub>...</sub>"), but now I need to draw the subscript text using a painter.
Possibly I will use the painter->drawText(...), but how to construct a QString with a subscript text?
Thanks for any ideas.
Maverick
jpn
8th January 2008, 07:07
How about using QTextLayout?
Uwe
8th January 2008, 07:58
void drawRichText(QPainter *painter, const QRect &rect, int flags, QTextDocument &text)
{
text.setPageSize(QSize(rect.width(), QWIDGETSIZE_MAX));
QAbstractTextDocumentLayout* layout = text.documentLayout();
const int height = qRound(layout->documentSize().height());
int y = rect.y();
if (flags & Qt::AlignBottom)
y += (rect.height() - height);
else if (flags & Qt::AlignVCenter)
y += (rect.height() - height)/2;
QAbstractTextDocumentLayout::PaintContext context;
context.palette.setColor(QPalette::Text, painter->pen().color());
painter->save();
painter->translate(rect.x(), y);
layout->draw(painter, context);
painter->restore();
}
If you need additional operations like heightForWidth() or textSize() you can have a look at the implementation of QwtRichTextEngine in the Qwt package.
And yes, you can ask yourself, why you have to write this strange code for such a simple task.
HTH,
Uwe
maverick_pol
8th January 2008, 21:09
Hi,
Thanks both of You! So what which solutions is better? Let's say I want to draw a text("upper <sub>lower</sub>"at QPointF(10,10). How to use QTextlayout to do this? I am not quite sure.
Let's say that I set a var containing my text like this:
QTextDocument* text = new QTextDocument(0);
text->setHtml("upper<sub>lower</sub>");
and now I need to draw the text in QPointF(10,10);
Isn't there a simpler way than using your function Uwe? Just wondering.
Thanks.
Maverick
Uwe
9th January 2008, 07:05
Isn't there a simpler way than using your function Uwe?
My code always prints the labels into a rect. In your case you can skip the alignment lines and have to adopt it to paint to a position. But the basics of the code will remain as ugly as it is.
I guess Scribe is designed for implementing something big like an office package and maybe it's ok for this - I never wrote one myself. But for the use case of drawing simple rich text labels, almost nobody ( I also had to ask the TrollTech support and it's by far not the first time I'm posting this code) will find the right code on his own. For a product, that takes care of a clean API, this is a very surprising situation.
If you have a commercial license you could also have a look at the MathML renderer in the Qt solution package.
Uwe
Powered by vBulletin® Version 4.2.5 Copyright © 2024 vBulletin Solutions Inc. All rights reserved.