Catch ESC key press event when editing a QTreeWidg

2020-03-26 07:48发布

问题:

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.

回答1:

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.



回答2:

Implement keyPressEvent function as following:

void TestTreeWidget::keyPressEvent(QKeyEvent *event)
{
    switch (event->key())
    {
        case Qt::Key_Escape:
        {
            escapeKeyPressEventHandler(); 
            event->accept();
            break;
        }
        default:
            QTreeWidget::keyPressEvent(event);
    }
}

TestTreeWidget::escapeKeyPressEventHandler()
{
     // work with your QTreeWidgetItem here
}