Search code examples
pythonimagepython-2.7user-interfacepyqt4

How to insert a QImage into an NxN grid layout in PyQt4?


I have a 4x4 grid in a grid layout in PyQt4:

self.grid = QtGui.QGridLayout()
        pos = [(0, 0), (0, 1), (0, 2),(0, 3),
               (1, 0), (1, 1), (1, 2), (1, 3),
               (2, 0), (2, 1), (2, 2), (2, 3),
               (3, 0), (3, 1), (3, 2), (3, 3)]

        for position in pos:
            button = QtGui.QPushButton('button 1')
            self.grid.addWidget(button, position[0], position[1])

        self.setLayout(self.grid)
        self.move(300, 150)
        self.show()

What I need is to replace the QPushButtons with grids that contain images, so that it forms a 4X4 grid of images. Towards that, I know that I will have to use QImage but am not exactly sure how! Could anyone please help me out?

Thanks


Solution

  • One way to do this would be to use a QLabel and add the images using setPixmap. The pixmaps themselves can be created directly from a file-path.

    Here's a simple example (specifiy the image file-path as an argument to the script):

    from PyQt4 import QtCore, QtGui
    
    class Window(QtGui.QWidget):
        def __init__(self, path):
            QtGui.QWidget.__init__(self)
            pixmap = QtGui.QPixmap(path)
            layout = QtGui.QGridLayout(self)
            for row in range(4):
                for column in range(4):
                    label = QtGui.QLabel(self)
                    label.setPixmap(pixmap)
                    layout.addWidget(label, row, column)
    
    if __name__ == '__main__':
    
        import sys
        app = QtGui.QApplication(sys.argv)
        window = Window(sys.argv[1] if len(sys.argv) else '')
        window.setGeometry(500, 300, 300, 300)
        window.show()
        sys.exit(app.exec_())