如何在 PyQt4 中将 QImage 插入到 NxN 网格布局中?

gra*_*tii 2 python user-interface image pyqt4 python-2.7

我在 PyQt4 的网格布局中有一个 4x4 网格:

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()
Run Code Online (Sandbox Code Playgroud)

我需要的是QPushButton用包含图像的网格替换s,以便它形成一个 4X4 的图像网格。为此,我知道我将不得不使用,QImage但不确定如何使用!有人可以帮我吗?

谢谢

ekh*_*oro 6

一种方法是使用QLabel并使用setPixmap添加图像。该像素图本身可以直接从一个文件路径来创建。

这是一个简单的示例(将图像文件路径指定为脚本的参数):

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_())
Run Code Online (Sandbox Code Playgroud)

  • QPixmap 针对在屏幕上显示图像进行了优化。QImage 更底层,专为直接访问像素而设计。显示图片的widget(比如QLabel)通常会有设置QPixmap的方法,但是对于QImage没有;所以 QImage 需要先转换为像素图。QPixmap 可能是一般 GUI 设计最常用的图像类;其他三个图像类(QImage、QBitmap 和 QPicture)更专业。 (2认同)