From b3e71b462f10ea22520483227bcce9cf2226b21e Mon Sep 17 00:00:00 2001 From: Samuel Abels Date: Wed, 21 Feb 2024 21:49:56 +0100 Subject: [PATCH] fix: correct resolution of icons on high DPI screens. #9 --- btl/ui/shapewidget.py | 2 +- btl/ui/tablecell.py | 6 +++--- btl/ui/util.py | 25 ++++++++++++++----------- 3 files changed, 18 insertions(+), 15 deletions(-) diff --git a/btl/ui/shapewidget.py b/btl/ui/shapewidget.py index 5380f4f..8ebd52a 100644 --- a/btl/ui/shapewidget.py +++ b/btl/ui/shapewidget.py @@ -21,7 +21,7 @@ def _update_icon(self): icon_ba = QtCore.QByteArray(icon_bytes) if icon_type == 'svg': - icon = qpixmap_from_svg(icon_ba, self.icon_size) + icon = qpixmap_from_svg(icon_ba, self.icon_size, self.devicePixelRatio()) elif icon_type == 'png': icon = qpixmap_from_png(icon_ba, self.icon_size) diff --git a/btl/ui/tablecell.py b/btl/ui/tablecell.py index e2909c4..a9671ea 100644 --- a/btl/ui/tablecell.py +++ b/btl/ui/tablecell.py @@ -49,6 +49,7 @@ def __init__ (self, parent=None): self.label_left.setAlignment(QtCore.Qt.AlignCenter|QtCore.Qt.AlignVCenter) self.label_left.setStyleSheet(style) + self.icon_size = QtCore.QSize(50, 60) self.icon_widget = QtGui.QLabel() style = "color: {}".format(fg_color.name()) @@ -116,12 +117,11 @@ def set_icon_from_shape(self, shape): if not icon_type: return icon_ba = QtCore.QByteArray(icon_bytes) - icon_size = QtCore.QSize(50, 60) if icon_type == 'svg': - icon = qpixmap_from_svg(icon_ba, icon_size) + icon = qpixmap_from_svg(icon_ba, self.icon_size, self.devicePixelRatio()) elif icon_type == 'png': - icon = qpixmap_from_png(icon_ba, icon_size) + icon = qpixmap_from_png(icon_ba, self.icon_size) self.set_icon(icon) diff --git a/btl/ui/util.py b/btl/ui/util.py index ef16ac1..51d4e13 100644 --- a/btl/ui/util.py +++ b/btl/ui/util.py @@ -17,16 +17,19 @@ def qpixmap_from_png(byte_array, icon_size): pixmap = QtGui.QPixmap(icon_size) pixmap.fill(QtGui.Qt.transparent) pixmap.loadFromData(byte_array) - return pixmap.scaled(icon_size) + return pixmap.scaled(icon_size, QtCore.Qt.KeepAspectRatio) -def qpixmap_from_svg(byte_array, icon_size): - svg_widget = QtSvg.QSvgWidget() - svg_widget.setFixedSize(icon_size) - svg_widget.load(byte_array) - svg_widget.setStyleSheet("background-color: rgba(0,0,0,0)") +def qpixmap_from_svg(byte_array, icon_size, ratio=1.0): + render_size = QtCore.QSize(icon_size.width()*ratio, icon_size.height()*ratio) - # Convert the QSvgWidget to QPixmap - pixmap = QtGui.QPixmap(icon_size) - pixmap.fill(QtGui.Qt.transparent) - svg_widget.render(pixmap) - return pixmap + image = QtGui.QImage(render_size, QtGui.QImage.Format_ARGB32) + image.fill(QtGui.Qt.transparent) + painter = QtGui.QPainter(image) + + data = QtCore.QXmlStreamReader(byte_array) + renderer = QtSvg.QSvgRenderer(data) + renderer.setAspectRatioMode(QtCore.Qt.KeepAspectRatio) + renderer.render(painter) + painter.end() + + return QtGui.QPixmap.fromImage(image)