Skip to content

Commit

Permalink
fix: correct resolution of icons on high DPI screens. #9
Browse files Browse the repository at this point in the history
  • Loading branch information
knipknap committed Feb 21, 2024
1 parent f2c5862 commit b3e71b4
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 15 deletions.
2 changes: 1 addition & 1 deletion btl/ui/shapewidget.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
6 changes: 3 additions & 3 deletions btl/ui/tablecell.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down Expand Up @@ -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)

Expand Down
25 changes: 14 additions & 11 deletions btl/ui/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

0 comments on commit b3e71b4

Please sign in to comment.