How to use QlineEdit to enter integer values

二次信任 提交于 2019-12-05 09:14:15

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/26777795/how-to-use-qlineedit-to-enter-integer-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!