QDialog返回值,仅Accepted或Rejected

QDialog return value, Accepted or Rejected only?

本文关键字:Rejected Accepted 返回值 QDialog      更新时间:2023-10-16

如何从QDialog返回自定义值?有文件记录它返回

QDialog::Accepted   1
QDialog::Rejected   0

如果用户按下CCD_ 3的CCD_。

我正在考虑一个自定义对话框,即三个复选框,允许用户选择一些选项。QDialog是否适用于此?

您将对两个函数感兴趣:

  • QDialog::setResult()允许您使用任何整数作为返回值(无需关闭对话框):http://doc.qt.io/qt-5/qdialog.html#setResult.
  • QDialog::done()执行相同的操作,只是它关闭对话框并使QDialog::exec()返回您指定的结果:http://doc.qt.io/qt-5/qdialog.html#done

通常,QDialog中的"OK"按钮连接到QDialog::accept()插槽。你想避免这种情况。相反,编写自己的处理程序来设置返回值:

// Custom dialog's constructor
MyDialog::MyDialog(QWidget *parent = nullptr) : QDialog(parent)
{
    // Initialize member variable widgets
    m_okButton = new QPushButton("OK", this);
    m_checkBox1 = new QCheckBox("Option 1", this);
    m_checkBox2 = new QCheckBox("Option 2", this);
    m_checkBox3 = new QCheckBox("Option 3", this);
    // Connect your "OK" button to your custom signal handler
    connect(m_okButton, &QPushButton::clicked, [=]
    {
        int result = 0;
        if (m_checkBox1->isChecked()) {
            // Update result
        }
        // Test other checkboxes and update the result accordingly
        // ...
        // The following line closes the dialog and sets its return value
        this->done(result);            
    });
    // ...
}