如何在 pyqt 中解决启用 DPI 缩放后 QIcon 模糊的问题

Python 投稿 64300 0 评论

如何在 pyqt 中解决启用 DPI 缩放后 QIcon 模糊的问题

问题描述

启用 DPI 缩放后,文字不会有太明显的锯齿问题,但是使用  设置的图标却会显得很模糊。比如下述代码:

# coding:utf-8
import os
import sys

from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QPushButton, QWidget


class Demo(QWidget):

    def __init__(self):
        super().__init__(parent=None)
        self.resize(300, 300)
        self.button = QPushButton(' Shuffle all', self)
        self.button.setIcon(QIcon("Shuffle.png"))
        self.button.move(self.width()//2-self.button.width()//2,
                         self.height()//2-self.button.height()//2)


if __name__ == '__main__':
    os.environ["QT_ENABLE_HIGHDPI_SCALING"] = "0"
    os.environ["QT_SCALE_FACTOR"] = '1.25'
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    app.exec_()

运行结果如下图所示,可以看到图标的锯齿现象非常明显:

问题解决

# coding:utf-8
from PyQt5.QtCore import QPoint, QRect, QSize, Qt
from PyQt5.QtGui import QIcon, QIconEngine, QImage, QPixmap, QPainter


class PixmapIconEngine(QIconEngine):
    """ Pixmap icon engine """

    def __init__(self, iconPath: str):
        self.iconPath = iconPath
        super().__init__()

    def paint(self, painter: QPainter, rect: QRect, mode: QIcon.Mode, state: QIcon.State):
        painter.setRenderHints(QPainter.Antialiasing |
                               QPainter.SmoothPixmapTransform)
        painter.drawImage(rect, QImage(self.iconPath))

    def pixmap(self, size: QSize, mode: QIcon.Mode, state: QIcon.State) -> QPixmap:
        pixmap = QPixmap(size)
        pixmap.fill(Qt.transparent)
        self.paint(QPainter(pixmap), QRect(QPoint(0, 0), size), mode, state)
        return pixmap


class Icon(QIcon):

    def __init__(self, iconPath: str):
        self.iconPath = iconPath
        super().__init__(PixmapIconEngine(iconPath))

接着只要把  换成 ,并开启 ,就能解决图标模糊的问题了,效果如下图所示:

编程笔记 » 如何在 pyqt 中解决启用 DPI 缩放后 QIcon 模糊的问题

赞同 (50) or 分享 (0)
游客 发表我的评论   换个身份
取消评论

表情
(0)个小伙伴在吐槽