Sometimes we want to do some operations before closing the window, such as saving the cache data or prompting the user whether to close the window.
Since windows generally inherit from qwidgets, We can override the closeevent (qcloseevent * event) function in qwidget to achieve this goal.
(1) first add the dependent database:
# Include <qcloseevent>
(2) declare and define the closeevent function: A). h file
Protected: void closeevent (qcloseevent * event );
B). cpp File
Void mainwindow: closeevent (qcloseevent * event) {// todo: the operation you want to perform before exiting the window}
I just applied closeevent to a small example above: In the main process, I fork () A sub-process and want to end the sub-process after the main window is closed (that is, the main process exits. In this case, the general practice is to listen to the window close event; then the window to be closed sends a SIGINT signal to its own process (parent process, the main process ends the sub-process by using the registered signal capturing function.
CodeDemo: (1) Main. cpp File
# Include <qtgui/qapplication> # include "mainwindow. H "int pid_t PID; pid_t child_make () {pid_t p_id; If (pid = fork ()> 0) {return p_id;} // todo: the following is the logical part of the sub-process} // end the sub-process void sig_int (INT signal) {kill (PID, sigterm);} int main (INT argc, char * argv []) {qapplication A (argc, argv); mainwindow W; W. show (); void sig_int (INT); pid = child_make (); // register the SIGINT function signal (SIGINT, sig_int); Return a.exe C ();}
(2) mainwindow. h file
# Include <qmainwindow> # include <qcloseevent> namespace UI {class mainwindow;} class mainwindow: Public qmainwindow {q_object public: explicit mainwindow (qwidget * parent = 0 ); // implement the virtual function closeevent (qcloseevent *) in qwidget; void closeevent (qcloseevent * event );~ Mainwindow (); Private: Ui: mainwindow * UI ;};
(3) mainwindow. cpp File
# Include "mainwindow. H "# include" ui_main1_1_h "# include <signal. h> mainwindow: mainwindow (qwidget * parent): qmainwindow (parent), UI (new UI: mainwindow) {UI-> setupui (this);} mainwindow ::~ Mainwindow () {Delete UI;} // implement the specific logic void mainwindow: closeevent (qcloseevent * event) in closeevent {// send a SIGINT signal to the process, equivalent to raise (SIGINT); kill (getpid (), SIGINT );}