Show QListView in QMessageBox

834 views Asked by At

I'm completely new with QT and find it quite confusing.

I created a QListView (called "listview") and would like to show that in my QMessageBox:

const int resultInfo = QMessageBox::information(this, tr("Generate Software"),
    tr("The following files will be changed by the program:"),
    => Here the QListView should show up!
    QMessageBox::Yes | QMessageBox::No);
if (resultInfo != QMessageBox::Yes) {
    return;
}

Is that possible somehow?

2

There are 2 answers

4
Minh On BEST ANSWER

QMessageBox is designed to serve texts and buttons only. See link.

If you just want to have a "More details" text, try using detail text property. In that case, you will have to create the message box using its constructor and set the icons, texts explicitly, not using the convenient information() function.

If you still want to have a list view in the message box, you should consider using QDialog, which is the base class of QMessageBox. Small example below:

#include "mainwindow.h"

#include <QDialog>
#include <QListView>
#include <QVBoxLayout>
#include <QLabel>
#include <QPushButton>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    QDialog *dialog = new QDialog{this};
    dialog->setWindowTitle(tr("Fancy title"));

    auto button = new QPushButton{tr("OK"), this};
    connect(button, &QPushButton::clicked, dialog, &QDialog::accept);

    QVBoxLayout *layout = new QVBoxLayout{dialog};
    layout->addWidget(new QLabel{tr("Description"), this});
    layout->addWidget(new QListView{this});
    layout->addWidget(button);

    dialog->show();
}

MainWindow::~MainWindow()
{
}
0
Allen Kempe On

Despite what has been said before, it is easy to add any widget to a QMessageBox. All you need to do is create your widget, say a QComboBox. Then create an instance of QMessageBox. Then get its layout which is a QGridLayout. Cast the QLayout value to QGridLayout and then you can add the widget thus:

QComboBox *myWidget = new QComboBox();
.. add items as necessary
QMessageBox* box = new QMessageBox(QMessageBox::Question, "Select value", "Select the value",QMessageBox::Ok);
QLayout *layout = box.layout();
((QGridLayout*)layout)->addWidget(myWidget, 1,2);
int ret = box.exec();

After returning from the QMessageBox. myWidget is set to the value that the user selected.