在开发Qt程序的过程中,我们可能会需要在程序中弹出输入框,并且获取用户输入的数据。一种比较麻烦的做法就是新建一个对话框类,然后在主界面中调用对话框类,获取返回值。
使用QInputDialog对话框类可以通过访问不同的接口函数,弹出输入对话框,获取多种类型的返回数据:
函数 | 功能 |
---|---|
getText | 获取字符串输入 |
getMultiLineText | 获取多行字符输入 |
getItem | 弹出下拉框,返回所选数据 |
getText | 获取int类型输入 |
getText | 获取double类型输入 |
通过模拟输入个人的姓名,性别,年龄,体重,个人简介,可以演示所有函数的调用方法。
void MainWindow::on_Btn_SetName_clicked()
{
bool bOk = false;
QString sName = QInputDialog::getText(this,
"QInputdialog_Name",
"请输入姓名",
QLineEdit::Normal,
"张三",
&bOk
);
if (bOk && !sName.isEmpty()) {
ui->label_Name->setText(sName);
}
}
void MainWindow::on_Btn_SetGender_clicked()
{
bool bOk = false;
QStringList tLi;
tLi << "男" << "女";
QString sGender = QInputDialog::getItem(this,
"QInputDialog_Gender",
"请选择性别",
tLi,
0,
false,
&bOk);
if (bOk && !sGender.isEmpty()) {
ui->label_Gender->setText(sGender);
}
}
void MainWindow::on_Btn_SetAge_clicked()
{
bool bOk = false;
int iAge = QInputDialog::getInt(this,
"QInputDialog_Age",
"请输入年龄",
20, //默认值
0, //最小值
100, //最大值
5, //步进
&bOk);
if (bOk && iAge >= 0) {
ui->label_Age->setText(QString::number(iAge));
}
}
void MainWindow::on_Btn_SetWeight_clicked()
{
bool bOk = false;
double dbWeight = QInputDialog::getDouble(this,
"QInputDialog_Weight",
"请输入体重",
60.01, //默认值
3.01, //最小值
1000.00, //最大值
2.00, //步进
&bOk);
if (bOk && dbWeight > 3.0) {
ui->label_Weight->setText(QString::number(dbWeight, 10, 2));
}
}
void MainWindow::on_Btn_SetIntro_clicked()
{
bool bOk = false;
QString sIntroduction = QInputDialog::getMultiLineText(this,
"QInputDialog_Intro",
"请输入自我介绍",
"这个人很懒,什么也不想说",
&bOk
);
if (bOk && !sIntroduction.isEmpty()) {
ui->text_Introduction->setText(sIntroduction);
}
}
// 获取字符串
static QString getText(QWidget *parent, const QString &title, const QString &label,
QLineEdit::EchoMode echo = QLineEdit::Normal,
const QString &text = QString(), bool *ok = 0, Qt::WindowFlags flags = 0,
Qt::InputMethodHints inputMethodHints = Qt::ImhNone);
//获取多行字符输入
static QString getMultiLineText(QWidget *parent, const QString &title, const QString &label,
const QString &text = QString(), bool *ok = 0, Qt::WindowFlags flags = 0,
Qt::InputMethodHints inputMethodHints = Qt::ImhNone);
//弹出下拉框,返回选择数据
static QString getItem(QWidget *parent, const QString &title, const QString &label,
const QStringList &items, int current = 0, bool editable = true,
bool *ok = 0, Qt::WindowFlags flags = 0,
Qt::InputMethodHints inputMethodHints = Qt::ImhNone);
//获取int类型数据
static int getInt(QWidget *parent, const QString &title, const QString &label, int value = 0,
int minValue = -2147483647, int maxValue = 2147483647,
int step = 1, bool *ok = 0, Qt::WindowFlags flags = 0);
//获取double类型数据
static double getDouble(QWidget *parent, const QString &title, const QString &label, double value = 0,
double minValue = -2147483647, double maxValue = 2147483647,
int decimals = 1, bool *ok = 0, Qt::WindowFlags flags = 0);