Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use QlineEdit to enter integer values

Tags:

c++

qt

qlineedit

I am trying to use QlineEdit.

How would I enter a value into the edit bar when I run the program and get that valued stored as a variable to be used later. So far I have only found out how to enter text using

void parameter_settings::on_lineEdit_textEdited(const QString &arg1)

{
    ui->lineEdit->setText("");
}

I have a GUI that requires the user to enter a value within a specific range. That value would be stored as a variable for later use. I have read about validators but can't get it to work as intended.

like image 571
Duanne Avatar asked Mar 18 '23 23:03

Duanne


1 Answers

I am not entirely sure what your question is, but you can get the input from a QLineEdit with the command text():

QString input = ui->lineEdit->text();

and an integer input by using:

int integer_value = ui->lineEdit->text().toInt();

As you mentioned validators: You can use validators to allow the user to insert only integers into the QLineEdit in the first place. There are different ones but I generally like to use 'RegEx' validators. In this case:

QRegExpValidator* rxv = new QRegExpValidator(QRegExp("\\d*"), this); // only pos
QRegExpValidator* rxv = new QRegExpValidator(QRegExp("[+-]?\\d*"), this); // pos and neg
ui->lineEdit->setValidator(rxv);

Note: As mentioned in the comments by Pratham, if you only require integers to be entered you should probably use a QSpinBox which does all this out-of-the-box and comes with extra handles to easily increase and decrease of the value.

like image 51
Bowdzone Avatar answered Mar 24 '23 22:03

Bowdzone