Qt中Esc键会在一些控件中默认的进行一些事件的触发,好比:QDialog,按下Esc键窗口消失。大多数状况下,咱们不须要这么作,那么就须要对默认事件进行屏蔽。markdown
经过查看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();
}
}
Ok,咱们若是想改变Esc键的默认动做,则能够经过两种途径:ui
重写Esc键对应的事件this
重写reject()spa
对QDialog使用事件过滤器,过滤Esc键。.net
installEventFilter(new EventFilter(this));
rest
bool EventFilter::eventFilter(QObject *obj, QEvent *event)
{
QDialog *pDialog = qobject_cast<QDialog *>(obj);
if (pDialog != NULL)
{
switch (event->type())
{
case QEvent::KeyPress:
{
QKeyEvent *pKeyEvent = static_cast<QKeyEvent*>(event);
if (pKeyEvent->key() == Qt::Key_Escape)
{
return true;
}
}
}
}
return QObject::eventFilter(obj, event);
}
重写QDialog的键盘事件keyPressEvent。code
void Dialog::keyPressEvent(QKeyEvent *event)
{
switch (event->key())
{
case Qt::Key_Escape:
break;
default:
QDialog::keyPressEvent(event);
}
}
m_bClosed为关闭的条件,为true时,窗口才会关闭。blog
void Dialog::reject()
{
if (m_bClosed)
QDialog::reject();
}
关于事件过滤器和事件重写实际上是属于一种状况,都是基于事件判断和过滤的,而事件过滤器相对来讲更易用、扩展性更好,不须要针对每一个控件都去重写对应的事件。事件
更多参考:
原文做者:一去丶二三里
做者博客:去做者博客空间