Qt之QRegExpValidator类

QRegExpValidator类用于根据正则表达式检查字符串。

QRegExpValidator使用正则表达式(regexp)来确定输入字符串是可接受的、中间的还是无效的。regexp可以在构建QRegExpValidator时提供,也可以在稍后的时候提供。

当QRegExpValidator确定一个字符串是否可接受时,regexp被视为以字符串断言(^)开头,以字符串断言($)结尾;匹配针对整个输入字符串,如果起始位置大于零,则从给定位置匹配。

如果字符串是可接受字符串的前缀,则认为它是中间的。例如,“”和“A”是regexp [A- z][0-9]的中间值(而“_”是无效的)。

// regexp: optional '-' followed by between 1 and 3 digits
  QRegExp rx("-?\\d{1,3}");
  QValidator *validator = new QRegExpValidator(rx, this);

  QLineEdit *edit = new QLineEdit(this);
  edit->setValidator(validator);

 

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
QRegExpValidatorQt 框架中的一个,用于验证用户输入的文本是否符合正则表达式规则。它通常与 QLineEdit、QPlainTextEdit 等控件一起使用。 以下是 QRegExpValidator 的基本用法: 1. 创建 QRegExp 对象,设置需要验证的正则表达式规则。 ```cpp QRegExp regExp("[A-Za-z0-9_]+"); // 匹配字母、数字和下划线 ``` 2. 创建 QRegExpValidator 对象,将 QRegExp 对象作为参数传入。 ```cpp QRegExpValidator validator(regExp, this); // this 表示当前窗口 ``` 3. 将 QRegExpValidator 对象设置给需要验证的控件。 ```cpp QLineEdit *lineEdit = new QLineEdit(this); lineEdit->setValidator(&validator); ``` 完整示例代码: ```cpp #include <QtWidgets> int main(int argc, char *argv[]) { QApplication app(argc, argv); // 创建正则表达式对象 QRegExp regExp("[A-Za-z0-9_]+"); // 创建验证器对象,将正则表达式对象作为参数传入 QRegExpValidator validator(regExp, nullptr); // 创建输入框对象,并设置验证器 QLineEdit *lineEdit = new QLineEdit; lineEdit->setValidator(&validator); // 创建主窗口,并设置布局 QWidget mainWidget; QVBoxLayout *layout = new QVBoxLayout(&mainWidget); layout->addWidget(lineEdit); mainWidget.show(); return app.exec(); } ``` 在上述示例中,我们创建了一个 QLineEdit 对象,并使用 QRegExpValidator 对象进行了验证。由于我们只允许用户输入字母、数字和下划线,因此如果用户输入其他字符,则无法通过验证。 注意:QRegExpValidator 只能验证单行文本框中的输入,如果需要验证多行文本框中的输入,则需要使用 QRegularExpressionValidator

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值