QTlineedit关于setPlaceholderText(背景文字的实现)

这个是我在linux下qt开发遇到的问题,因为当时的QT的库只有3.3,里面没有setPlaceholderText这个方法,所以我重写了这个方法。

想要实现这个效果,首先我们要用到QT内控件的几个事件。

1)void focusInEvent(QFocusEvent *e);光标聚焦在当前输入框时会触发该事件

2)void focusOutEvent(QFocusEvent *e);光标离开该输入框时会触发该事件

话不多说先上代码,该部分代码我写成了内联函数。

#ifndef MYEDIT_H
#define MYEDIT_H
#include
#include 
using namespace std;
class myedit :public QLineEdit    //基于QLineEdit继承出一个自己的类
{
public:
    myedit(QWidget *parent = 0);    //构造时只需将自己的属性清零即可

    void setplaceholdertext(QString text)    //设置需要显示在背景的文本
    {
        placeholderText = text;
        if(this->text().isEmpty())   //如果是空的 说明该输入框没有用户输入的文字
        {
     //判断是否为密文,因为我们的背景文本是明文,密码显示则为密文,所以这一块是处理最麻烦的东西
            if(this->echoMode() == QLineEdit::Password)
            {
                this->setEchoMode(QLineEdit::Normal);
                this->ps_flag=1;//设置是否是密文为1 表示去人为密文
            }
            this->setText(placeholderText);//设置文本
        }
    }
    void focusInEvent(QFocusEvent *e)    //光标聚焦事件
    {
        this->setFocus();//显示光标
        if(!placeholderText.isNull())   
        {
            QString t = this->text();
            if(t.isEmpty()|| t==placeholderText)//判断是否为空,或者文字等于背景文字
            {

                if(this->ps_flag ==1)//判断明文或者密文
                {

                    this->setEchoMode(QLineEdit::Password);//设置为密文
                    this->clear();//清空背景字
                    //this->clearFocus();  //让光标失去焦点
                }
                else
                {
                    this->setEchoMode(QLineEdit::Normal);//设置为明文
                    this->clear();//清空背景字
                  //  this->clearFocus();  //让光标失去焦点
                }

            }
        }

    }
    void focusOutEvent(QFocusEvent *e)//光标离开事件
    {
        this->clearFocus();//清空光标
           if(!placeholderText.isNull())
           {
               if(this->text().isEmpty())//判断用户有没有输入文字
               {
                   if(this->ps_flag==1)
                   {
                //如果是密码框,先改回明文,再显示背景文字
                       this->setEchoMode(QLineEdit::Normal);
                   }
                    //设置明文
                   this->setText(placeholderText); 

               }
               else
               {

               }
           }

    }
    void set_psw_flag(bool psw_flag);    //new出该文本框时需要设置该文本为明文密文
    void set_Password()    //这个类是我在清空密码框时使用,看需要使用这个函数
    {
        this->setEchoMode(QLineEdit::Normal);

    }

private:
    QString placeholderText;
    int ps_flag;    //判断是否是密码输入
    bool psw_flag;    //明文,暗文标志位
protected:


};


#endif // MYEDIT_H

以上是我代码的部分,写的不是很完善,希望有问题可以提出来一起研究,欢迎交流

 

QTlineedit关于setPlaceholderText(背景文字的实现)_第1张图片

这是我项目中的实际效果,谢谢大家,我会努力更新的

 

你可能感兴趣的:(QTlineedit关于setPlaceholderText(背景文字的实现))