Qt C++ QException issue : debug error

后端 未结 1 1046
野性不改
野性不改 2020-12-20 08:43

I want to read objects from an XML file and i need to handle 2 exceptions : when the file cannot be opened and when the file content cannot be loaded. (incorrectly formated)

相关标签:
1条回答
  • 2020-12-20 08:57

    The exceptions are thrown from code that runs in the event loop, specifically they will reach the QCoreApplication::notify(). This one is indirectly called from a.exec(), via an intervening operating system event loop call.

    Thus you can't merely wrap a.exec() in a try/catch. You must reimplement QCoreApplication::notify() as follows:

    class MyApplication : public QApplication
    {
    public:
       MyApplication(int & c, char ** a) : QApplication(c,a) {}
       virtual bool notify(QObject * obj, QEvent * ev) {
          bool rc = true;
          try {
             rc = QApplication::notify(obj, ev);
          }
          catch (QException &ex) {
             ...
          }
          return rc;
       }
    };
    
    int main(...) {
       MyApplication app(...);
       ...
    }
    

    Another problem with your code is that it screams to use the State Machine Framework. You should have states that represent file being open and closed, and intermediate states when e.g. an "unsaved changes" dialog box is shown. Then you won't have the ui->actionXYZ->setEnabled(true) littered around the code. Assuming you have a fileOpen state, you'd have

    fileOpen->assignProperty(ui->actionBy_name, "setEnabled", true);
    ...
    

    Then when the file is open, you emit a signal that is attached to a signal transition in the state machine. The state machine will do the rest - it will enable/disable actions for you, etc.

    0 讨论(0)
提交回复
热议问题