学习Qt也有几个月了,渐渐的喜欢上了Qt,以此来记录Qt开发中遇到的问题:
QDatetimeEdit是常用的日期编辑控件,但官方的该控件并不能显示为空值。近期测试那边新提需求希望日期编辑控件默认为空值,这对于一个新人来说有些莫名奇妙,但考虑到还在实习期人微言轻,只能默默承受。虽然听起来不难,但实现起来还是花了不少时间,希望能帮助有类似需求的同学。
QDateTimeEdit的默认显示
点击上或下箭头后的显示
以下为.h头文件内容
#ifndef BLANKDATETIMEEDIT_H
#define BLANKDATETIMEEDIT_H
#include <QDateTimeEdit>
#include <QLineEdit>
#include <QDebug>
class BlankDateTimeEdit : public QDateTimeEdit
{
Q_OBJECT
public:
explicit BlankDateTimeEdit(QWidget *parent = 0);
public:
void SetNull(bool NullSwitch);//设置是允许为空
protected:
virtual QValidator::State validate(QString &input, int &pos) const override;
virtual QString textFromDateTime(const QDateTime &dt) const override;
void focusInEvent(QFocusEvent *e)override;//重写获取焦点函数,使其获取焦点时正常显示时间
void mousePressEvent(QMouseEvent *e)override;//重写鼠标按下函数
private:
bool m_NullSwitch;//是否允许为空
};
#endif // BLANKDATETIMEEDIT_H
以下为.cpp文件函数的具体实现
#include "blankdatetimeedit.h"
BlankDateTimeEdit::BlankDateTimeEdit(QWidget *parent) :
QDateTimeEdit(parent),m_NullSwitch(true)
{
this->setParent(parent);
lineEdit()->clear();
}
void BlankDateTimeEdit::SetNull(bool NullSwitch)
{
m_NullSwitch=NullSwitch;
if(m_NullSwitch)
{
lineEdit()->clear();
}
else
{
this->setDateTime(QDateTime::currentDateTime());
}
}
//QDateTime调用此虚拟函数以确定输入是否有效,pos参数表示字符串中的位置
QValidator::State BlankDateTimeEdit::validate(QString &input, int &pos) const
{
qDebug()<<"validate"<<input<<" "<<pos;
if(m_NullSwitch)
{
input="";
return QValidator::Intermediate;
}
return QDateTimeEdit::validate(input,pos);
}
QString BlankDateTimeEdit::textFromDateTime(const QDateTime &dt) const
{
return QDateTimeEdit::textFromDateTime(dt);
}
//用在嵌入式里获取焦点弹出键盘,并正常显示
//注意页面只有这一个控件时,页面初显示时会使此控件获取焦点,正常显示
void BlankDateTimeEdit::focusInEvent(QFocusEvent *e)
{
if(0 == this->text().length())
{
// SetNull(false);
return;
}
QDateTimeEdit::focusInEvent(e);
}
void BlankDateTimeEdit::mousePressEvent(QMouseEvent *e)
{
if(0 == this->text().length())
{
SetNull(false);
return;
}
QDateTimeEdit::mousePressEvent(e);
}