Suppose you have a file named iconLable.py like above, and someone want to use it as a module in his/her program, like:
The problem is the above file only works when started from the same folder where iconLabel.py is saved. The module file should be put away into sys.path, so Python can find and import the module no matter where the program is started. Typically module files go to C:\Python26\Lib\site-packages
To test if it works, lauch Python command line, try:
Another problem is those icon images, circle and square, are lost. Relative file path like:
only works when the file is started from the same path where the images are saved. Using absolute path:
image = QtGui.QPixmap('D:/somewhere/circle.png')
still cannot work because everyone to use the module should have a copy of those images in the same path.
Resources will be the solution. Save a .qrc file, iconLabel.qrc:
<!DOCTYPE RCC><RCC version="1.0"> <qresource> <file>circle.png</file> <file>square.png</file> </qresource> </RCC>
pyrcc4 iconLabel.qrc -o iconLabel_rc.py
Will create a module file, iconLabel_ry.py, contains those images. Inside iconLabel.py:
and change all file path to start with ‘:’, i.e.
desc.image_path = ':circle.png'
Run the module file again, Python will create binary code for both iconLabel and iconLabel_rc. Copy both .pyc files to sys.path, and this module is ready to go. You can remove iconLabel.py from sys.path, just use the .pyc files. This will be helpful in case you don’t want to give up your source code.
For more details about Qt resources, go here.