编辑 QTreeWidgetItem 时捕获 ESC 按键事件 [英] Catch ESC key press event when editing a QTreeWidgetItem

查看:45
本文介绍了编辑 QTreeWidgetItem 时捕获 ESC 按键事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Qt 开发一个项目.我有一个 QTreeWidget(filesTreeWidget) 带有一些文件名和一个用于创建文件的按钮.Create 按钮向 filesTreeWidget 添加一个新项目(项目的文本是"),该项目被编辑以选择名称.当我按 ENTER 时,文件名通过套接字发送到服务器.当我按 ESC 时出现问题,因为文件名仍然是"并且没有发送到服务器.我试图覆盖 keyPressEvent 但不工作.有任何想法吗?我需要在编辑项目时捕捉 ESC 按下事件.

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.

推荐答案

你可以继承QTreeWidget,然后像这样重新实现QTreeView::keyPressEvent:

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.

这篇关于编辑 QTreeWidgetItem 时捕获 ESC 按键事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆