QMainWindow close()信号未发出

时间:2014-08-22 19:52:20

标签: qt qt5

要在关闭一个继承自QMainWindow的窗口之前发出警告,我重新实现了它的closeEvent,当我手动发出close()时它可以正常工作。但是,单击" x"按钮不会触发这个;它只是退出。

它会为应用程序发出aboutToQuit(),我可以使用它来恢复"它关闭后的窗口。但是我希望在最初结束之前发出警告。

我不确定问题出在哪里。窗口是顶级的,没有正在运行的线程。我是否误解了实际连接到按钮点击的信号...? close(),对吧?

2 个答案:

答案 0 :(得分:2)

在主窗口类标题中(closeEvent必须是虚拟的):

public:
    /*!
     * \brief closeEvent
     * \param event
     */
    virtual void closeEvent ( QCloseEvent * event );

然后在cpp

void MainWindow::closeEvent( QCloseEvent *event )
{
    //! Ignore the event by default.. otherwise the window will be closed always.
    event->ignore();

    if(!EntitiesSaverObserver::Instance()->isAllSaved())
    {
        QMessageBox msgBox;
        msgBox.setWindowIcon(QIcon(":/Resources/Icons/warning.png"));
        msgBox.setIconPixmap(QPixmap(":/Resources/Icons/warning.png"));
        QString strToShow = QString("Some Entities has been created or modified...");
        msgBox.setText(strToShow);
        msgBox.setInformativeText("Do you want to save your changes?");
        msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
        msgBox.setDefaultButton(QMessageBox::Save);
        int ret = msgBox.exec();

        switch (ret) {
          case QMessageBox::Save:
            {
              // Save was clicked
              qDebug() << "SAVE";
              //! Do your stuff here
              // ....
              event->accept();
              break;
            }
          case QMessageBox::Discard:
            {
                // Don't Save was clicked
                qDebug() << "DISCARD";
                event->accept();
                break;
            }
          case QMessageBox::Cancel:
            {
              // Cancel was clicked
              qDebug() << "CANCEL";
              break;
            }
          default:
              // should never be reached
              break;
        }
    } else {
        event->accept(); // Do not need to save nothing... accept the event and close the app
    }
}

此外,如果您想将工具栏中的按钮作为QAction,您可以连接信号然后:

void MainWindow::on_actionExit_triggered()
{
    close();
}

这将调用主窗口的关闭事件。我希望这会对你有所帮助。

答案 1 :(得分:-1)

只需创建一个信号槽QObject :: connect(yourButton,SIGNAL(clicked()),这个,SLOT(close()));