SVG icons with PyQt on Windows and Linux

4.7k views Asked by At

I have a PyQt user interface as follows

import sys
from PyQt4 import QtGui

class Example(QtGui.QMainWindow):

    def __init__(self, parent=None):
        super(Example, self).__init__(parent)
        self.setWindowTitle('Example')
        self.setWindowIcon(QtGui.QIcon('note_add.svg'))        


def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

It works fine on Linux but it doesn't work well on Windows, because the SVG icon doesn't appear. I have two questions:

  1. What is the proper way to use SVG icons with PyQt on Windows?
  2. Is there a way to change the color fill of an SVG icon on the fly? This should work fine on both operating systems.
1

There are 1 answers

0
Higgsy On

I know this is a few years late. But, better late than never. :)

For me, Qt works best when I define a specific directory. So, I'd implement this as so:

import sys
import os
from PyQt4 import QtGui

class Example(QtGui.QMainWindow):

    def __init__(self, parent=None):
        super(Example, self).__init__(parent)

        ###   Newly added code   ###
        self.current_directory  = os.path.dirname(__file__)
        self.note_icon      = os.path.join( self.current_directory, 'note_add.svg' )
        ###   ###   ###   ###

        self.setWindowTitle('Example')
        self.setWindowIcon(QtGui.QIcon(self.note_icon))        

    def main():

        app = QtGui.QApplication(sys.argv)
        ex = Example()
        ex.show()
        sys.exit(app.exec_())

if __name__ == '__main__':
    main()