C ++ Qt QCloseEvent不起作用

时间:2017-08-29 08:08:23

标签: c++ qt

当用户按下退出按钮时,我想创建一个显示在新窗口中的消息。因此我创建了一个QCloseEvent,但MainWindow实际上根本没有关闭。我究竟做错了什么?

Mainwindow.h

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    //Constructor
    explicit MainWindow(QWidget *parent = 0);

    //Destructor
    ~MainWindow();

public slots:
    void closeMainWindow();

private:
    QCloseEvent *event;

MainWindow.cpp

void MainWindow::closeMainWindow(){

    event = new QCloseEvent();
    QMessageBox::StandardButton answer = QMessageBox::question(
                this,
                tr("Close the Window"),
                tr("Do you want to close the window?"),
                QMessageBox::Yes | QMessageBox::No);

    if(answer == QMessageBox::Yes){
        event->accept();
    }
    else
        event->ignore();
}

2 个答案:

答案 0 :(得分:3)

您必须实现mainwindow的closeEvent功能!

e.g

void MyMainWindow::closeEvent(QCloseEvent *event)
{
    QMessageBox::StandardButton answer = QMessageBox::question(
                this,
                tr("Close the Window"),
                tr("Do you want to close the window?"),
                QMessageBox::Yes | QMessageBox::No);

    if(answer == QMessageBox::Yes){
        event->accept();
    }
    else
        event->ignore();
}

答案 1 :(得分:0)

您缺少close()函数

if(answer == QMessageBox::Yes)
{
  event->accept();
  close();
}

或覆盖MainWindow的closeEvent()函数

参考以下链接: Generating a QCloseEvent won't close QMainWindow