calendardtedit.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #include "calendardtedit.h"
  2. #include <QDebug>
  3. #include <QApplication>
  4. #include <QDesktopWidget>
  5. #include <QKeyEvent>
  6. #include <QEvent>
  7. #include "calendarex.h"
  8. CalendarDTEdit::CalendarDTEdit(QWidget *parent) : QDateTimeEdit(parent)
  9. {
  10. setCalendarPopup(false);// 阻止自带的日历窗口
  11. }
  12. CalendarDTEdit::~CalendarDTEdit()
  13. {
  14. }
  15. void CalendarDTEdit::CloseCalendar()
  16. {
  17. }
  18. /* 手动触发日期选择弹框 */
  19. void CalendarDTEdit::triggerCalendarPopup()
  20. {
  21. }
  22. /**
  23. * @brief 设置手动禁止修改日期区域,只能使用弹窗
  24. *
  25. * @param value 是否禁止修改日期区域
  26. * @param triggerPopup 点击日期区域是否会跳出弹窗
  27. */
  28. void CalendarDTEdit::setManualDisableEdit(bool value, bool triggerPopup)
  29. {
  30. if(value)
  31. {
  32. setReadOnly(true);
  33. for(auto& it : children())
  34. {
  35. if(it->objectName() == "qt_spinbox_lineedit")
  36. {
  37. m_pCalendar = it;
  38. m_pCalendar->installEventFilter(this);
  39. }
  40. }
  41. }else {
  42. setReadOnly(false);
  43. if(m_pCalendar != nullptr)
  44. {
  45. m_pCalendar->removeEventFilter(this);
  46. m_pCalendar = nullptr;
  47. }
  48. }
  49. m_isPopup = triggerPopup;
  50. }
  51. void CalendarDTEdit::mousePressEvent(QMouseEvent *e)
  52. {
  53. Q_UNUSED(e);
  54. CalendarEx *pC = new CalendarEx(date());
  55. if (nullptr == pC) return;
  56. connect(pC, &CalendarEx::sig_DateChanged, this, [this](const QDate& date){
  57. if (date.isValid()) {
  58. setDate(date);
  59. }
  60. });
  61. pC->show();
  62. pC->positionCalendarPopup(this);
  63. }
  64. bool CalendarDTEdit::eventFilter(QObject* watched, QEvent* event)
  65. {
  66. if(watched == m_pCalendar)
  67. {
  68. if(event->type() == QEvent::MouseButtonPress)
  69. {
  70. // qDebug() << "点击了日期区域";
  71. if(m_isPopup)
  72. {
  73. mousePressEvent(nullptr);
  74. }
  75. }
  76. }
  77. return QDateTimeEdit::eventFilter(watched, event);
  78. }