Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt4.8: How to make LineEdit show text in uppercase always and still have a RegExp

Tags:

regex

qt

qt4

qt4.8

I'm making a gui app on Qt 4.8 which contains some lineedits to let the user introduce some information.

Normally you can write in 4 different ways the text "hello":

  1. Caps Off, no shift pressed = "hello"
  2. Caps Off, shift pressed = "HELLO"
  3. Caps ON, no shift pressed = "HELLO"
  4. Caps ON, shift pressed = "hello"

What I want is that no matter how the user writes, the line edit must show it in caps always ("HELLO").

What I was using now is:

Myclass.cpp:

auto validatorA = new MyValidator(parent);
myLineEdit->setValidator(validatorA);

Myclass.h (after includes and before class MyClass: ...)

 class MyValidator: public QValidator {
 public:
    MyValidator(QObject* parent=nullptr): QValidator(parent) {}
    State validate(QString& input, int&) const override {
      input = input.toUpper();
       return QValidator::Acceptable;
    }
 };

It works perfect but I also need this line edit to accept only letters, spaces and numbers (no symbols acepted) so after set the validatorA I need to set:

QRegExp rx("[A-Z\\.\\- 0-9]{0,30}");
QValidator *validator7 = new QRegExpValidator(rx, this);
myLineEdit->setValidator(validator7);

I've noticed that the last validator designed is the one who decides the behaviour, so I can't use both. If I use the validator7 it works fine but it fails with the case number 4: if caps on and presses shift, then nothing is written, its like if the user were not typing even if he is clubbing the keyboard. So I don't know how to be able to set both validators (I hav eother line edits with other different RegExp).

So... how can I make my lineedits follow RegExp and show always text in caps no matter the keyboard combination of caps+shift?

Thank you so much

like image 304
Megasa3 Avatar asked Mar 15 '23 10:03

Megasa3


1 Answers

Use the validator for input with the following modification

QRegExp rx("[a-z-A-Z\\.\\- 0-9]{0,30}");
QValidator *validator7 = new QRegExpValidator(rx, this);
ui->lineEdit->setValidator(validator7);

And for the upper case use the textEdited signal from the LineEdit like this

void MainWindow::on_lineEdit_textEdited(const QString &arg1)
{
    ui->lineEdit->setText(arg1.toUpper());
}
like image 150
techneaz Avatar answered Apr 09 '23 10:04

techneaz