pythonpython-3.xqtpyqt5qdateedit

Python Pyqt5 QDateEdit Get Date String


I'm trying to build a date printer using Pyqt5 QDateEdit. I can popup the calendar, but I want to write the clicked date's string in the console (or in a label in window). I tried print(self.calendarWidget().document().toPlainText()) or print(self.calendarWidget().currentText()) but it didn't work.

I use this code;

from PyQt5 import QtCore, QtWidgets


class DateEdit(QtWidgets.QDateEdit):
    popupSignal = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super(DateEdit, self).__init__(parent)
        self.setCalendarPopup(True)
        self.calendarWidget().installEventFilter(self)

    def eventFilter(self, obj, event):
        if self.calendarWidget() is obj and event.type() == QtCore.QEvent.Show:
            self.popupSignal.emit()
        return super(DateEdit, self).eventFilter(obj, event)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = DateEdit()
    w.popupSignal.connect(lambda: print("popup"))
    w.show()
    sys.exit(app.exec_())

What is its syntax? I didn't find enough documentation for it. Can you help please?


Solution

  • EDIT: The answer

    from PyQt5 import QtCore, QtGui, QtWidgets
    from PyQt5.QtGui import QPixmap
    from PyQt5.QtWidgets import *
    
    class MyWindow(QtWidgets.QWidget):
        def __init__(self, parent=None):
            super(MyWindow, self).__init__(parent)
    
            self.dateEdit = QDateEdit(self)
            self.lbl = QLabel()
            self.dateEdit.setMaximumDate(QtCore.QDate(7999, 12, 28))
            self.dateEdit.setMaximumTime(QtCore.QTime(23, 59, 59))
            self.dateEdit.setCalendarPopup(True)
    
            layout = QGridLayout()
            layout.addWidget(self.dateEdit)
            layout.addWidget(self.lbl)
            self.setLayout(layout)
    
    
            self.dateEdit.dateChanged.connect(self.onDateChanged)
    
        def onDateChanged(self, qDate):
            print('{0}/{1}/{2}'.format(qDate.day(), qDate.month(), qDate.year()))
    
    
    if __name__ == "__main__":
        import sys
    
        app = QtWidgets.QApplication(sys.argv)
        app.setApplicationName('MyWindow')
    
        main = MyWindow()
        main.show()
    
        sys.exit(app.exec_())