编辑QTreeWidgetItem时,按ESC键按下事件 [英] Catch ESC key press event when editing a QTreeWidgetItem
问题描述
您可以对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屋!