【问题标题】:Error messages and having better organized code in Qt错误消息和在 Qt 中更好地组织代码
【发布时间】:2014-06-03 15:27:43
【问题描述】:

当它启动时,它会从文件中加载数据并在将其保存到内存之前验证它是否正确。

RepositoryInFile::RepositoryInFile(Validator *validator){
    this->validator = validator;
    this->read();
}

read() 是一个私有方法,它尝试从文件中打开和读取数据。它也抛出异常。当我在程序中发现错误时,我会执行以下操作:

  try {
    //do something
  } catch (CustomException customE) {
    QString message = QString::fromStdString(customE.reason());
    // I'm not extending std::exception beacause... well I don't know why
    QMessageBox::critical(this, "Error!", message);
  }

现在,如果 RepositoryInFile 的构造函数出现问题,我可以抛出异常并在我的主函数中捕获它,但我无法在屏幕上显示一个漂亮的消息框,通知用户出现问题(或者我不不知道怎么做)。 现在我使用 qDebug() 在控制台中显示一条消息,但这只是为了帮助我。

【问题讨论】:

  • 最后一段听起来很不错。首先启动 GUI,然后在单独的线程中开始执行其余操作,并通知 GUI 任何更新。
  • "...但我无法在屏幕上显示漂亮的消息框"。为什么不能?
  • @vahancho 因为 QMessageBox::critical ( QWidget * parent, const QString & title, const QString & text, StandardButtons buttons = Ok, StandardButton defaultButton = NoButton ) 并且同样适用于 QMessageBox::information 和QMessageBox::警告。当我在 main 时,父母是什么?我是这个 Qt 的新手,所以我说“或者我不知道怎么做”。
  • @user3002428,如果您的应用程序中没有其他窗口,则可以将父参数设置为空(0)。
  • @vahancho 哦,谢谢!但是这样组织我的代码可以吗?在构造函数中调用 read()?

标签: c++ qt oop


【解决方案1】:

我是否应该重新设计 RepositoryInFile 的工作方式并使用其他方法在 GUI 初始化后从文件中加载数据?

不一定需要。您可以简单地在异常处理程序中显示消息框。您需要做的唯一更改是:

QMessageBox::critical(0, "Error!", message);
//                    ^

所以,基本上如果你用“零”替换它,那么它将成为你 UI 的“根”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2011-07-10
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    • 1970-01-01
    相关资源
    最近更新 更多