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 按键事件
基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
