【问题标题】:How to load a bitmap on a window on PyQt如何在 PyQt 的窗口上加载位图
【发布时间】:2010-12-15 08:37:48
【问题描述】:

我目前有一个 PIL 图像,我想在 PyQt 窗口上显示它。我知道这一定很容易,但我在任何地方都找不到如何做到这一点。谁能帮我解决这个问题? 这是我目前拥有的窗口的代码:

import sys
from PyQt4 import QtGui

class Window(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Window')


app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())

编辑:根据 Rapid Gui Programming with Qt and Python:

根据 PyQt 的文档, QPixmaps 针对屏幕进行了优化 显示(因此它们可以快速绘制), 和 QImages 针对编辑进行了优化 (这就是为什么我们用它们来 保存图像数据)。

我有一个复杂的算法,可以生成我想在我的窗口上显示的图片。它们的创建速度非常快,因此对用户来说它们看起来就像一个动画(每秒可能有 15+、20+ 个)。我应该使用 QPixmaps 还是 QImages?

【问题讨论】:

    标签: python pyqt pyqt4


    【解决方案1】:

    试试这样的方法,你可以使用http://svn.effbot.org/public/stuff/sandbox/pil/ImageQt.py 将任何 pil 图像转换为 qimage

    import sys
    from PyQt4 import QtGui
    from PIL import Image
    
    def get_pil_image(w, h):
        clr = chr(0)+chr(255)+chr(0)
        im = Image.fromstring("RGB", (w,h), clr*(w*h))
        return im
    
    def pil2qpixmap(pil_image):
        w, h = pil_image.size
        data = pil_image.tostring("raw", "BGRX")
        qimage = QtGui.QImage(data, w, h, QtGui.QImage.Format_RGB32)
        qpixmap = QtGui.QPixmap(w,h)
        pix = QtGui.QPixmap.fromImage(qimage)
        return pix
    
    class ImageLabel(QtGui.QLabel):
        def __init__(self, parent=None):
            QtGui.QLabel.__init__(self, parent)
    
            self.setGeometry(300, 300, 250, 150)
            self.setWindowTitle('Window')
    
            self.pix = pil2qpixmap(get_pil_image(50,50))
            self.setPixmap(self.pix)
    
    app = QtGui.QApplication(sys.argv)
    imageLabel = ImageLabel()
    imageLabel.show()
    sys.exit(app.exec_())
    

    【讨论】:

    • 只是一个挑剔的选择,但您的实例化不应该以小写字母 imageLabel 开头。
    【解决方案2】:

    关于this discussion,最快的方法是使用 GLPainter 以提高显卡性能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-27
      • 2015-06-10
      • 2017-07-10
      • 2012-05-17
      • 2010-12-06
      • 1970-01-01
      • 2015-02-19
      相关资源
      最近更新 更多