Python Pyqt5 QDateEdit获取日期字符串

时间:2019-12-20 11:27:01

标签: python python-3.x qt pyqt5 qdateedit

我正在尝试使用Pyqt5 QDateEdit构建日期打印机。我可以弹出日历,但是我想在控制台中(或窗口中的标签中)写入单击日期的字符串。我尝试了print(self.calendarWidget().document().toPlainText())print(self.calendarWidget().currentText()),但是没有用。

我使用此代码;

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_())

它的语法是什么?我没有找到足够的文档。你能帮忙吗?

1 个答案:

答案 0 :(得分:0)

编辑:答案

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_())