QDateEdit widget does not respond to setSelectedSection

Heads up! You've already completed this tutorial.

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

Packaging Python Applications with PyInstaller by Martin Fitzpatrick — This step-by-step guide walks you through packaging your own Python applications from simple examples to complete installers and signed executables.

More info Get the book

Well done, you've finished this tutorial! Mark As Complete
[[ user.completed.length ]] completed [[ user.streak+1 ]] day streak

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.