QGraphicsView and QGraphicsScene

Check out the new site at https://rkblog.dev.

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_())
Scenes can also be rendered with OpenGL, which is handy and efficient for images and multimedia processing. To use OpenGL only one line of code is needed:
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_())
The result will be the same:
qgraphicsview
QGraphicsView and QGraphicsScene have a lot of features. For example if we want to scale the image to the window size we can use events:
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_())
We made our own class that inherits QGraphicsView, so we can use resizeEvent event. The event object is QResizeEvent, which has the current size of the scene. When we have the size we can scale the pixmap to that size and update the pixmap used by the scene.
RkBlog

PyQt and GUI, 15 December 2008


Check out the new site at https://rkblog.dev.
Comment article
Comment article RkBlog main page Search RSS Contact