c++qtqmessagebox

Setting multiple checkboxes in QMessageBox


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

Solution

  • 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();