11

How can I show a message box with a "Do not show again" checkbox below?

I imagine something that looks like this:

enter image description here

sashoalm
  • 75,001
  • 122
  • 434
  • 781
user5820174
  • 151
  • 1
  • 12

1 Answers1

22

Qt 5.2 added the possibility to add a QCheckBox to a QMessageBox. Have a look at QMessageBox::setCheckbox

Here is some demo code

if (this->showMsgBox) {
    QCheckBox *cb = new QCheckBox("Okay I understand");
    QMessageBox msgbox;
    msgbox.setText("Am I nerve-wrecking?");
    msgbox.setIcon(QMessageBox::Icon::Question);
    msgbox.addButton(QMessageBox::Ok);
    msgbox.addButton(QMessageBox::Cancel);
    msgbox.setDefaultButton(QMessageBox::Cancel);
    msgbox.setCheckBox(cb);

    QObject::connect(cb, &QCheckBox::stateChanged, [this](int state){
        if (static_cast<Qt::CheckState>(state) == Qt::CheckState::Checked) {
            this->showMsgBox = false;
        }
    });

    msgbox.exec();
}
Christian Rapp
  • 1,853
  • 24
  • 37
  • 1
    This won't work unless `msgbox.exec();` is called after `connect` statement. `exec()` is a blocking call and `stateChanged` signal won't be effective this way. Just tried this with a small demo app. – ramtheconqueror Feb 01 '16 at 14:41
  • 1
    Ups you are right of course. Didn't actually runt he code. Stupid me. Thank you! – Christian Rapp Feb 01 '16 at 14:47
  • Sorry for the stupid question, what is ShowMsgBox exactly? – user5820174 Feb 02 '16 at 06:46
  • 1
    Its a boolean member variable of the test class I used. – Christian Rapp Feb 02 '16 at 22:29
  • On Qt5 getting `error: invalid use of ‘this’ in non-member function` and had to change to `QObject::connect(cb, &QCheckBox::stateChanged, [=]( const int &state ){` - a C++11 lambda expression. – cpb2 Jul 02 '20 at 14:30