1

I want to draw a character aligned to the top-left corner of parent.

QGraphicsTextItem * tItem = new QGraphicsTextItem(parent);
tItem->setPlainText("a"); 
tItem->setPos(QPointF(0,0));

Picture below presents output of my code (grey rectangle is parent of QGraphicsTextItem)

Result:

Result

I want to get a result like this:

My dream result:

My dream result

I tried to use Qt::AlignLeft and Qt::AlignTop but to no avail.

Kurt Pattyn
  • 2,758
  • 2
  • 30
  • 42
Newbie
  • 249
  • 1
  • 2
  • 8

1 Answers1

0

The solution is to use setDocumentMargin(0) to the QTextDocument, if you only put the letter "a" it seems that it is not the solution since there seems to be a vertical offset, but in reality it is not an offset but the capital letters have a higher height.

Example:

#include <QApplication>
#include <QGraphicsTextItem>
#include <QGraphicsView>
#include <QTextDocument>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QGraphicsScene scene;
    QGraphicsView view(&scene);
    auto parent = scene.addRect(QRectF(0, 0, 100, 100),  QPen(Qt::red), QBrush(Qt::blue));

    auto * tItem = new QGraphicsTextItem(parent);
    tItem->setPlainText("aAbB");
    tItem->document()->setDocumentMargin(0);
    view.show();
    return a.exec();
}

enter image description here

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Thanks you for help. For me solution is using QGraphicsSimpleTextItem and translate by value calculate by QFontMetricsF::tightBoundingRect / QFontMetricsF::boundingRect. – Newbie Aug 16 '18 at 08:19