Module And Resources

https://github.com/spinos/aphid/blob/master/pyqtmodule/iconLabel.py

Suppose you have a file named iconLable.py like above, and someone want to use it as a module in his/her program, like:

https://github.com/spinos/aphid/blob/master/pyqtmodule/testIconLabel.py

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:

import iconLabel

Another problem is those icon images, circle and square, are lost. Relative file path like:

image= QtGui.QPixmap('./circle.png')

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>

Run command:

pyrcc4 iconLabel.qrc -o iconLabel_rc.py

Will create a module file, iconLabel_ry.py, contains those images. Inside iconLabel.py:

import iconLabel_rc

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.

Advertisements

Leave a comment

Filed under Python, Qt

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s