QDateEdit widget does not respond to setSelectedSection

allenwjohnson11084 | 2022-08-09 11:10:08 UTC | #1

Want to use QDateEdit with default SectionIndex set to the day. Index displays correct value, but the display and arrow keys respond as if it is still set to the default (month). Is this a bug or am I reading the documentation incorrectly? Extracted code:

python
import sys
import PyQt5.QtWidgets as qtw
import PyQt5.QtCore as qtc

class Window(qtw.QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("QDateEdit")
        self.setGeometry(100, 100, 500, 400)

        self.dateEdit = qtw.QDateEdit(self, calendarPopup=True)
        self.dateEdit.setGeometry(100, 100, 150, 40)
        self.label1 = qtw.QLabel("", self)
        self.label1.setGeometry(100, 150, 200, 60)
        self.label2 = qtw.QLabel("", self)
        self.label2.setGeometry(100, 170, 200, 60)

        self.dateEdit.dateChanged.connect(lambda: self.dateChanged())
        self.dateEdit.setDate(qtc.QDate.currentDate())
        self.dateEdit.setDisplayFormat('MM-dd-yy')

        si = self.dateEdit.currentSectionIndex()
        print(f'default currentSectionIndex ({si})')

        self.dateEdit.setSelectedSection(qtw.QDateTimeEdit.DaySection)

        si = self.dateEdit.currentSectionIndex()
        print(f'after setSelectedSection.DaySection: currentSectionIndex({si})')
        self.show()

    def dateChanged(self):
        strDate = self.dateEdit.date().toString(qtc.Qt.ISODate)
        self.label1.setText(f'changed date({strDate})')
        si = self.dateEdit.currentSectionIndex()
        self.label2.setText(f'currentSectionIndex({si})')

App = qtw.QApplication([])
window = Window()
sys.exit(App.exec())
  • Python 3.8.10
  • Qt 5.12.8
  • PyQt 5.14.1

Create GUI Applications with Python & Qt5 by Martin Fitzpatrick — (PyQt5 Edition) The hands-on guide to making apps with Python — Over 15,000 copies sold!

More info Get the book

Mark As Complete
Martin Fitzpatrick

QDateEdit widget does not respond to setSelectedSection was written by Martin Fitzpatrick .

Martin Fitzpatrick has been developing Python/Qt apps for 8 years. Building desktop applications to make data-analysis tools more user-friendly, Python was the obvious choice. Starting with Tk, later moving to wxWidgets and finally adopting PyQt. Martin founded PythonGUIs to provide easy to follow GUI programming tutorials to the Python community. He has written a number of popular Python books on the subject.