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 按键事件
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
