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

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

问题描述

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

解决方案

您可以对QTreeWidget进行子类化,并重新实现 QTreeView :: keyPressEvent 像这样:

  void MyTreeWidget :: keyPressEvent(QKeyEvent *事件)
{
if(event-> key()== Qt :: Key_Escape)
{
//处理按键,也许给项目文本默认value
event-> accept();
}
else
{
QTreeView :: keyPressEvent(event); //调用默认实现
}
}

可能会更优雅实现你想要的方法,但这应该很容易。例如,如果你真的不希望子类化,你可以安装一个事件过滤器,但是我不喜欢这样做,特别是对于大类,有很多事情,因为它比较昂贵。


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.

解决方案

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天全站免登陆