我是 Qt 新手。我想检查 QLineEdit 的输入值:如果输入以空格开头,则将字体颜色变为黑色,否则将其变为红色。但效果不佳。
代码如下:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_lineEdit_textChanged(const QString &arg1)
{
QRegExp regexp("^\s*");
if(!regexp.exactMatch(arg1))
{
ui->lineEdit->setStyleSheet("color:red");
} else
{
ui->lineEdit->setStyleSheet("color:black");
}
}
所以当我运行这段代码并以空格开头时,它变成了红色,我不明白为什么会这样。
更新问题
以下是我的看法: 如果我想在输入不是数字时标记为红色,RegExp 应该是这样的:
void MainWindow::on_lineEdit_textChanged(const QString &arg1)
{
QRegExp regexp("^[0-9]*");
if(regexp.exactMatch(arg1)) {
ui->lineEdit->setStyleSheet("color:black");//if the input is digits,black
} else {
ui->lineEdit->setStyleSheet("color:red");//not digits,red
}
}
它如我所愿地工作。但是当我在 RegExp(QRegExp regexp("^\s[0-9]*")
) 中添加 \s
时,数字以空格开头或纯数字变成红色.这是为什么?
最佳答案
你的代码有几个问题。
首先,使用正则表达式来解决这个任务是大材小用。您只需要检查字符串的第一个字符是否为空格。如果需要检查与简单空格字符 (0x20) 的相等性,可以使用 QString::startsWith函数:arg1.startsWith(' ')
。或者,如果您需要考虑任何空白字符,您可以使用 QChar::isSpace方法:
bool stringDoesStartWithWhitespace = false;
if (!arg1.isEmpty()) {
stringDoesStartWithWhitespace = arg1[0].isSpace();
}
这将我们引向代码的这些变体:
void MainWindow::on_lineEdit_textChanged(const QString &arg1)
{
if (arg1.startsWith(' ')) {
ui->lineEdit->setStyleSheet("color:black");
} else {
ui->lineEdit->setStyleSheet("color:red");
}
}
或:
void MainWindow::on_lineEdit_textChanged(const QString &arg1)
{
bool stringDoesStartWithWhitespace = false;
if (!arg1.isEmpty()) {
stringDoesStartWithWhitespace = arg1[0].isSpace();
}
if (stringDoesStartWithWhitespace) {
ui->lineEdit->setStyleSheet("color:black");
} else {
ui->lineEdit->setStyleSheet("color:red");
}
}
现在让我们看一下正则表达式(如果您真的需要使用一个)。您应该转义 反斜杠,以便将其视为正则表达式的一部分,而不是转义序列 (\s
) 的一部分。你可以阅读here关于转义序列。
另外,据我所知,如果输入至少以一个空格开头,则需要将控件前景色设为黑色。在这种情况下,您应该使用 +
符号而不是 *
(E+
用于匹配一次或多次出现的 E
).您可以阅读有关量词的信息 here .
二、QRegExp的使用。 QRegExp::exactMatch页面说这个功能
Returns
true
if string is matched exactly by this regular expression; otherwise returnsfalse
.
在您的情况下,您只需要检查 QTextEdit 值的开头是否与正则表达式匹配。你应该使用 QRegExp::indexIn功能。
结果,您的代码将如下所示:
void MainWindow::on_lineEdit_textChanged(const QString &arg1)
{
QRegExp regexp("^\\s+");
if (regexp.indexIn(arg1) > -1) { //we do have the whitespace in the beginning of the string
ui->lineEdit->setStyleSheet("color:black");
} else {
ui->lineEdit->setStyleSheet("color:red");
}
}
关于c++ - 带空格的 Qt QRegExp 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38045577/