[Qt-interest] How to catch key press/release first?

Martin Gebert martin.gebert at alpha-bit.de
Fri May 15 13:45:09 CEST 2009


> Next problem: The event filter works, but though I mark the 
> event as accepted and return true from my eventFilter() the 
> focused widget still handles the key press, too. What to do?


My current code for illustration of the issue:

--8><--

[...]
	QApplication::instance()->installEventFilter(this);	//For cursor
key control
[...]

bool MainWindow::eventFilter(QObject* watched, QEvent* event)
{
	if(m_ui.enableCursorControl->isChecked() && event->type() ==
QEvent::KeyPress)
	{
		const static QSet<Qt::Key> moveKeys(
			QSet<Qt::Key>() << Qt::Key_Up << Qt::Key_Down <<
Qt::Key_Left << Qt::Key_Right);
		QKeyEvent* ke = dynamic_cast<QKeyEvent*>(event);
		Q_ASSERT(ke);

		if(moveKeys.contains(Qt::Key(ke->key())) && ke->modifiers()
== Qt::NoModifier)
		{
			qDebug() << "Key pressed: " << ke->key();
			event->setAccepted(true);
			return true;
		}
	}

	return QMainWindow::eventFilter(watched, event);
}

--><8--

Martin






More information about the Qt-interest-old mailing list