QT 点击按钮改变输入框中文字显示 加强版

今天原本感觉前面一版还可以,然后老师就说还可以在改进下。后面也觉得还能在修改一下就写了这篇。

 最开始的版本:

QT 点击按钮改变输入框中文字显示(明文或密文)_weixin_44421186的博客-CSDN博客

先上成品。

 

 修改后的会更加符合我们所见到的登录界面。

其实说简单一点就是将按钮移动到输入框上,同时设置按钮背景透明以及样式颜色为0.

代码如下:

loginPwdButton->setToolTip(QStringLiteral("显示密码"));//鼠标停留在按钮上会出现文字
    loginPwdButton->setFlat(true);//实现按钮透明的效果
    //setFlat实现了按钮透明,但是按下按钮变化图片时会显示一下按钮的轮廓以及按钮的颜色,把样式颜色设为0可以解决
    loginPwdButton->setStyleSheet("background-color: rgba(0, 0, 0, 0)");

还修改了一开始的静态变量。将其的类型修改为了bool。这会更加简单。

关于编辑框在此我加了正则表达式。但是说实话这玩意我有点晕。这部分可以参考一下

正则表达式 – 语法 | 菜鸟教程

代码如下。

pwdEdit->setValidator(new QRegExpValidator(QRegExp("^[0-9]{1,6}$")));//只允许输入数字且为6位

接下来就是完整的代码:

头函数如下:

#include <QDebug>
#include <QMovie>
#include <QRegExpValidator>//根据正则表达式检查字符串
#include <QMessageBox>//弹窗
#include <QStringListModel>//用于处理字符串列表的数据模型
#include <QCompleter>
#include <QRegularExpression>//正则表达式规则
#include <QRegularExpressionMatch>//接收正则表达式结果
    //按钮与密码框
    pwdEdit = new QLineEdit(this);
    pwdEdit -> setGeometry(150,60,200,40);
    pwdEdit -> setPlaceholderText("请输入6位密码");
    pwdEdit -> setMaxLength(6);//设置长度为6
    pwdEdit->setFont(ft);
    //QRegularExpression var("^\w$");//正则表达式规则
    pwdEdit->setValidator(new QRegExpValidator(QRegExp("^[0-9]{1,6}$")));//只允许输入数字且为6位
    pwdEdit -> setEchoMode(QLineEdit::Password);//将其用密文显示
    loginPwdButton = new QPushButton(this);
    loginPwdButton -> setGeometry(310,60,40,40);//设置控件位置以及大小
    loginPwdButton->setIcon(QIcon(":/image/CloseeyeLogo.png"));//按钮设置图片
    loginPwdButton->setToolTip(QStringLiteral("显示密码"));//鼠标停留在按钮上会出现文字
    loginPwdButton->setFlat(true);//实现按钮透明的效果
    //setFlat实现了按钮透明,但是按下按钮变化图片时会显示一下按钮的轮廓以及按钮的颜色,把样式颜色设为0可以解决
    loginPwdButton->setStyleSheet("background-color: rgba(0, 0, 0, 0)");
    loginPwdButton->setIconSize(QSize(35,35));//图片大小设置

静态变量:

bool Widget::numButton = false;//确定按钮,来改变状态

函数:

/*****************************************************************
* 函数名称: editComplete()
* 功能描述: 按钮变换图片
* 参数说明: 无
* 返回值:   无
******************************************************************/
void Widget::on_pushButton_eyeSlot()
{
    //一开始Widget::numButton=flase
    if(Widget::numButton == true)//如果按下按键为true 则闭上眼睛 显示密文
    {
        loginPwdButton->setIcon(QIcon(":/image/CloseeyeLogo.png"));
        pwdEdit -> setEchoMode(QLineEdit::Password);//将其用密文显示
        loginPwdButton->setToolTip(QStringLiteral("显示密码"));//当为控件设置了toolTip之后,鼠标停留在控件上时就会显示toolTip的信息
        Widget::numButton = false;
    }
    else if(Widget::numButton == false)//如果按下按键为false 则睁开眼睛 显示明文
    {
        loginPwdButton->setIcon(QIcon(":/image/openEyeLogo.png"));
        pwdEdit -> setEchoMode(QLineEdit::Normal);//将其用明文显示
        loginPwdButton->setToolTip(QStringLiteral("密文显示密码"));//鼠标停留在按钮上会出现文字
        Widget::numButton = true;
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_44421186/article/details/124629802
今日推荐