edition
edition

Reputation: 678

QMessageBox disappears

I'm trying to display a QMessageBox through calling its show function in a lambda function like the following:

connect(ui->graphButton, &QAbstractButton::clicked, [](void){
        QMessageBox message;
        message.setText(tr("Graphing button clicked"));
        message.show();
});

However, upon clicking the graphButton, the QMessageBox window appears only momentarily before disappearing. How can I fix this?

Upvotes: 2

Views: 2126

Answers (2)

Boiethios
Boiethios

Reputation: 42739

message.exec();

to execute it.

Full code :

connect(ui->graphButton, &QAbstractButton::clicked, [](void){
        QMessageBox message;
        message.setText(tr("Graphing button clicked"));
        message.exec();
});

show only set the visibility status of the widget : http://doc.qt.io/qt-4.8/qwidget.html#show http://doc.qt.io/qt-4.8/qwidget.html#visible-prop while exec has the desired behavior http://doc.qt.io/qt-5/qmessagebox.html#exec

You do not need to use show, because it is the default visibility. Use it when you disabled the visibility of a widget to enable it again.

Upvotes: 4

Ahmet Ipkin
Ahmet Ipkin

Reputation: 942

Use QMessageBox.setModal to set the message box to "Modal" mode (that is, it blocks the execution until it is done working) and then use "open" method to show the messagebox.

connect(ui->graphButton, &QAbstractButton::clicked, [](void){
    QMessageBox message;
    message.setText(tr("Graphing button clicked"));
    message.setModal(true);
    message.open( ... );
});

Upvotes: -1

Related Questions