简述
Qt中Esc键会在一些控件中默认的进行一些事件的触发,比如:QDialog,按下Esc键窗口消失。大多数情况下,我们不需要这么做,那么就需要对默认事件进行屏蔽。
源码分析
通过查看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 list =