5

How to return custom value from a QDialog? It's documented it returns

QDialog::Accepted   1
QDialog::Rejected   0

respectively if user press Ok of Cancel.

I'm thinking in a custom dialog presenting i.e. three check boxes to allow user to select some options. Would QDialog be appropriate for this?

KcFnMi
  • 5,516
  • 10
  • 62
  • 136

1 Answers1

6

You'll be interested in 2 functions:

Usually, the "OK" button in a QDialog is connected to the QDialog::accept() slot. You want to avoid this. Instead, write your own handler to set the return value:

// 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);            
    });

    // ...
}
JKSH
  • 2,658
  • 15
  • 33
  • 2
    While this is possible, i'd usually just make the checkbox values accessible via getters and call them when exec() returns Accepted. That results in less code and tends to be more readable, too. – Frank Osterfeld May 08 '16 at 06:19
  • @JKSH, I was thinking in how to encode a combination of check boxes selection in an integer. But following Frank Osterfeld idea seems to help avoid that endeavor, which might be a good thing. – KcFnMi May 08 '16 at 10:25
  • Side question, `QWidget *parent = nullptr` is the current `Qt` recommended approach or is it a current C++ (C++14?) trend (I usually do/see `QWidget *parent = 0`) ? – KcFnMi May 08 '16 at 10:31
  • Agreed, @FrankOsterfeld's approach is cleaner. – JKSH May 08 '16 at 12:40
  • 1
    @KcFnMi `parent = 0` is the old style. C++11 introduced `nullptr`, so now it's better to write `parent = nullptr`. – JKSH May 08 '16 at 12:41