PDA

View Full Version : TextEdit created by QAbstractItemDelegate can't receive Escape key event?



quantity
8th November 2011, 07:31
Hi guys,

I have a QTableView to display a bunch of data, which is stored in a QStyledItemDelegate. I also want to edit the data sometime, so I use a QAbstractItemDelegate to create an editor (of QTextEdit type) when I double click on the cell. However, I want to handle the key Press event myself, but I never catch Key_Escape pressing in the Text Edit editor (Other keys such as Enter and Ascii can be captured). I checked the code, and found that Escape is directly connected to QTableView's closeEditor() function, which is a virtual method and is automatically invoked. As far as I know, key press event is the bottom layer of event handling, but it is not true with such case.

I do need to capture the Escape key press event so that I can handle it myself, can anyone tell me how to do this? Thanks!

quantity
8th November 2011, 10:33
I got the answer, and I think would help others:

Override QStyledItemDelegate::eventFilter() method:

MyItemDelegate::eventFilter(QObject* editor, QEvent* event)
{
if(event->type()==QEvent::KeyPress)
return false;
return QStyledItemDelegate::eventFilter(editor, event);
}
According to Qt's documentation, QStyledItemDelegate::eventFilter() returns true if the given editor is a valid QWidget and the given event is handled; otherwise returns false. Tab, Backtab, Enter, Return and Ecs are handled by default. So, if you want to handle the key press event yourself, you must let eventFilter return false when KeyPress event occurs. So that the editor's keyPressEvent() method will be invoked instead.