如何处理用户按下QInputDialog中的取消按钮?

时间:2015-08-20 13:57:26

标签: c++ qt

这是我第一周做Qt,所以如果我不太了解基础知识,请原谅我。在下面代码的注释部分中,我想编写处理QInputDialog上的取消按钮的代码。

#include <QtWidgets>

int main (int argc, char* argv[]) {              
  QApplication app(argc, argv);                  
  QTextStream cout(stdout);                       
  int answer;

  do {  
    int celciusArg = 0;
    int farenheit;
    celciusArg = QInputDialog::getInt(0, "Celcius Calculator",
        "Convert this number to Farenheit:", 1);

    // I'd like to say here:
    // if (user clicked cancel)
    //      then (close the widget)

    cout << "User entered: " << celciusArg
         << endl;
    farenheit = celciusArg * 1.8 + 32;

    QString response = QString("%1 degrees celcius is %2 degrees farenheit .\n%3")
        .arg(celciusArg).arg(farenheit)        /* Each %n is replaced with an arg() value. */
        .arg("Convert another temperature?");  /* Long statements can continue on multiple lines, as long as they are broken on token boundaries. */
    answer = QMessageBox::question(0, "Play again?", response,
        QMessageBox::Yes| QMessageBox::No);    /* Bitwise or of two values. */
  } while (answer == QMessageBox::Yes);
  return EXIT_SUCCESS;
}

2 个答案:

答案 0 :(得分:3)

阅读文档有很多帮助:

  

如果ok为nonnull * ok,如果用户按下OK,则设置为true;如果用户按下Cancel,则设置为false。对话框的父级是父级。该对话框将是模态的,并使用小部件标记。

完整的原型是:

int QInputDialog::getInt(QWidget * parent, const QString & title, const QString & label, int value = 0, int min = -2147483647, int max = 2147483647, int step = 1, bool * ok = 0, Qt::WindowFlags flags = 0)

所以在这里你只需要使用bool * ok

bool isOkPressed{};
int celciusArg = 0;
int farenheit;
celciusArg = QInputDialog::getInt(0, "Celcius Calculator",
    "Convert this number to Farenheit:", 1, -2147483647, 2147483647, 1, &isOkPressed);

if (isOkPressed) {
    // here you go
}

QInputDialog::getInt() documentation

答案 1 :(得分:2)

更改为

bool ok;
celciusArg = QInputDialog::getInt(0, "Celcius Calculator",
    "Convert this number to Farenheit:", 0, 0, 100, 1, &ok);

if (ok)
    //pressed ok
else
    //pressed cancel

第一个零是默认值,第二个是最小值,100应该是最大值,1是增量/减量,如果你想从30 C开始从-100 C到200 C获得温度必须使用

celciusArg = QInputDialog::getInt(0, "Celcius Calculator",
    "Convert this number to Farenheit:", 30, -100, 200, 1, &ok);