J. Doe
J. Doe

Reputation: 102

Why is increasing the DPI of my QImage also increasing the size of my text?

Typically, when we increase DPI without changing anything else, the image/text should decrease in size. This is because more dots/pixels are drawn per inch, hence, decreasing the size. However, I have found the opposite behaviour here where increasing the DPI will also increase the size of my drawn text. This is not what I expected, would anybody know why?

import sys

from PyQt6.QtCore import Qt
from PyQt6.QtGui import QFont, QImage, QPainter
from PyQt6.QtWidgets import QApplication, QMainWindow, QWidget

DEFAULT_WIDTH = DEFAULT_HEIGHT = 250


class QPainterWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.image = QImage(DEFAULT_WIDTH, DEFAULT_HEIGHT, QImage.Format.Format_RGB32)
        self.image.fill(Qt.GlobalColor.green)
        self.image.setDevicePixelRatio(1)
        print(self.image.dotsPerMeterX())
        self.image.setDotsPerMeterX(25000) # 5000, 10000, 15000, 20000
        self.image.setDotsPerMeterY(25000)
        
        painter = QPainter(self.image)
        
        point_size_font = QFont('arial')
        point_size_font.setPointSizeF(1)
        painter.setFont(point_size_font)
        painter.drawText(0, 0, DEFAULT_WIDTH//2, DEFAULT_HEIGHT//2, Qt.AlignmentFlag.AlignCenter, "point font text")
        painter.end()

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawImage(0, 0, self.image)      
        painter.end()


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.resize(DEFAULT_WIDTH, DEFAULT_HEIGHT)
        self.setCentralWidget(QPainterWidget())


app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()

Upvotes: 0

Views: 449

Answers (1)

G.M.
G.M.

Reputation: 12879

I'm not really sure where the confusion lies. You have...

self.image.setDotsPerMeterX(25000)
self.image.setDotsPerMeterY(25000)

which tells Qt that the QImage is to be treated as having a resolution of 625 dpi. You then select a font with size 1pt using...

point_size_font = QFont('arial')
point_size_font.setPointSizeF(1)
painter.setFont(point_size_font)

1pt is 1/72 inches which combined with the 625 dpi resolution evaluates to approximately 9 'pixels'. Hence the underlying paint device will draw the text with a 9 pixel high font.

Upvotes: 1

Related Questions