简述
Qt中Esc键会在一些控件中默认的进行一些事件的触发,比如:QDialog,按下Esc键窗口消失。大多数情况下,我们不需要这么做,那么就需要对默认事件进行屏蔽。
简述
源码分析
事件过滤器
事件重写
重写reject
源码分析
通过查看QDialog的源码,我们很容易会发现keyPressEvent事件中,当按下Esc键时,会默认执行reject()。
void QDialog::keyPressEvent(QKeyEvent *e)
{
// Calls reject() if Escape is pressed. Simulates a button
// click for the default button if Enter is pressed. Move focus
// for the arrow keys. Ignore the rest.
ifdef Q_OS_MAC
if(e->modifiers() == Qt::ControlModifier && e->key() == Qt::Key_Period) {
reject();
} else
endif
if (!e->modifiers() || (e->modifiers() & Qt::KeypadModifier && e->key() == Qt::Key_Enter)) {
switch (e->key()) {
case Qt::Key_Enter:
case Qt::Key_Return: {
QList<QPushButton*> list = findChildren<QPushButton*>();
for (int i=0; i<list.size(); ++i) {
QPushButton *pb = list.at(i);
if (pb->isDefault() && pb->isVisible()) {
if (pb->isEnabled())
pb->click();
return;
}
}
}
break;
case Qt::Key_Escape:
reject();
break;
default:
e->ignore();
return;
}
} else {
e->ignore();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
Ok,我们如果想改变Esc键的默认动作,则可以通过两种途径:
重写Esc键对应的事件
重写reject()
事件过滤器
对QDialog使用事件过滤器,过滤Esc键。
installEventFilter(new EventFilter(this));
bool EventFilter::eventFilter(QObject *obj, QEvent *event)
{
QDialog *pDialog = qobject_cast