QDateEdit

The QDateEdit widget is used to let users select and edit dates.

In this example, we’ll create a QDateEdit object and set it to display as the current date.

For further details, check QDateEdit official document .


Example

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QDateEdit, QVBoxLayout
from PyQt5.QtCore import QDate


class MyApp(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        lbl = QLabel('QDateEdit')

        dateedit = QDateEdit(self)
        dateedit.setDate(QDate.currentDate())
        dateedit.setMinimumDate(QDate(1900, 1, 1))
        dateedit.setMaximumDate(QDate(2100, 12, 31))
        # dateedit.setDateRange(QDate(1900, 1, 1), QDate(2100, 12, 31))

        vbox = QVBoxLayout()
        vbox.addWidget(lbl)
        vbox.addWidget(dateedit)
        vbox.addStretch()

        self.setLayout(vbox)

        self.setWindowTitle('QDateEdit')
        self.setGeometry(300, 300, 300, 200)
        self.show()


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

QDateEdit appears on the window.


Description

dateedit = QDateEdit(self)
dateedit.setDate(QDate.currentDate())
dateedit.setMinimumDate(QDate(1900, 1, 1))
dateedit.setMaximumDate(QDate(2100, 12, 31))

Create a date edit widget using the QDateEdit class.

In the setDate method, type QDate.currentDate() to display the current date when the program runs

SetMinimumDate and setMaximumDate allow you to limit the range of dates that you can select.

The minimum date is set to September 14, 1752 by default, and the maximum date is set to December 31, 9999.

The minimum date must be at least January 1, 100.


# dateedit.setDateRange(QDate(1900, 1, 1), QDate(2100, 12, 31))

The setDateRange method is the same as using setMinimumDate and setMaximumDate at the same time.


vbox = QVBoxLayout()
vbox.addWidget(lbl)
vbox.addWidget(dateedit)
vbox.addStretch()

self.setLayout(vbox)

Use the vertical box layout to position the label and date editing widget vertically and set it as the layout of the entire widget.


Results

../_images/4_16_qdateedit.png ../_images/4_16_qdateedit_mac.png

Figure 5-16. Using QDateEdit for date editing widget.


Prev/Next

Next :