正则表达式的使用

使用正则表达式限制QLineEdit的测试例子:

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>

namespace Ui {
class Dialog;
}

class Dialog : public QDialog
{
    Q_OBJECT

public:
    explicit Dialog(QWidget *parent = 0);
    ~Dialog();

public Q_SLOTS:
    void accept() override;

private:
    Ui::Dialog *ui;
};

#endif // DIALOG_H

#include "dialog.h"
#include "ui_dialog.h"

#include <QDebug>
#include <QMessageBox>

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    ui->lineEdit_1->setValidator(new QRegExpValidator(QRegExp(tr("[0-9]+")),this));  //设置只能输入数字
    ui->lineEdit_2->setValidator(new QRegExpValidator(QRegExp(tr("[-]?[0-9]+,[0-9]+")),this));  //设置
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::accept()
{
    if(!QRegExp(tr("[0-9]+")).exactMatch(ui->lineEdit_1->text()))
    {
        QMessageBox temMB(QMessageBox::Warning,
                          tr("警告"),
                          tr("第一行输入错误,默认输入是1\n请问是否设置为默认值?"),
                          QMessageBox::Yes | QMessageBox::No);
        temMB.setButtonText(QMessageBox::Yes,tr("是"));
        temMB.setButtonText(QMessageBox::No,tr("否"));
        if(temMB.exec() == QMessageBox::Yes)
            ui->lineEdit_1->setText(tr("1"));
        return;
    }
    if(!QRegExp(tr("[-]?[0-9]+,[0-9]+")).exactMatch(ui->lineEdit_2->text()))
    {
        QMessageBox temMB(QMessageBox::Warning,
                          tr("警告"),
                          tr("第二行输入错误,默认输入是1,1\n请问是否设置为默认值?"),
                          QMessageBox::Yes | QMessageBox::No);
        temMB.setButtonText(QMessageBox::Yes,tr("是"));
        temMB.setButtonText(QMessageBox::No,tr("否"));
        if(temMB.exec() == QMessageBox::Yes)
            ui->lineEdit_2->setText(tr("1,1"));
        return;
    }
    qDebug()<<ui->lineEdit_1->text()<<'\n'<<ui->lineEdit_2->text();
    QDialog::accept();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75

注意,我发现虽然设置了正真表达式后,QLineEdit只能保证输入的时候可以按照其规则输入,但是不能保证客户使用的时候输入完全,比如需要输入坐标(23,34),客户可能没有输入逗号,还是可以按确定按钮的,为了让其完全有保证,必须在按下接受按钮的时候再次检验,这是可以重写QDialogaccept()函数,并在里面再次使用正则表达式QRegExp类的exactMatch进行匹配来达到目的。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值