编辑 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.
相关文章