Making It Scalable


So our Four-Image program is a little inefficient. It would be nice if we didn’t have to write a separate event handler for each image, since the code is virtually the same for each one. Our current program does not scale up well. For example, if we want to make a Memory Game with 18 cards, our current implementation would require 18 click handlers.

A New Layout

Thankfully, we can do better. First, let’s implement a new layout container, the QGridLayout. This container divides its contents into a grid of cells (rows and columns) similar to a spreadsheet. Creating one is simple.

# Set up QGridLayout
glo = QtGui.QGridLayout()

We can add images to this layout in nearly the same way we added them to the QHBoxLayout, with the addition of the row and column location of the image.

pixmap = QtGui.QPixmap('someimage.png')
mylabel = ExtendedQLabel(self)
glo.addWidget(mylabel,r,c) # r = row, c = column

Event Handlers

But how does this help up reduce the number of event handlers? Well, it doesn’t by itself. When a signal is sent to an event handler function, we can find out which object sent the signal by calling self.sender(). We do not need one function for each image.  We simply need a function that can handle all of the images. Our previous image1Clicked() function becomes:

# **************************************************
def imageClicked(self):
	sender = self.sender()
	pixmap = QtGui.QPixmap(self.images[randint(0,3)])


Use these new concepts (the QGridLayout and the self.sender() function) to re-implement your Clickable Images program as discussed in class.  When complete, submit your code with the name using his submission link.