在Qt框架中,QDateEdit
是一个用于编辑日期的控件,如果想要删除QDateEdit不是特别好做,如果直接获取QDateEdit中的QLineEdti并设置显示删除按钮(代码如下所示),删除按钮会一直显示,效果并不好,所以继承QDateEdit重新定义样式是比较方便。
QLineEdit *lineEdit = pDateEdit->findChild<QLineEdit*>();
lineEdit->setClearButtonEnabled(true);
头文件:
class customDateEdit :public QDateEdit
{
Q_OBJECT
public:
explicit customDateEdit();
~customDateEdit();
public slots:
void slot_clearDate();
protected:
bool eventFilter(QObject *obj, QEvent *event) override;
void focusOutEvent(QFocusEvent *event) override;
private:
void init();
void updateClearBtnPosition(QLineEdit *lineEdit);// 更新清除按钮的位置
private:
QToolButton *m_pBtnClear = nullptr;
QLineEdit *m_pLineEdit = nullptr;
};
源文件:
customDateEdit::customDateEdit()
{
init();
}
customDateEdit::~customDateEdit()
{
}
void customDateEdit::slot_clearDate()
{
this->setSpecialValueText(" ");
m_pLineEdit->clear();
}
bool customDateEdit::eventFilter(QObject * obj, QEvent * event)
{
if (obj == this->findChild<QLineEdit*>()) {
if (event->type() == QEvent::Resize) {
QLineEdit *lineEdit = qobject_cast<QLineEdit*>(obj);
if (lineEdit) {
updateClearBtnPosition(lineEdit);
}
}
else if (event->type() == QEvent::MouseMove) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
QLineEdit *lineEdit = qobject_cast<QLineEdit*>(obj);
if (lineEdit) {
// 计算清除按钮的位置
int clearButtonWidth = m_pBtnClear->sizeHint().width();
int clearButtonX = lineEdit->width() - clearButtonWidth;
if (mouseEvent->pos().x() >= clearButtonX) {
//如果文本框中有内容再显示
if (lineEdit->text().size() > 0)
{
// 显示清除按钮
m_pBtnClear->show();
}
}
else {
// 隐藏清除按钮
m_pBtnClear->hide();
}
}
}
else if (event->type() == QEvent::Leave) {
QLineEdit *lineEdit = qobject_cast<QLineEdit*>(obj);
if (lineEdit) {
// 隐藏清除按钮
m_pBtnClear->hide();
}
}
}
return QDateEdit::eventFilter(obj, event);
}
void customDateEdit::focusOutEvent(QFocusEvent * event)
{
//以免失去焦点自动setDate
QDateEdit::focusOutEvent(event);
}
void customDateEdit::init()
{
// 获取QLineEdit控件
m_pLineEdit = findChild<QLineEdit*>();
if (m_pLineEdit)
{
//创建自定义删除按钮
m_pBtnClear = new QToolButton(m_pLineEdit);
QIcon clearIcon = QApplication::style()->standardIcon(QStyle::SP_LineEditClearButton);
m_pBtnClear->setIcon(clearIcon);
m_pBtnClear->setCursor(Qt::ArrowCursor);
m_pBtnClear->setStyleSheet("QToolButton { border: none; padding: 0px; }");
m_pBtnClear->hide();
// 连接清除按钮的点击信号到槽函数
connect(m_pBtnClear, &QToolButton::clicked, this, &CDateEditWithDel::slot_clearDate);
// 安装事件过滤器
m_pLineEdit->installEventFilter(this);
// 更新清除按钮的位置
updateClearBtnPosition(m_pLineEdit);
m_pLineEdit->setPlaceholderText(QString::fromLocal8Bit("选择日期"));// 设置提示文本
//初始化默认清空
slot_clearDate();
}
setFocusPolicy(Qt::NoFocus);//默认失去焦点,防止光标一直跳动
}
void customDateEdit::updateClearBtnPosition(QLineEdit * lineEdit)
{
int nClearButtonWidth = m_pBtnClear->sizeHint().width();
m_pBtnClear->setGeometry(lineEdit->width() - nClearButtonWidth, 0, nClearButtonWidth, lineEdit->height());
}
效果: