没有发出QMainWindow close()信号



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

它确实发出aboutToQuit()的应用程序,我可以用它来"恢复"窗口后,它已经关闭。但是我想在初始结束前显示警告。

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

在主窗口类头中(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();
}
这将调用主窗口的关闭事件。我希望这对你有帮助。

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

相关内容

  • 没有找到相关文章

最新更新