這篇文章主要介紹“Qt如何實現密碼顯示按鈕”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“Qt如何實現密碼顯示按鈕”文章能幫助大家解決問題。
PasswordLineEdit.h
#ifndef PASSWORDLINEEDIT_H
#define PASSWORDLINEEDIT_H
#include <QAction>
#include <QLineEdit>
#include <QToolButton>
class PasswordLineEdit : public QLineEdit {
public:
PasswordLineEdit(QWidget *parent = nullptr);
private slots:
void onPressed();
void onReleased();
protected:
void enterEvent(QEvent *event);
void leaveEvent(QEvent *event);
void focusInEvent(QFocusEvent *event);
void focusOutEvent(QFocusEvent *event);
private:
QToolButton *button;
};
#endif // PASSWORDLINEEDIT_HPasswordLineEdit.cpp
#include "passwordlineedit.h"
PasswordLineEdit::PasswordLineEdit(QWidget *parent) : QLineEdit(parent)
{
setEchoMode(QLineEdit::Password);
QAction *action = addAction(QIcon(":/eyeOff"), QLineEdit::TrailingPosition);
button = qobject_cast<QToolButton *>(action->associatedWidgets().last());
button->hide();
button->setCursor(QCursor(Qt::PointingHandCursor));
connect(button, &QToolButton::pressed, this, &PasswordLineEdit::onPressed);
connect(button, &QToolButton::released, this, &PasswordLineEdit::onReleased);
}
void PasswordLineEdit::onPressed()
{
QToolButton *button = qobject_cast<QToolButton *>(sender());
button->setIcon(QIcon(":/eyeOn"));
setEchoMode(QLineEdit::Normal);
}
void PasswordLineEdit::onReleased()
{
QToolButton *button = qobject_cast<QToolButton *>(sender());
button->setIcon(QIcon(":/eyeOff"));
setEchoMode(QLineEdit::Password);
}
void PasswordLineEdit::enterEvent(QEvent *event)
{
button->show();
QLineEdit::enterEvent(event);
}
void PasswordLineEdit::leaveEvent(QEvent *event)
{
button->hide();
QLineEdit::leaveEvent(event);
}
void PasswordLineEdit::focusInEvent(QFocusEvent *event)
{
button->show();
QLineEdit::focusInEvent(event);
}
void PasswordLineEdit::focusOutEvent(QFocusEvent *event)
{
button->hide();
QLineEdit::focusOutEvent(event);
}main.cpp
#include "passwordlineedit.h"
#include <QApplication>
#include <QFormLayout>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget w;
PasswordLineEdit *w1 = new PasswordLineEdit;
QLineEdit *w2 = new QLineEdit;
QFormLayout *lay = new QFormLayout(&w);
lay->addRow("PasswordLineEdit: ", w1);
lay->addRow("QLineEdit: ", w2);
w.show();
return a.exec();
}
關于“Qt如何實現密碼顯示按鈕”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注億速云行業資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。