在做用户登录、修改密码的时候,往往会用到密码框,其中一些功能要求与普通的输入框不同。
例如:不能选中、复制、粘贴、无右键菜单等功能,当然设置密码不可见是必须的!
一般的密码框:(默认 可以选中,复制,粘贴,有右键菜单)
QLineEdit *pCommonLineEdit = new QLineEdit(this);
pCommonLineEdit->setPlaceholderText(QStringLiteral("密码由字母、数字、下划线组成,长度8-16位"));
//QStringLieral是Qt5中新引入的一个用来从“字符串常量”创建QString对象的宏
pCommonLineEdit->setEchoMode(QLineEdit::Password);
下面进行一些设置:不可选择,没有右键菜单
1.可以进行事件重写去完成
class PasswordLineEdit : public QLineEdit
{
Q_OBJECT public:
explicit PasswordLineEdit(QWidget *parent = 0);
~PasswordLineEdit(); protected:
virtual void keyPressEvent(QKeyEvent *event);
virtual void mouseMoveEvent(QMouseEvent *event);
virtual void mouseDoubleClickEvent(QMouseEvent *event);
};
PasswordLineEdit::PasswordLineEdit(QWidget *parent)
: QLineEdit(parent)
{
//设置无右键菜单
setContextMenuPolicy(Qt::NoContextMenu);
//设置无输入时密码提示
setPlaceholderText(QStringLiteral("请输入密码"));
//设置密码隐藏
setEchoMode(QLineEdit::Password);
//设置最大长度16位
setMaxLength(16);
} PasswordLineEdit::~PasswordLineEdit()
{
} //屏蔽输入框全选、复制、粘贴功能
void PasswordLineEdit::keyPressEvent(QKeyEvent *event)
{
if(event->matches(QKeySequence::SelectAll)
|| event->matches(QKeySequence::Copy)
|| event->matches(QKeySequence::Paste))
{
return;
} QLineEdit::keyPressEvent(event);
} //鼠标位于密码框中时不可移动
void PasswordLineEdit::mouseMoveEvent(QMouseEvent *event)
{
Q_UNUSED(event);
} //鼠标位于密码框中时不可移动
void PasswordLineEdit::mouseDoubleClickEvent(QMouseEvent *event)
{
Q_UNUSED(event);
}
2.通过事件过滤器去实现上述的功能
QLineEdit *pFilterLineEdit = new QLineEdit(this);
pFilterLineEdit->installEventFilter(new EventFilter(this));
pFilterLineEdit->setEchoMode(QLineEdit::Password);
pFilterLineEdit->setPlaceholderText(QStringLiteral("密码由字母、数字、下划线组成,长度8-16位"));
pFilterLineEdit->setContextMenuPolicy(Qt::NoContextMenu);
pFilterLineEdit->setMaxLength(16);
class EventFilter : public QObject
{
public:
explicit EventFilter(QObject *parent = 0);
~EventFilter(); protected:
virtual bool eventFilter(QObject *obj, QEvent *event);
};
EventFilter::EventFilter(QObject *parent)
: QObject(parent)
{ } EventFilter::~EventFilter()
{ } bool EventFilter::eventFilter(QObject *obj, QEvent *event)
{
QLineEdit *pLineEdit = qobject_cast<QLineEdit *>(obj);
if (pLineEdit != NULL)
{
switch (event->type())
{
case QEvent::MouseMove:
case QEvent::MouseButtonDblClick:
return true;
case QEvent::KeyPress:
{
QKeyEvent *pKeyEvent = static_cast<QKeyEvent*>(event);
if(pKeyEvent->matches(QKeySequence::SelectAll)
|| pKeyEvent->matches(QKeySequence::Copy)
|| pKeyEvent->matches(QKeySequence::Paste))
{
return true;
}
}
}
}
return QObject::eventFilter(obj, event);
}