C++ Qt:如何处理用户按下“X”(关闭)按钮的事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17480984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Qt: How do I handle the event of the user pressing the 'X' (close) button?
提问by The Peaceful Coder
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:
我正在使用 Qt 开发应用程序。我不知道哪个插槽对应于“用户单击窗口框架的'X'(关闭)按钮”的事件,即这个按钮:
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.
如果没有用于此的插槽,任何人都可以向我建议一些其他方法,以便在用户按下关闭按钮后我可以启动功能。
回答by asclepix
If you have a QMainWindow
you can override closeEvent
method.
如果你有一个QMainWindow
你可以覆盖的closeEvent
方法。
#include <QCloseEvent>
void MainWindow::closeEvent (QCloseEvent *event)
{
QMessageBox::StandardButton resBtn = QMessageBox::question( this, APP_NAME,
tr("Are you sure?\n"),
QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes,
QMessageBox::Yes);
if (resBtn != QMessageBox::Yes) {
event->ignore();
} else {
event->accept();
}
}
If you're subclassing a QDialog
, the closeEvent
will not be called and so you have to override reject()
:
如果您子类化 a QDialog
,closeEvent
则不会调用 ,因此您必须覆盖reject()
:
void MyDialog::reject()
{
QMessageBox::StandardButton resBtn = QMessageBox::Yes;
if (changes) {
resBtn = QMessageBox::question( this, APP_NAME,
tr("Are you sure?\n"),
QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes,
QMessageBox::Yes);
}
if (resBtn == QMessageBox::Yes) {
QDialog::reject();
}
}
回答by The Peaceful Coder
Well, I got it. One way is to override the QWidget::closeEvent
(QCloseEvent *event)
method in your class definition and add your code into that function. Example:
嗯,我明白了。一种方法是覆盖类定义中的方法并将代码添加到该函数中。例子:QWidget::closeEvent
(QCloseEvent *event)
class foo : public QMainWindow
{
Q_OBJECT
private:
void closeEvent(QCloseEvent *bar);
// ...
};
void foo::closeEvent(QCloseEvent *bar)
{
// Do something
bar->accept();
}
回答by Sebastian Lange
You can attach a SLOT to the
您可以将 SLOT 连接到
void aboutToQuit();
signal of your QApplication. This signal should be raised just before app closes.
QApplication 的信号。这个信号应该在应用程序关闭之前发出。
回答by Alexander
also you can reimplement protected member QWidget::closeEvent()
你也可以重新实现受保护的成员 QWidget::closeEvent()
void YourWidgetWithXButton::closeEvent(QCloseEvent *event)
{
// do what you need here
// then call parent's procedure
QWidget::closeEvent(event);
}