How can I capture all mouse events in a widget descended from a Qt widget in PyQt?

StackOverflow https://stackoverflow.com/questions/1716916

  •  19-09-2019
  •  | 
  •  

Question

In particular, I'm inheriting from QCalendarWidget and I want to override the mousePressEvent method to filter what dates are allowed to be selected (disjoint set, not a simple range). But when I override the method, it doesn't catch any events that are going to child widgets inside the calendar. How can I do this?

Was it helpful?

Solution

I'm surprised that overriding mousePressEvent doesn't work for a QCalendarWidget. It works for most other widgets. After looking at the docs for QCalendarWidget, I notice there's a clicked signal. If you connect that it works.

import sys

from PyQt4 import QtGui, QtCore

class MyCalendar(QtGui.QCalendarWidget):
    def __init__(self):
        QtGui.QCalendarWidget.__init__(self)
        self.connect(self, QtCore.SIGNAL("clicked(QDate)"), self.on_click)
        self.prev_date = self.selectedDate()

    def on_click(self, date):
        if self.should_ignore(date):
            self.setSelectedDate(self.prev_date)
            return
        self.prev_date = date

    def should_ignore(self, date):
        """ Do whatever here """
        return date.day() > 15

app = QtGui.QApplication(sys.argv)
cal = MyCalendar()
cal.show()
app.exec_()

I'd never checked out QCalendarWidget before. Pretty sweet little widget.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top