Graphics and resources

Our crop simulation is nearly complete, there is one major task remaining: providing a visual representation* of the crop growth. To accomplish this we will need to be familiar with how PyQt handles graphics but before we dive into that we must first consider how we provide our images to PyQt.

Resource files

To use graphics within PyQt we can either provide:

  1. A file path to each image
  2. A resource file that bundles all of the images together

Providing the file path to each image seems the easier option - as long as PyQt can find each image on your hard disk then this will work but crucially it makes it more difficult to distribute code as a stand-alone application. Therefore, we will take the time to create a resource file which will produce a single python module containing all of the images our application needs. If we ever decide to create a stand-alone application using a utility such as cx_freeze then it will much easier for us to do so.

The video demonstrates how to produce a resource file for our graphics. Pay close attention to the section relating to the ``pyrcc4'' command as this step will require you to make use of either the Terminal (Mac OS X) or the Command Prompt (Windows).


Task 5a

Use the above video to create the image resource file.


Graphics in PyQt

In order to display a visual representation of a crop in our interface we must understand how PyQt uses graphics. The animation below covers the basic concepts you need to be aware of.

Explanation of Graphics in PyQt

CropView

To represent our crops we are going to create a sub-class of QGraphicsView called CropView which will be set-up with all of the required scenes and items necessary to show the status of each crop. Doing this means we can reduce the complexity of the layout code (as all of the code associated with the construction of the graphics is moved to another module) and also it provides us with a widget that we could reuse in future.

CropView class diagram

You can see from the above class diagram the CropView will have a method called switch_scene() that can be used to easily switch between the different graphical representations of the crop.

The video demonstrates how to create this class and associated sub-classes.


Task 5b

Use the above video to create the crop view widget class.


Updating the crop's visual status

Now that we have the WheatView and PotatoView classes we can complete our user interface. The WheatView or PotatoView will be placed in (0,0) of our grid on the crop status view layout:

Crop status view layout design

Once this is in place we can then improve the update_crop_view_status() method to switch to the correct visual representation depending on the current status of the crop.

The video demonstrates how to do this.


Task 5c

Use the above video to add the ability to display a visual indicator of the crop status and complete the crop simulation.