Qt:如何处理用户按下“X"(关闭)按钮的事件?

Qt: How do I handle the event of the user pressing the #39;X#39; (close) button?(Qt:如何处理用户按下“X(关闭)按钮的事件?)
本文介绍了Qt:如何处理用户按下“X"(关闭)按钮的事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在使用 Qt 开发应用程序.我不知道哪个插槽对应于用户单击窗口框架的'X'(关闭)按钮"的事件,即这个按钮:

I am developing an application using Qt. I don't know which slot corresponds to the event of "the user clicking the 'X'(close) button of the window frame" i.e. this button:

如果没有用于此的插槽,任何人都可以建议我一些其他方法,以便在用户按下关闭按钮后我可以启动功能.

If there isn't a slot for this, can anyone suggest me some other method by which I can start a function after the user presses that close button.

推荐答案

如果你有一个 QMainWindow 你可以覆盖 closeEvent 方法.

If you have a QMainWindow you can override closeEvent method.

#include <QCloseEvent>
void MainWindow::closeEvent (QCloseEvent *event)
{
    QMessageBox::StandardButton resBtn = QMessageBox::question( this, APP_NAME,
                                                                tr("Are you sure?
"),
                                                                QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes,
                                                                QMessageBox::Yes);
    if (resBtn != QMessageBox::Yes) {
        event->ignore();
    } else {
        event->accept();
    }
}


如果您要继承 QDialog,则不会调用 closeEvent,因此您必须覆盖 reject():


If you're subclassing a QDialog, the closeEvent will not be called and so you have to override reject():

void MyDialog::reject()
{
    QMessageBox::StandardButton resBtn = QMessageBox::Yes;
    if (changes) {
        resBtn = QMessageBox::question( this, APP_NAME,
                                        tr("Are you sure?
"),
                                        QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes,
                                        QMessageBox::Yes);
    }
    if (resBtn == QMessageBox::Yes) {
        QDialog::reject();
    }
}

这篇关于Qt:如何处理用户按下“X"(关闭)按钮的事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Unresolved external symbol quot;public: virtual struct QMetaObject const * __thiscall Parent(未解析的外部符号“public: virtual struct QMetaObject const * __thiscall Parent)
QVector vs QList(QVector 与 QList)
How to create/read/write JSON files in Qt5(如何在 Qt5 中创建/读取/写入 JSON 文件)
STL or Qt containers?(STL 还是 Qt 容器?)
Sort filenames naturally with Qt(使用 Qt 自然地对文件名进行排序)
Qt macro keywords cause name collisions(Qt 宏关键字导致名称冲突)