[Solved] Do I need to run Qt even loop (QApplication.exec()) to display QMessage::critical()?



  • While this code seems to work. Is it correct?
    I thought that no Qt functinality would work if I didn't use a.exec().

    @int main(int argc, char *argv[])
    {
    QApplication a(argc, argv);

    try {
        MainWindow w;
        w.show();
    
        return a.exec();
    }
    catch (ExceptionInitialization& exception) {
        qDebug() << exception.getMessage();
        QMessageBox::critical(nullptr,
                              QObject::tr("ERROR"),
                              exception.getMessage());
    
        return (-1);
    }
    

    }@



  • Not required. It is dialog. Instead of passing nullptr, try passing 0. What is the issue you are facing ? It it not shown ?


  • Moderators

    Hi,

    [quote author="Zingam" date="1407675034"]While this code seems to work. Is it correct?
    I thought that no Qt functinality would work if I didn't use a.exec().[/quote]Yes, it's fine.

    exec() starts and event loop. Without it, you can't handle events and signals, but other things in Qt still work. (For example, even if I don't call exec() I can still use QFile to read/write files)

    Note that there are many ways to start an event loop:

    • QCoreApplication::exec()
    • QThread::exec()
    • QEventLoop::exec()
    • QDialog::exec()

    What Dheerendra meant is that QMessage::critical() calls QDialog::exec() internally, so you do get a running event loop until you close the dialog.

    [quote author="Dheerendra" date="1407677087"]Instead of passing nullptr, try passing 0.[/quote]Why? nullptr was invented specifically to avoid the ambiguity caused by passing 0.

    We should encourage each other to use C++11.



  • @
    #include <QtGui/QApplication>
    #include <QtGui/QMessageBox>
    #include <exception>
    using namespace std;

    #if __cplusplus<201103L // naive C++11 support test
    #define nullptr 0
    #endif

    class MyException: public exception {
    virtual const char *what() const throw(){
    return "My Exception Happened";
    }
    } myException;

    int main(int argc, char *argv[])
    {
    QApplication a(argc, argv);

    try { throw myException; }
    catch(exception &e) {
        QMessageBox::critical(nullptr, "Exception!", e.what());
    }
    

    }
    @

    Works perfectly for me (Qt4.8) ;o)



  • Thank you!
    I wasn't sure if the MessageBox would work without issues. I do a great deal of initialization in MainWindow like copying files, socket initialization, xml parsing, etc. And if some of this fails I need to warn the user and exit.

    So I assume my doubts are solved.

    Note: It's a C++11 app.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.