QDialog返回值,仅接受或拒绝?

KcF*_*nMi 5 c++ qt qdialog qt5 c++14

如何从 a 返回自定义值QDialog?它已记录它返回

QDialog::Accepted   1
QDialog::Rejected   0
Run Code Online (Sandbox Code Playgroud)

分别如果用户OkCancel

我正在考虑在一个自定义对话框中显示三个复选框,以允许用户选择一些选项。适合QDialog这个吗?

JKS*_*KSH 6

您会对 2 个函数感兴趣:

通常,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);            
    });

    // ...
}
Run Code Online (Sandbox Code Playgroud)

  • 虽然这是可能的,但我通常只是让复选框值可以通过 getters 访问,并在 exec() 返回 Accepted 时调用它们。这会导致代码更少,而且可读性也更高。 (2认同)