Reputation: 902
In a pyqt project, I'm using a QDateEdit widget to let the user select dates. The widget returns year, month and day. How can I apply a constraint to this widget to be sure that the user can only select a day equal to 1, 11 or 21?
A simple approach would be to connect a validation function to the event triggered when a value is set, for example by rounding the date to the closest 01, 11 or 21. But I would prefer to offer only to choose one of those 3 days.
Upvotes: 1
Views: 1413
Reputation: 6065
Here's my idea: subclass QDateEdit
and use the dateChanged
signal.
You define a list of valid days (valid=[1,11,21]
) and a dictionary to match regular days to the corresponding valid day. For example, let's say the current day is 1. When the user press the up arrow, the day will be changed to 2 (next "regular day"). We want the day to be changed to 11 (next "valid day"). So in the dictionary, you will have a key {2:11}
.
You can quickly wrote the dictionary by hand:
match={2:11,10:1,12:21,20:11,22:21}
Whenever the date is changed, you first check if the day has changed (if day in self.valid
).
If it has changed, you defined the new valid date thanks to the dictionary, and set it with setDate
.
class customDate(QtGui.QDateEdit):
def __init__(self,parent):
super(customDate, self).__init__(parent)
self.dateChanged.connect(self.on_change)
self.valid=[1,11,21]
self.match={2:11,10:1,12:21,20:11,22:21}
def on_change(self,date):
day=date.day()
if day in self.valid:
return
newDay=self.match[day]
newDate=QtCore.QDate(date.year(),date.month(),newDay)
self.setDate(newDate)
Upvotes: 2