QRegExpValidator

简介

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

用法

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

// 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);
ui->edtDevComID->setValidator(new QRegExpValidator(QRegExp("[0-9a-fA-F]{16}"),this));
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
QRegExpValidator 是 Qt 框架中的一个类,用于验证用户输入的文本是否符合正则表达式规则。它通常与 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 类。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阳光开朗男孩

你的鼓励是我最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值