c++qtqgraphicsviewqgraphicssceneqgraphicswidget

Drawing Text In a QGraphicsWidget::paint function


I'm trying to draw text inside a qgraphicswidget. The scale of the scene is -180 to 180 in the horizontal and -90 to +90 in the vertical (it's a world map).

When i zoom in to individual items on the map, i want some text to show up. My code for the paint function of one particular item looks like this:

void AirportGraphicsWidget::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) {

    QPen pen;
    pen.setStyle(Qt::PenStyle::NoPen);
    painter->setBrush(Qt::lightGray);
    painter->setPen(pen);

    if (m_curr_lod <= LevelOfDetail::MEDIUM) {
        painter->setBrush(QColor(206, 211, 219));
        painter->drawEllipse(m_airport_significance_rect);
    } else if(m_curr_lod == LevelOfDetail::HIGH) {
        painter->setBrush(QColor(56, 55, 52, 150));
        painter->drawEllipse(m_airport_boundary);    
        DrawRunways(painter, option, widget);
    } else {
        painter->setBrush(QColor(56, 55, 52));
        painter->drawEllipse(m_airport_boundary);    
        pen.setStyle(Qt::PenStyle::SolidLine);
        pen.setColor(Qt::black);
        painter->setPen(pen);
        DrawRunways(painter, option, widget);
        DrawILS(painter, option, widget);
        DrawCOM(painter, option, widget);

        QPen pen;
        pen.setStyle(Qt::PenStyle::SolidLine);
        pen.setColor(Qt::white);
        pen.setWidth(0);
        QFont font("Arial");
        font.setPixelSize(15);
        painter->setFont(font);
        painter->setPen(pen);
        painter->drawText(m_airport_boundary, "TEST");
    }
}

The drawText call does not seem to be working at all. My scale at this zoom level is very small. The m_airport_boundary QRectF variable has the following values: { x = -0.010286252057250001, y = -0.010286252057250001, width = 0.020572504114500002, height = 0.020572504114500002 }

the drawing of the m_airport_boundary rect is visible so I know im trying to draw in the correct location. Can anyone tell me what I'm doing wrong?

Screenshot of what is drawing... The dark circle is the m_airport_boundary ellipse. Green things are a result of DrawILS and the blue circle is DrawCOM

enter image description here


Solution

  • The current QTransform scale is affecting the font size.

    I suggest to calculate the text position in screen space, reset the transform and then call drawText().

    Here is a snippet (suppose you want to draw at the center):

    QPointF pos = m_airport_boundary.center();
    QTransform t = painter->transform();
    painter->resetTransform();
    pos = t.map(pos);
    
    painter->drawText(pos, "TEST");