QGraphicsTextItem and path
I am sure this has been asked before.
I am trying to retrieve the path outline of the text that would be contained within a QGraphicsTextItem. I do not see a method to do this in the class.
I tried taking the text and putting it directly into a QPainterPath. This gets me close to what I need, but they don’t quite line up. Below is a piece of code that shows what I am referring too.
- for (int i = 0; i < 10; i++) //draw reference lines
- QFont font = pText->font();
- QPainterPath text;
- text.addText(pText->pos(), pText->font(), pText->toPlainText());
- QPainterPath path = pText->mapToScene(text);
- QPen penLine;
- pScene->addRect(pText->boundingRect(), penLine);
- pScene->addRect(path.boundingRect(), penLine);
What is the proper means to do this? It needs to be able to handle different fonts and sizes and matrix transformations on the QGraphicsTextItem (ie scaling, rotation, translation, etc).
I am working with Qt 4.8 if that matters.
Thanks in advance for any suggestions.
So I finally had some time to work on this some more and made a little headway on it but still have some alignment issues.
I found that I needed to adjust my path positioning by the document margin and by the ascent of the font used to get some fonts, like the default and Brush Script MT, to align up. But other fonts, like Arial, are still off a small amount (mostly vertically). The below code should show this. Also it seems to be more pronounced on my Mac OS X Lion then on my Windows 7.
- #include <QApplication>
- #include <QGraphicsScene>
- #include <QGraphicsView>
- #include <QGraphicsPathItem>
- #include <QGraphicsTextItem>
- #include <QTextDocument>
- #include <QDebug>
- int main(int argc, char *argv)
- QApplication a(argc, argv);
- pScene->setSceneRect(0, 0, 500, 500);
- QPen p;
- p.setColor(QColor(100, 200, 100));
- //QFont font;
- //QFont font("Brush Script MT");
- QFont font("Arial");
- QFontMetrics f(font);
- //create graphic text item
- pText->setPos(100, 100);
- qDebug() << pText->font().family();
- //create path of graphic text item
- QPainterPath path;
- path.addText(QPointF(0, 0), pText->font(), pText->toPlainText());
- //create graphic path item from path
- pPath->setPos(100 + pText->document()->documentMargin(), 100 + pText->document()->documentMargin() + f.ascent());
- return a.exec();
Is there another value that I need to be applying that I am missing? Something from the font metrics or document settings/layout?
Hope someone has some ideas. Oh I have tried Qt 4.7.4, 4.8.0, and 4.8.1 and it has been off in all of them. No, I have not tried a ton of fonts to see which ones were and were not off.