QT 在QCustomCalendarWidget添加今天按钮

QDateEdit可以弹出日期选择框

 

 qt默认的日期选择窗口是不带today按钮的,如何添加按钮快速定位到今天日期呢?

我们可以自定义一个类通过继承QCalendarWidget的形式来实现

详细代码演示

.h头文件

#ifndef QCUSTOMCALENDARWIDGET_H
#define QCUSTOMCALENDARWIDGET_H
#include "custom_global.h"
#include <QCalendarWidget>
class QHBoxLayout;
class MYEXPORT QCustomCalendarWidget : public QCalendarWidget
{
Q_OBJECT
public:
QCustomCalendarWidget(QWidget *parent);
~QCustomCalendarWidget();
private:
QHBoxLayout* hboxLayoutOuter;
private:
void initBottomWidget();
void initUi();
};
#endif // QCUSTOMCALENDARWIDGET_H

.cpp文件

#include "QCustomCalendarWidget.h"
#include "qboxlayout.h"
#include "qpushbutton.h"
QCustomCalendarWidget::QCustomCalendarWidget(QWidget *parent):
QCalendarWidget(parent)
{
initUi();
initBottomWidget();
}

QCustomCalendarWidget::~QCustomCalendarWidget()
{

}

void QCustomCalendarWidget::initBottomWidget()
{
QWidget* bottomWidget = new QWidget(this);
bottomWidget->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred);

QHBoxLayout* hboxLayout = new QHBoxLayout;


QSpacerItem * spcer1 = new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
hboxLayout->addItem(spcer1);

QPushButton *totayBtn = new QPushButton(this);
totayBtn->setText(tr("today"));
hboxLayout->addWidget(totayBtn);

spcer1 = new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
hboxLayout->addItem(spcer1);

bottomWidget->setLayout(hboxLayout);

connect(totayBtn,&QPushButton::clicked,this,[this]()
{
this->setSelectedDate(QDate::currentDate());
});
this->layout()->addWidget(bottomWidget);
}

void QCustomCalendarWidget::initUi()
{
setNavigationBarVisible(false);
setVerticalHeaderFormat(QCalendarWidget::NoVerticalHeader);
}

通过上述源码就是实现了QDateEdit弹出日期窗口的自定义

然后可以在其他文件里面通过如下代码来使用这个自定义的类

QCustomCalendarWidget *customCalendarWidget = new QCustomCalendarWidget(this);

QDateEdit *dateEdit = new QDateEdit(this);
dateEdit ->setCalendarWidget(customCalendarWidget);

即可完成自定义窗口

需要注意的地方是QCustomCalendarWidget *customCalendarWidget = new QCustomCalendarWidget(this); 

new这个对象的时候注意把当前窗口作为父对象传给它,因为引用官网上的一句话

void QDateTimeEdit::setCalendarWidget(QCalendarWidget *calendarWidget)

Sets the given calendarWidget as the widget to be used for the calendar pop-up. The editor does not automatically take ownership of the calendar widget

 

calendar widget并不会自动把editor作为自己的父控件,为了避免内存泄漏,在new calendar widget把当前窗口传给它作为父对象即可。

 

PS:如果你有什么好方法,或者有什么需要指正的地方,请在下面留言,知识因为分享而变得更加美好

 

posted @ 2021-03-03 14:44  beautifulday  阅读(577)  评论(0编辑  收藏  举报