Catch ESC key press event when editing a QTreeWidgetItem

时间秒杀一切 提交于 2019-12-01 09:16:46

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.

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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!