#include <QApplication> #include <QWidget> int main(int argc, char *argv[]) { QApplication app(argc, argv); QWidget *window = new QWidget; window->showNormal(); window->setAttribute( Qt::WA_DeleteOnClose, true ); window->close(); return app.exec(); }
本意是這個widget closed後程式應該正常退出
但實際上進程依然運行。
Qt中對app的退出預設為最後一個視窗關閉時自動結束
可以通過setQuitOnLastWindowClosed來更改
關於 close() 函數的文檔
Closes this widget. Returns true if the widget was closed; otherwise returns false.
First it sends the widget a QCloseEvent. The widget is hidden if it accepts the close event. If it ignores the event, nothing happens. The default implementation of QWidget::closeEvent() accepts the close event.
If the widget has the Qt::WA_DeleteOnClose flag, the widget is also deleted. A close events is delivered to the widget no matter if the widget is visible or not.
The QApplication::lastWindowClosed() signal is emitted when the last visible primary window (i.e. window with no parent) with the Qt::WA_QuitOnClose attribute set is closed. By default this attribute is set for all widgets except transient windows such as splash screens, tool windows, and popup menus.
紅色部分,當最後一個視窗關閉的時候會產生 QApplication::lastWindowClosed() 訊號,而正是這個訊號使程式退出。
但是在調用 windows.close() 的時候,程式並沒有進入訊息迴圈,而作業系統是訊息響應的,
QApplication::lastWindowClosed() 訊號所對應的槽應該不會被執行。
而等程式進入app.exec() 之後,永遠沒有 quit() 執行,相當於進入的死迴圈
而上面的代碼為什麼要在那個地方調用 close() 方法。 (沒有理由 純屬無聊)在進入app.exec() 之前,建立的 Widget 可以不用關閉,程式運行結束的時候會自動關閉