0

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()

J. Doe
  • 92
  • 5

1 Answers1

1

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.

G.M.
  • 12,232
  • 2
  • 15
  • 18
  • I found it a little less intuitive, but working it out by hand I did the calculations for 5000DPM (127dpi) which came out to 1.7 (2px) high (Y axis). I just thought that by decreasing the dots per inch, while having a fixed size it should increase the same. For example, if I had a 100x100 image on a 100X dpi 100Y dpi monitor. It should come out to 1 inch by 1 inch, however if it was a 1dpi by 1dpi monitor, it will come out as 100 by 100 inches, thus, increasing the image size by lowering the dpi. However, the inverse seems to happen with fonts? – J. Doe Oct 03 '22 at 20:45