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



//==>QPasswordLineEdit.h

#ifndef QPASSWORDLINEEDIT_H
#define QPASSWORDLINEEDIT_H

#include

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

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_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
mask += "*";
}
return mask;
}


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

你可能感兴趣的:(QT)