Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch ESC key press event when editing a QTreeWidgetItem

I'm developing a project in Qt. I have a QTreeWidget(filesTreeWidget) whith some file names and a button for creating a file. The Create button adds to the filesTreeWidget a new item(the item's text is "") who is edited for choosing a name. When I press ENTER, the filename is send through a socket to the server. The problem comes when I press ESC because the filename remains "" and is not send to the server. I tried to overwrite the keyPressEvent but is not working. Any ideas? I need to catch the ESC press event when I'm editing the item.

like image 869
John Smith Avatar asked Dec 16 '22 14:12

John Smith


1 Answers

You can subclass QTreeWidget, and reimplement QTreeView::keyPressEvent like so:

void MyTreeWidget::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Escape)
    {
        // handle the key press, perhaps giving the item text a default value
        event->accept();
    }
    else
    {
        QTreeView::keyPressEvent(event); // call the default implementation
    }
}

There might be more elegant ways to achieve what you want, but this should be pretty easy. For example, if you really don't want to subclass, you can install an event filter, but I don't like doing that especially for "big" classes with lots of events because it's relatively expensive.

like image 152
Anthony Avatar answered Jan 10 '23 11:01

Anthony