Search code examples
qtpositionalignmentqgraphicstextitem

QT : QGraphicsTextItem alignment char to top-left corner


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.


Solution

  • 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