MelMed
MelMed

Reputation: 1752

aborting the execution with Visual Studio / Qt

I would like to abort an application execution (done with Qt) with an error message in case there was a problem regarding it.

with abort(); it was not working with me.

Do you have any suggestions?

Upvotes: 0

Views: 87

Answers (1)

The simplest way is to exit the application's event loop with a non-zero result code, and show a message box afterwards. You can either re-spin the event loop manually, or let the messagebox's static method do it for you.

#include <QPushButton>
#include <QMessageBox>
#include <QApplication>

QString globalMessage;

class Failer : public QObject {
    Q_OBJECT
public:
    Q_SLOT void failure() {
        globalMessage = "Houston, we have got a problem.";
        qApp->exit(1);
    }
};

int main(int argc, char ** argv) {
    QApplication app(argc, argv);
    QPushButton pb("Fail Me");
    Failer failer;
    failer.connect(&pb, SIGNAL(clicked()), SLOT(failure()));
    pb.show();
    int rc = app.exec();
    if (rc) {
        QMessageBox::critical(NULL, "A problem has occurred...", 
                              globalMessage, QMessageBox::Ok);
    }
    return rc;
}

#include "main.moc"

Upvotes: 1

Related Questions