据我了解,在 Qt 中处理事件循环内发生的异常的方法是覆盖 QApplication::notify() 并在那里处理它。我已经尝试过了,它有效:
class Application : public QApplication
{
Q_OBJECT
public:
explicit Application( int& argc, char** argv );
// override to handle out of memory exceptions
bool notify( QObject* receiver, QEvent* e );
signals:
public slots:
private:
char* m_buffer;
};
Application::Application(int &argc, char **argv)
:QApplication( argc, argv )
{
m_buffer = new char[1024*1024];
}
bool Application::notify(QObject *receiver, QEvent *e)
{
try
{
return QApplication::notify( receiver, e );
}
catch( std::bad_alloc& )
{
if ( m_buffer )
{
delete[] m_buffer;
m_buffer = NULL;
}
// calling QMessageBox from here doesn't work
// even if release a load of reserved memory
// don't know why
QMessageBox::critical( NULL, "Exception", "Application out of memory" );
}
但是消息框出现时是空白的(即未正确呈现)。我想也许这个过程没有足够的内存。所以我尝试在开始时分配 1MB 内存(参见上面的 m_buffer),然后在 QMessageBox 显示之前释放它。但这也没有用。有任何想法吗?