PyQt events

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

PyQt implements not only signal and slots for handling actions. There are also events that occur for example when we press a mouse button, a key, move the cursor, or timer runs out of time. For example QListWidget has a signal "itemClicked", which is send when an item is clicked - by any mouse button. If we want more controll over mose clicks we can use events like:
mouseReleaseEvent (self, QMouseEvent e)
mousePressEvent (self, QMouseEvent e)
To use an event we have to make our own class that inherits the widget we want to use. Our class must have methods named as events that we want to use (like those two examples). Event object will be under the method argument. Here is an working example:
# -*- coding: utf-8 -*-
import sys

from PyQt4 import QtCore, QtGui

class FileManagerWidget(QtGui.QListWidget):
	def __init__(self, parent=None):
		"""
		QListWidget with handling of mouse events - left and right clicks
		"""
		super(FileManagerWidget, self).__init__(parent)
		
		# configure the items list
		self.setViewMode(QtGui.QListView.IconMode)
		self.setLayoutMode(QtGui.QListView.SinglePass)
		self.setResizeMode(QtGui.QListView.Adjust)
		self.setGridSize(QtCore.QSize(75, 75))
	
	def mouseReleaseEvent(self, event):
		"""
		mouse button release event
		"""
		button = event.button()
		# select an item on which we clicked
		item = self.itemAt(event.x(), event.y())
		if item:
			self.setCurrentItem(item)
			if button == 1:
				print 'SIMPLE LEFT CLICK'
	
	def mousePressEvent(self, event):
		"""
		mouse clicks events
		"""
		button = event.button()
		item = self.itemAt(event.x(), event.y())
		if item:
			# select the item we clicked
			self.setCurrentItem(item)
			if button == 1:
				print 'LEFT CLICK - DRAG'
		if button == 2:
			print 'RIGHT CLICK'

app = QtGui.QApplication(sys.argv)

f = FileManagerWidget()
for i in range(1,20):
	f.addItem(unicode(i))
f.show()

sys.exit(app.exec_())
We made our own class that inherits QListWidget, and we defined two methods for two events. QMouseEvent hidden under event argument contains such methods as "x()" and "y()" which contain the place location on the widget where the click/release occurred. The button() method will inform us which button was used. Also we use some QListWidget methods like very nice one: itemAt(X, Y), which will return the item if any under X, Y coordinates. We select the item we click on. Just save the code in a file and run it from a terminal - and when you click on an item - event messages will be printed there.
RkBlog

PyQt and GUI, 8 December 2008


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