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

一、效果图

 

 

 

 二、关键逻辑

QLineEditPassword.h 

#ifndef QLINEEDITPASSWORD_H
#define QLINEEDITPASSWORD_H

#include 

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

signals:

public slots:
};

#endif // QLINEEDITPASSWORD_H

 QLineEditPassword.cpp

#include "QLineEditPassword.h"
#include 
#include 
#include 

// 加载文件内容
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;
}



 

你可能感兴趣的:(Qt,C++)