关闭

Qt---实现在QLineEdit中输入密码时先显示明文,然后显示*号

标签: Qt---实现在QLineEdit中输入然后显示号
1184人阅读 评论(0) 收藏 举报
分类:



//==>QPasswordLineEdit.h

#ifndef QPASSWORDLINEEDIT_H
#define QPASSWORDLINEEDIT_H

#include <QLineEdit>

class QPasswordLineEdit : public QLineEdit
{
Q_OBJECT

public:
QPasswordLineEdit(QWidget *parent,int timeout = 300);
~QPasswordLineEdit();
private slots:
void DisplayPasswordAfterEditSlot(int,int);
void DisplayPasswordSlot();
void GetRealTextSlot(const QString&);

public:
QString GetPassword() const;
void SetTimeout(int msec);
int GetTimeout() const;

private:
QString  GetMaskString();

private:
int  m_Timeout;
QString  m_LineEditText;
int  m_LastCharCount;
};

#endif // QPASSWORDLINEEDIT_H


/// ===> QPasswordLineEdit.cpp

#include "qpasswordlineedit.h"
#include <QTimer>

QPasswordLineEdit::QPasswordLineEdit(QWidget *parent,int timeout) : QLineEdit(parent)
{
m_Timeout = timeout;
m_LineEditText = "";
m_LastCharCount = 0;

connect(this,SIGNAL(cursorPositionChanged(int,int)),this,SLOT(DisplayPasswordAfterEditSlot(int,int)));
connect(this,SIGNAL(textEdited(const QString&)),this,SLOT(GetRealTextSlot(const QString&)));
}

QPasswordLineEdit::~QPasswordLineEdit()
{

}

void QPasswordLineEdit::DisplayPasswordAfterEditSlot(int oldPos,int newPos)
{
if(oldPos>=0 && newPos>=0 )
{
if(newPos>oldPos)
QTimer::singleShot(m_Timeout,this,SLOT(DisplayPasswordSlot()));
else
this->setCursorPosition(oldPos);
}

}
void QPasswordLineEdit::DisplayPasswordSlot()
{
this->setText(GetMaskString());
}
void QPasswordLineEdit::GetRealTextSlot(const QString& text)
{
if(text.count()>m_LastCharCount)
m_LineEditText.append(text.right(1));
else if(text.count()<m_LastCharCount)
m_LineEditText.remove(m_LineEditText.count()-1,1);
m_LastCharCount = m_LineEditText.count();
}

QString QPasswordLineEdit::GetPassword() const
{
return m_LineEditText;
}
void QPasswordLineEdit::SetTimeout(int msec)
{
m_Timeout = msec;
}
int QPasswordLineEdit::GetTimeout() const
{
return m_Timeout;
}

QString QPasswordLineEdit::GetMaskString()
{
QString mask = "";
int count = this->text().length();
if(count>0)
{
for(int i=0;i<count;i++)
mask += "*";
}
return mask;
}


通过GetPassword()可以获取当前的密码明文;
0
1

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:177105次
    • 积分:2085
    • 等级:
    • 排名:第19042名
    • 原创:21篇
    • 转载:209篇
    • 译文:0篇
    • 评论:9条
    最新评论