如何使用QlineEdit输入整数值

Dua*_*nne 1 c++ qt qlineedit

我正在尝试使用QlineEdit

运行程序并将值存储为变量以供以后使用时,如何在编辑栏中输入值。到目前为止,我只发现了如何使用

void parameter_settings::on_lineEdit_textEdited(const QString &arg1)

{
    ui->lineEdit->setText("");
}
Run Code Online (Sandbox Code Playgroud)

我有一个GUI,要求用户输入特定范围内的值。该值将作为变量存储,以备后用。我已经阅读了有关验证器的信息,但无法使其按预期工作。

Bow*_*one 5

我不确定您的问题是什么,但是您可以使用以下命令从QLineEdit获取输入text()

QString input = ui->lineEdit->text();
Run Code Online (Sandbox Code Playgroud)

和一个整数输入,使用:

int integer_value = ui->lineEdit->text().toInt();
Run Code Online (Sandbox Code Playgroud)

正如您提到的验证器:您可以使用验证器来允许用户仅在QLineEdit中插入整数。有不同的验证器,但我通常喜欢使用“ RegEx”验证器。在这种情况下:

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

注意:如Pratham的评论中所述,如果只要求输入整数,则可能应该使用a QSpinBox来完成所有现成的工作,并带有额外的句柄以轻松增加和减少值。