Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QLineEdit: how to prevent leading whitespace



  • I am trying to prevent the user from entering leading whitespace in a QLinEdit, thus:
    QRegExp rx("[A-Z]");
    m_validator = new QRegExpValidator(rx, this);
    m_lineedit->setValidator(m_validator);
    This sort of works, but it doesn't prevent the cursor from moving one step, so there is still a single whitespace in the lineedit. This behaviour can probably be prevented by using backspace(), but it's a bit messy. Or is there a way to include the backspace() with a validator?


  • Lifetime Qt Champion

    Hi,

    QRegExpValidator is deprecated. Please use QRegularExpressionValidator.

    What about "^[A-Z]*" as your regular expression ?



  • Thanks. I changed to QRegularExpressionValidator. This regexp work fine, but only for ASCII characters. I need it to word with UTF-8, which it does using the regexp "^\p{L}*$". Somewhere else in the code I have got
    name.replace(0, 1, name.left(1).toUpper()); // I change everything to lower case first
    in order to ensure that the first letter is in upper case. Without the regexp in place this works fine for any characters, but with the regexp in place, if the user types the wrong letter and presses backspace then the first letter isn't changed to upper case anymore. But maybe this issue isn't Qt related and ought to be asked in a group dealing with text processing?


  • Lifetime Qt Champion

    Can you provide a minimal compilable example that shows your issue ?



  • The problem turned out to be that when the user presses backspace to delete the first character a null char ( "\u000" ) gets inserted into the text string in the lineedit. I can print it out:
    QString name = m_name_le->text();
    qDebug() << "name:" << name;
    but I do not know how to delete it, as gcc does not like "\u000".



  • @Buller
    It does not sound very good if a QLineEdit were to insert some character every time user presses Backspace, don't you think?

    You would have to get your \u000 right for C++, depending on how you use it. Perhaps you only need \0? In any case, if it's the first character you want to delete you could do that by position.


Log in to reply