当前位置 博文首页 > 木木木 的博客:Qt开发之路13---QLineEdit

    木木木 的博客:Qt开发之路13---QLineEdit

    作者:[db:作者] 时间:2021-08-21 10:06

    Qt提供的单行文本编辑框。

    一:QLineEdit设置/获取内容

    • 获取编辑框内容使用text(),函数声明如下:
    QString	text() const
    
    • 设置编辑框内容
    void setText(const QString &)
    

    二:QLineEdit设置显示模式

    QLineEdit类的setEchoMode () 函数设置文本的显示模式,函数声明:

    void setEchoMode(EchoMode mode)
    

    EchoMode是一个枚举类型,定义显示模式:

    • QLineEdit::Normal 模式显示方式,按照输入的内容显示(默认)。
    • QLineEdit::NoEcho 不显示任何内容,此模式下无法看到用户的输入。
    • QLineEdit::Password 密码模式,输入的字符会根据平台转换为特殊字符。
    • QLineEdit::PasswordEchoOnEdit 编辑时显示内容否则显示字符作为密码。

    另外,使用QLineEdit显示文本的时候,希望在左侧留出一段空白的区域,可以使用QLineEdit给我们提供的setTextMargins函数:

    void setTextMargins(int left, int top, int right, int bottom)
    

    用此函数可以指定显示的文本与输入框上下左右边界的间隔的像素数。

    三:QLineEdit设置输入提示

    如果我们想实现一个与百度的搜索框类似的功能:输入一个或几个字符,下边会列出几个跟输入的字符相匹配的字符串,QLineEdit要实现这样的功能可以使用该类的成员函数setComleter()函数来实现:

    void setCompleter(QCompleter * c)
    

    创建QCompleter对象,并初始化

    QStringList tipList;
    tipList<< "Hello"<< "how" << "Why" << "my,Hi";
    
    QCompleter *completer = new QCompleter(tipList, this);
    // 不区分大小写
    completer->setCaseSensitivity(Qt::CaseInsensitive);
    

    QCompleter类的setCaseSensitivity()函数可以设置是否区分大小写,默认匹配字符串时是区分大小写的,它的参数是一个枚举类型:

    • Qt::CaseInsensitive 不区分大小写
    • Qt::CaseSensitive 区分大小写

    还可以设置字符串其中某一部分匹配,通过QCompleter类的setFilterMode函数来实现,函数声明如下:

    void setFilterMode(Qt::MatchFlags filterMode)
    

    参数可以使用 Qt::MatchContains:

    completer->setFilterMode(Qt::MatchContains);
    

    属性设置完成之后,将QCompleter对象设置到QLineEdit中:

    QLineEdit *edit = new QLineEdit(this);
    edit->setCompleter(completer);
    

    完整例程:

    QStringList tipList;
    tipList<< "Hello"<< "how" << "Why" << "my,Hi";
    
    QCompleter *completer = new QCompleter(tipList, this);
    //不区分大小写
    completer->setCaseSensitivity(Qt::CaseInsensitive);
    
    //某一部分匹配
    completer->setFilterMode(Qt::MatchContains);
    
    QLineEdit *edit = new QLineEdit(this);
    edit->setCompleter(completer);
    

    在这里插入图片描述

    四:QLineEdit密码输入框例程

    ui->lineEdit_loginPassword->setContextMenuPolicy(Qt::NoContextMenu);//设置无右键菜单
    ui->lineEdit_loginPassword->setPlaceholderText(QString::fromLocal8Bit("输入密码"));//设置密码提示
    ui->lineEdit_loginPassword->setEchoMode(QLineEdit::Password);//设置密码隐藏
    ui->lineEdit_loginPassword->setStyleSheet("QLineEdit{font-size:16px;color:gray;border:transparent;border-bottom:1px solid gray;}"
                                              "QLineEdit:hover{font-size:16px;color:gray;border:transparent;border-bottom:1px solid rgb(80, 120, 200);}");
    ui->lineEdit_loginPassword->setMaxLength(16);//设置最大长度16位*/
    

    上一篇:Qt开发之路12—QLabel显示文字、图片、动画
    下一篇:Qt开发之路14—项目(.pro)文件

    cs