0

Using a .SVG as the image for a button in PyQt5 and Qt Designer

I'm trying to use an .SVG as the image for a button in PyQt5, however it seems this is only supported in PyQt6 (tried and worked great, but PyQt6 doesn't support other things, like QtCore.Qt.AA_EnableHighDpiScaling, so I can't switch).

I've tried importing only the QIcon from PyQt6 but naturally this doesn't work.

It doesn't have to be on a button, as long as I can call a function from it with clicked.connect()

I'm aware of the QSvgWidget class but there doesn't appear to be a clear way to use/add this in QtDesigner. The buttons in question are embedded within a few layouts with spacers so adding in the QSvgWidget without designer wouldn't work either.

Is there a way for me to add a widget in Qt Designer, add an .SVG to it, and call a function from it when clicked? I am trying to get DpiScaling to work across multiple scaled monitors and the .SVG icons scale way nicer than .PNG.

Example code only runs with a .ui from designer, but illustrates the desired outcome.

from PyQt5 import QtWidgets, uic, QtCore, QtGui
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        #Need the widget to be in the .ui file from Qt Designer
        uic.loadUi("assets/mainwindow.ui", self)

        #QPushButton - it doesn't have to be this class as long as I can use a .SVG on it and call a function on click
        self.svg_button.setIcon(QtGui.QIcon('assets/copy.svg'))
        self.svg_button.setIconSize(QtCore.QSize(25,25))
        self.svg_button.clicked.connect(self.something)

    def something(self):
        print('i have an svg icon, woohoo')

def main():
    app = QtWidgets.QApplication([sys.argv])
    window = MainWindow()
    window.show()
    sys.exit(app.exec())

if __name__ == '__main__':
    main()
lachesis
  • 1
  • 2

0 Answers0