Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将QImage插入PyQt4中的NxN网格布局?_Python_Python 2.7_User Interface_Pyqt4 - Fatal编程技术网

Python 如何将QImage插入PyQt4中的NxN网格布局?

Python 如何将QImage插入PyQt4中的NxN网格布局?,python,python-2.7,user-interface,pyqt4,Python,Python 2.7,User Interface,Pyqt4,我在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)]

我在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()
我需要的是用包含图像的网格替换
QPushButton
s,以便它形成一个4X4图像网格。为此,我知道我将不得不使用
QImage
,但不确定如何使用!谁能帮我一下吗


谢谢

这样做的一种方法是使用,并使用添加图像。可以直接从文件路径创建文件本身

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


谢谢你@EKHUMO。这就是我要找的。一般来说,这两种方式中哪一种是“首选”方式—QImage还是QPixmap?这两者是如何相互竞争的?QPixmap经过优化,可以在屏幕上显示图像。QImage更低级,设计用于直接访问像素。显示图像的小部件(比如QLabel)通常会有一个设置QPixmap的方法,但不用于QImage;因此,QImage首先需要转换为pixmap。QPixmap可能是通用GUI设计中最常用的图像类;其他三个图像类(QImage、QBitmap和QPicture)更专业。
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_())