如何在PyQt窗口中加载位图
我现在有一个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_())
补充说明:根据《快速GUI编程与Qt和Python》的内容:
根据PyQt的文档,QPixmap是为了在屏幕上显示而优化的(所以绘制速度很快),而QImage则是为了编辑而优化的(这就是我们用它来保存图像数据的原因)。
我有一个复杂的算法会生成我想在窗口上显示的图片。这些图片生成得很快,所以对用户来说,看起来就像动画一样(每秒可能会有15张以上,20张以上)。那么我应该使用QPixmap还是QImage呢?
2 个回答
1
关于这个讨论,最快的方法是使用GLPainter,这样可以利用显卡的性能。
2
试试这样做,你可以使用这个链接 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_())