4

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.

trivelt
  • 1,913
  • 3
  • 22
  • 44
Duanne
  • 137
  • 1
  • 3
  • 13

2 Answers2

7

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.

Bowdzone
  • 3,827
  • 11
  • 39
  • 52
  • I added the line QString input = ui->lineEdit->text(); But now I can't enter data into the lineEdit at all. What I want is a lineEdit that will allow a user to enter integer values within a specific range when I run the program. This value will be stored as a variable to be used later eg frequency. Apologies for the poor explanation earlier and thank you for the help – Duanne Nov 06 '14 at 11:50
  • For a specific range a combination of a QLineEdit and a [QSlider](http://qt-project.org/doc/qt-4.8/qslider.html) which are connected using some of their SLOTS and SIGNALS can be useful. But you should probably get the lineedit to work first. Check you are retrieving its value at the right position in code – Bowdzone Nov 06 '14 at 12:00
  • I've been attempting to fix it but the lineEdit does not allow input anymore. I indented four spaces to paste my code but it doesn't appear in the right format, how can i add it – Duanne Nov 06 '14 at 12:37
  • okay i've fixed that problem is this how to the value of the lineEdit whatever is input? ` ui->lineEdit->setText(text());` That's what I got from the QT help section. – Duanne Nov 06 '14 at 12:58
  • You should probably look at some of qts examples and understand them. This is really basic stuff, sorry – Bowdzone Nov 06 '14 at 13:06
0

Use this method:

QString str = QString::number(4.4);
ui->lineEdit->setText(str);
double-beep
  • 5,031
  • 17
  • 33
  • 41
Harsh Gaur
  • 133
  • 9