1

I am trying to set two QCheckBox in a QMessageBox. Only the second checkbox appears. How do I achieve this? Is it better to just create a custom QDialog?

    void TextEditor::actionConfigure_triggered()
    {
        QCheckBox *checkbox = new QCheckBox("Cursor to end of file");
        QCheckBox *geometryCheckBox = new QCheckBox("Save and restore geometry");
        QMessageBox msgBox(this);
        msgBox.setStandardButtons(QMessageBox::Apply | QMessageBox::Discard | QMessageBox::Reset | QMessageBox::RestoreDefaults);
        msgBox.setDefaultButton(QMessageBox::Apply);
        msgBox.setCheckBox(checkbox);
        msgBox.setCheckBox(geometryCheckBox);
        checkbox->setToolTip("Option to move cursor to end of text on file open");
        geometryCheckBox->setToolTip("Option to save and restore geometry on open / close");
        int ret = msgBox.exec();
        switch (ret) {
          case QMessageBox::Apply:
              // Save was clicked
              break;
          case QMessageBox::Discard:
              // Don't Save was clicked
              break;
          case QMessageBox::Reset:
            // Cancel was clicked
            break;
          case QMessageBox::RestoreDefaults:
            // Restore defaults
            break;
          default:
            // should never be reached
            break;
        }
    }

1 Answer 1

4

QMessageBox by default only allows placing a QCheckBox so if a new QCheckBox is added it will replace the previous one. A possible solution is to inject the QCheckBox to the layout directly:

QCheckBox *checkbox = new QCheckBox("Cursor to end of file");
QCheckBox *geometryCheckBox = new QCheckBox("Save and restore geometry");
QMessageBox msgBox(this);
msgBox.setStandardButtons(QMessageBox::Apply | QMessageBox::Discard | QMessageBox::Reset | QMessageBox::RestoreDefaults);
msgBox.setDefaultButton(QMessageBox::Apply);
checkbox->setToolTip("Option to move cursor to end of text on file open");
geometryCheckBox->setToolTip("Option to save and restore geometry on open / close");
msgBox.setCheckBox(checkbox);

QGridLayout *grid = qobject_cast<QGridLayout *>(msgBox.layout());
int index = grid->indexOf(checkbox);
int row, column, rowSpan, columnSpan;
grid->getItemPosition(index, &row, &column, &rowSpan, &columnSpan);
grid->addWidget(geometryCheckBox, row + 1,  column, rowSpan, columnSpan);

int ret = msgBox.exec();
Sign up to request clarification or add additional context in comments.

1 Comment

What a clever hack! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.