【问题标题】:How do I handle a user pressing the cancel button in a QInputDialog?如何处理用户按下 QInputDialog 中的取消按钮?
【发布时间】:2015-08-20 13:57:25
【问题描述】:

这是我使用 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;
}

【问题讨论】:

  • 没有测试,但也许将对话框中的rejected 信号连接到处理函数?
  • 虽然这个问题相当基本,但它确实包含完整的源代码 - 所以向提问者致敬。恕我直言,反对票是毫无根据的。

标签: c++ qt


【解决方案1】:

阅读文档有很大帮助:

如果 ok 不为空,如果用户按下 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

【讨论】:

    【解决方案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);
    

    【讨论】:

    • 这很有趣。我的另一个问题是,当我们有 'QInputDialog::getInt()' 时,为什么会有范围解析运算符?我见过的唯一一次是为类定义成员函数。
    • 因为getIntQInputDialog 类的静态成员
    猜你喜欢
    • 1970-01-01
    • 2012-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-03
    • 2014-09-02
    • 2021-05-07
    相关资源
    最近更新 更多