Important: Please read the Qt Code of Conduct -

drawText with different fonts?

  • This is my idea, I have a custom Text object with a QString and some other extra data like location and font.
    So the idea is to loop through every bit of text and output to screen. What I try to do is change the font just before the drawText, but it doesn't seem to work. So when I add a text the first time it's ok, but on the 2nd time when it's a different font, both changes to the latest font, and when I use the debugger, the 2 fonts in the 2 texts are different. But this isn't reflected on screen.

    for (std::shared_ptr<Text> currentElement : drawnLayout->getTextList())
            int currentX = currentElement->getLocationX();
            int currentY = currentElement->getLocationY();
            int minCoordinateX = (offsetX * canvasSizeX);
            int maxCoordinateX = ((offsetX+1) * canvasSizeX);
            int minCoordinateY = ((offsetY-1) * canvasSizeY);
            int maxCoordinateY = (offsetY*canvasSizeY);;
            int minDisplayX = (offsetX * canvasSizeX);
            int maxDisplayY = (offsetY*canvasSizeY);
            if (currentX >= minCoordinateX && currentX <= maxCoordinateX)
                if (currentY >= minCoordinateY && currentY <= maxCoordinateY)
                    int displayX = currentX- minDisplayX;
                    int displayY = 0-(currentY - maxDisplayY);
                    painter.drawText(displayX, displayY, currentElement->getReadableText());

  • Use painter.setFont() instead.

  • Moderators

    @jkwok678 by calling setFont on the (presumably) parent widget instead of the QPainter, you set the font on the parent and that is cascading down to its children -> you see only one font for all texts

Log in to reply