Catch ESC key press event when editing a QTreeWidgetItem(编辑 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 按键事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:编辑 QTreeWidgetItem 时捕获 ESC 按键事件


基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01