QGraphicsView and QGraphicsScene
Check out the new site at https://rkblog.dev.
15 December 2008
Comments
QGraphicsView is a class that offers a widget for visualizing QGraphicsScene objects - surfaces with lot of 2D elements. Scene can contain various elements (added with addEllipse(), addLine(), addPath(), addPixmap(), addPolygon(), addRect() or addText()) and display them in given way. Here is an example of displaying an image:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
app = QApplication(sys.argv)
grview = QGraphicsView()
scene = QGraphicsScene()
scene.addPixmap(QPixmap('pic.jpg'))
grview.setScene(scene)
grview.show()
sys.exit(app.exec_())
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtOpenGL import *
app = QApplication(sys.argv)
grview = QGraphicsView()
grview.setViewport(QGLWidget())
scene = QGraphicsScene()
scene.addPixmap(QPixmap('pic.jpg'))
grview.setScene(scene)
grview.show()
sys.exit(app.exec_())

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class ImageView(QGraphicsView):
def __init__(self, parent=None, origPixmap=None):
"""
QGraphicsView that will show an image scaled to the current widget size
using events
"""
super(ImageView, self).__init__(parent)
self.origPixmap = origPixmap
QMetaObject.connectSlotsByName(self)
def resizeEvent(self, event):
"""
Handle the resize event.
"""
size = event.size()
item = self.items()[0]
# using current pixmap after n-resizes would get really blurry image
#pixmap = item.pixmap()
pixmap = self.origPixmap
pixmap = pixmap.scaled(size, Qt.KeepAspectRatio, Qt.SmoothTransformation)
self.centerOn(1.0, 1.0)
item.setPixmap(pixmap)
app = QApplication(sys.argv)
pic = QPixmap('pic.jpg')
grview = ImageView(origPixmap=pic)
scene = QGraphicsScene()
scene.addPixmap(pic)
grview.setScene(scene)
grview.show()
sys.exit(app.exec_())
RkBlog
Check out the new site at https://rkblog.dev.
Comment article