创建事件过滤器
我正在尝试在树视图中启用删除键。这就是我到目前为止所拥有的:
class delkeyFilter(QObject):
delkeyPressed = pyqtSignal()
def eventFilter(self, obj, event):
if event.type() == QEvent.KeyPress:
if event.key() == Qt.Key_Delete:
self.delkeyPressed.emit()
print 'delkey pressed'
return True
return False
我像这样连接eventfilter
:
filter = delkeyFilter(self.dataTreeView)
self.dataTreeView.installEventFilter(filter)
为什么在创建过滤器时需要传递self.dataTreeview
?没有它它就无法工作。
I am trying to enable the delete key in my treeview. This is what I have so far:
class delkeyFilter(QObject):
delkeyPressed = pyqtSignal()
def eventFilter(self, obj, event):
if event.type() == QEvent.KeyPress:
if event.key() == Qt.Key_Delete:
self.delkeyPressed.emit()
print 'delkey pressed'
return True
return False
I connect the eventfilter
like this:
filter = delkeyFilter(self.dataTreeView)
self.dataTreeView.installEventFilter(filter)
Why do I need to pass self.dataTreeview
when I create the filter? It doesn't work without it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
@balpha是正确的。简单的答案是,如果您不传入父级或以其他方式确保
filter
实例具有实时引用,它将被垃圾收集。PyQt 使用 SIP 绑定到 Qt 的 C++ 实现。来自 SIP 文档:
上面的内容意味着,如果您将 Python 对象传递给拥有所有权的 Qt 对象,则一切都会正常工作,即使您无法保证维护对特定对象的引用。
因此,为了重申 @balpha 在他的评论中所说的话,当您不想将对象传递给构造函数时,这里有一种解决方法:
@balpha is correct. The simple answer is that if you don't pass in a parent or otherwise ensure that the
filter
instance has a live reference, it will be garbage collected.PyQt uses SIP to bind to Qt's C++ implementation. From the SIP documentation:
The above implies that if you pass a Python object to a Qt object that takes ownership, everything will also work, even though you haven't guaranteed that a reference to the specific object was maintained.
So, to restate what @balpha said in his comment, here's one workaround for the case when you don't want to pass in an object to the constructor:
QAbstractItemView 中已经实现了密钥处理。您所要做的就是对树视图进行子类化,然后实现
keyPressEvent
。`
Key handling is already implimented in
QAbstractItemView
. All you have to do is subclass the treeview, then implementkeyPressEvent
.`