QInputDialog Multiple Inputs 输入多个变量的对话框

 

在之前的博客QInputDialog 使用方法中展示了利用QInputDialog可以快速通过一行代码来生成一个输入框,来获取用户的输入值,那么如果我们希望获取多个输入值,怎么办呢?那么此时用QInputDialog就没法实现了,我们必须基于QDialog类重新写一个类,可是只是一个简单的多值输入框,我们又不想为了它而生成对应的.cpp和.h,还有.ui文件,这样太麻烦了,其实我们可以用代码来添加输入框和对应的label。

 

 

如果我们想生成一个上图一样的多个输入值的文本对话框,可以使用如下代码:

 

QDialog dialog(this);
QFormLayout form(&dialog);
form.addRow(new QLabel("User input:"));
// Value1
QString value1 = QString("Value1: ");
QSpinBox *spinbox1 = new QSpinBox(&dialog);
form.addRow(value1, spinbox1);
// Value2
QString value2 = QString("Value2: ");
QSpinBox *spinbox2 = new QSpinBox(&dialog);
form.addRow(value2, spinbox2);
// Add Cancel and OK button
QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
    Qt::Horizontal, &dialog);
form.addRow(&buttonBox);
QObject::connect(&buttonBox, SIGNAL(accepted()), &dialog, SLOT(accept()));
QObject::connect(&buttonBox, SIGNAL(rejected()), &dialog, SLOT(reject()));

// Process when OK button is clicked
if (dialog.exec() == QDialog::Accepted) {
    // Do something here
}

 

参考资料:

http://stackoverflow.com/questions/17512542/getting-multiple-inputs-from-qinputdialog-in-qtcreator

 

posted @ 2017-01-09 08:40  Grandyang  阅读(5612)  评论(0编辑  收藏  举报
Fork me on GitHub