天天看點

Qt 捕捉視窗關閉事件與信号的捕捉

作者:QT進階進階

有時候我們希望在關閉視窗之前做一些操作,例如儲存緩存資料或向使用者提示是否關閉視窗等等。

由于一般的視窗都是繼承自QWidget, 那麼我們可以通過覆寫QWidget中的虛函數closeEvent(QCloseEvent* event);來達到這個目的。

(1)首先添加依賴庫:

#include <QCloseEvent>           

2)接着聲明和定義closeEvent函數:

a).h檔案

1 protected:
2      void closeEvent(QCloseEvent *event);           

b).cpp檔案

1 void MainWindow::closeEvent(QCloseEvent *event)
2 {
3     //TODO: 在退出視窗之前,實作希望做的操作
4 }           

剛剛将closeEvent應用在了一個小例子上面:

我在主程序中fork()了一個子程序,希望在關閉主視窗後(也就是主程序退出)結束子程序。那麼這個時候一般的做法就是監聽視窗的關閉事件;然後将要關閉的視窗向本身程序(父程序)發送SIGINT信号,主程序通過已注冊好的信号捕捉函數來結束子程序。

【領更多QT學習資料,點選下方連結免費領取↓↓,先碼住不迷路~】

點選→領取Qt開發必備技術棧學習路線+資料

代碼示範:

(1)main.cpp檔案

1 #include <QtGui/QApplication>
 2 #include "mainwindow.h"
 3  
 4 int pid_t pid;
 5  
 6 pid_t child_make()
 7 {
 8     pid_t p_id;
 9  
10     if((pid = fork()) > 0)
11     {
12         return p_id;
13     }
14  
15     //TODO: 以下是子程序的邏輯部分
16 }
17  
18 // 結束子程序
19 void sig_int(int signal)
20 {
21     kill(pid, SIGTERM);
22 }
23  
24 int main(int argc, char *argv[])
25 {
26     QApplication a(argc, argv);
27     MainWindow w;
28     w.show();
29  
30     void sig_int(int);
31     pid = child_make();
32     // 注冊捕捉SIGINT信号的函數 
33     signal(SIGINT, sig_int);
34    
35     return a.exec();
36 }           

(2)mainwindow.h檔案

1 #include <QMainWindow>
 2 #include <QCloseEvent>
 3  
 4 namespace Ui {
 5 class MainWindow;
 6 }
 7  
 8 class MainWindow : public QMainWindow
 9 {
10     Q_OBJECT
11    
12 public:
13     explicit MainWindow(QWidget *parent = 0);
14     // 實作QWidget中的虛函數closeEvent(QCloseEvent*);
15     void closeEvent(QCloseEvent *event);
16     ~MainWindow();
17    
18 private:
19     Ui::MainWindow *ui;
20 };           

(3)mainwindow.cpp檔案

1 #include "mainwindow.h"
 2 #include "ui_mainwindow.h"
 3 #include <signal.h>
 4  
 5 MainWindow::MainWindow(QWidget *parent) :
 6     QMainWindow(parent),
 7     ui(new Ui::MainWindow)
 8 {
 9     ui->setupUi(this);
10 }
11  
12 MainWindow::~MainWindow()
13 {
14     delete ui;
15 }
16  
17 // 在closeEvent内實作具體邏輯
18 void MainWindow::closeEvent(QCloseEvent *event)
19 {
20     // 向自身程序發送SIGINT信号,相當于raise(SIGINT);
21     kill(getpid(), SIGINT);
22 }           

繼續閱讀