在 Qt MainWindow 上设置 WA_DeleteOnClose 属性时,删除 ui 指针时程序崩溃
我已在 MainWindow 中设置了 WA_DeleteOnClose
小部件属性。
setAttribute(Qt::WA_DeleteOnClose);
但是,每当我关闭该主窗口时,我都会在其析构函数中遇到段错误,该析构函数中只有 delete ui;
简而言之,在 Creator 中创建了一个 Qt4 GUI 应用程序,添加了 setAttribute(Qt ::WA_DeleteOnClose);
到构造函数,程序现在在退出时崩溃。
I have set the WA_DeleteOnClose
widget attribute in a MainWindow.
setAttribute(Qt::WA_DeleteOnClose);
However, whenever I close that main window, I get a segfault in its destructor, which only has delete ui;
In a nutshell, created a Qt4 GUI Application in Creator, added the setAttribute(Qt::WA_DeleteOnClose);
to constructor, program now crashes on exit.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是第一次还是第二次在其析构函数中遇到段错误?请记住,您的主窗口析构函数应该只运行一次。也就是说,它应该因为堆栈展开而运行,或者因为
WA_DeleteOnClose
而运行,而不是同时运行。IIRC,Creator会将主窗口放在
main()
的堆栈上。因此,当main()
返回时,主窗口被销毁。Are you getting a segfault in its destructor the first time, or the second time? Remember that your main window destructor should run only once. That is to say that it should run either because of a stack unwind, or because of
WA_DeleteOnClose
, not both.IIRC, Creator will put the main window on the stack of
main()
. Therefore, whenmain()
returns the main window is destroyed.此链接提供了很好的解决方案建议。
我认为最好的方法是定义为 QPointer 指向 obj 并每次使用它时测试 NULL,这样当 UI obj 被销毁时,指针直接设置为 NULL。
“QPointer 为 QObject 提供受保护的指针。您可以使用它来保存对对话框的引用,当对话框被删除时,指针将自动设置为 NULL。”
this link gives a good suggestion on solution.
Me I think the best is to define as QPointer to point to the obj and test NULL each time using it, so when the UI obj get destroyed, the pointer set to NULL directly.
"QPointer provides guarded pointers for QObjects. You can use it to hold a reference to your dialog and when the dialog is deleted the pointer will be set to NULL automatically."