QLineEdit实现可显示密码可隐藏密码

20 篇文章 0 订阅

一、效果图

 

 

password_hide.png

 password_hide.png

password_show.png

二、关键逻辑

QLineEditPassword.h 

#ifndef QLINEEDITPASSWORD_H
#define QLINEEDITPASSWORD_H

#include <QLineEdit>

class QLineEditPassword : public QLineEdit
{
    Q_OBJECT
public:
    explicit QLineEditPassword(QWidget *parent = nullptr);

signals:

public slots:
};

#endif // QLINEEDITPASSWORD_H

 QLineEditPassword.cpp

#include "QLineEditPassword.h"
#include <QFile>
#include <QHBoxLayout>
#include <QPushButton>

// 加载文件内容
inline bool LoadStyleFile(QString strFilePath, QString& strContent)
{
    QFile qssFile(strFilePath);
    qssFile.open(QFile::ReadOnly);
    if(!qssFile.isOpen())
    {
        return false;
    }

    strContent = qssFile.readAll();
    qssFile.close();

    return true;
}


QLineEditPassword::QLineEditPassword(QWidget *parent) : QLineEdit(parent)
{
    setEchoMode(QLineEdit::Password);

    QPushButton* button = new QPushButton();
    button->setCursor(Qt::PointingHandCursor);
    button->setCheckable(true);
    connect(button, &QPushButton::toggled, [this](bool checked) {
            if (checked)
            {
                setEchoMode(QLineEdit::Normal);
            }
            else
            {
                setEchoMode(QLineEdit::Password);
            }
        });

    QHBoxLayout* layout = new QHBoxLayout();
    layout->addStretch();
    layout->addWidget(button);
    layout->setContentsMargins(0, 0, 0, 0);
    setLayout(layout);

    QString strStyle;
    if (LoadStyleFile(":/QLineEditPasswordStyle.qss", strStyle))
    {
        setStyleSheet(strStyle);
    }
}

QLineEditPasswordStyle.qss

QLineEdit {
    font-family: "Microsoft YaHei";
    font-size: 12px;
    color: rgb(50, 50, 50);
    background-color: #f2f2f2;
    border: 1px solid #e5e5e5;
    border-radius: 4px;
    padding: 2px 2px;
    min-height: 18px;   /* 对应高度大概是24px,这里不知为何不能等价 */
    padding-right: 18px;
}

QLineEdit:hover{
    border: 1px solid #014099;
}

QLineEdit:focus{
    border: 1px solid #014099;
}

QLineEdit:hover{
    border: 1px solid #014099;
}

QLineEdit QPushButton {
    width:  16px;
    height: 16px;
    qproperty-flat: true;
    margin-right: 4px;
    border: none;
    border-width: 0;
    border-image: url(:/password_hide.png) 0 0 0 0 stretch stretch;
    background: transparent;
}

QLineEdit QPushButton::checked {
    border-image: url(:/password_show.png) 0 0 0 0 stretch stretch;
}



 

  • 5
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值