我正在尝试使用PyQt连接到QTreeView的selectionChanged信号。我过去做过这个(对于QTableView)并且成功了。但现在我无法获得类似的代码。
在下面的代码示例中,我成功连接到展开和折叠的信号,但没有成功连接到selectionChanged或激活的信号。有人能告诉我我做错了什么吗?感谢。
from PyQt4 import QtGui
from PyQt4 import QtCore
################################################################################
class ShaderDefTreeView(QtGui.QTreeView):
"""
Overrides the QTreeView to handle keypress events.
"""
#---------------------------------------------------------------------------
def __init__(self, parent=None):
"""
Constructor for the ShaderDefTreeView class.
"""
super(ShaderDefTreeView, self).__init__(parent)
#listen to the selectionChanged signal
print "Connecting"
#whenever the selection changes, let the data model know
self.connect(self,
QtCore.SIGNAL("selectionChanged(QItemSelection&, QItemSelection&)"),
self.store_current_selection)
self.connect(self, QtCore.SIGNAL("activated(const QModelIndex &)"),
self.activated)
self.connect(self, QtCore.SIGNAL("collapsed(const QModelIndex &)"),
self.collapsed)
self.connect(self, QtCore.SIGNAL("expanded(const QModelIndex &)"),
self.expanded)
#---------------------------------------------------------------------------
def store_current_selection(self, newSelection, oldSelection):
print "changed"
#self.model().selection_changed(newSelection)
#---------------------------------------------------------------------------
def expanded(self, newSelection):
print "expanded"
#---------------------------------------------------------------------------
def collapsed(self, newSelection):
print "collapsed"
#---------------------------------------------------------------------------
def activated(self, newSelection):
print "activated"
答案 0 :(得分:13)
好的,想通了(大多是偶然的)。
由于我在 init 中建立了连接,但之后只为此QTreeView设置了模型,因此没有有效的selectionModel。
为了使其发挥作用,我必须进行两项修改:
1)必须将发射对象更改为QTreeView的selectionModel。我不知道为什么,但网上的一些(罕见的)例子表明可能是这种情况
和
2)我必须覆盖QTreeView的setModel方法,以便调用超类的setModel方法,然后再建立连接。
所以新代码看起来像这样:
class ShaderDefTreeView(QtGui.QTreeView):
"""
Overrides the QTreeView to handle keypress events.
"""
#---------------------------------------------------------------------------
def __init__(self, parent=None):
"""
Constructor for the ShaderDefTreeView class.
"""
super(ShaderDefTreeView, self).__init__(parent)
#---------------------------------------------------------------------------
def setModel(self, model):
super(ShaderDefTreeView, self).setModel(model)
self.connect(self.selectionModel(),
QtCore.SIGNAL("selectionChanged(QItemSelection, QItemSelection)"),
self.store_current_selection)
#---------------------------------------------------------------------------
def store_current_selection(self, newSelection, oldSelection):
print "changed"
答案 1 :(得分:4)
如果您使用声明,则可以执行以下操作:
self.ui = uic.loadUi(main_path, self)
self.ui.tree.selectionModel().selectionChanged.connect(self.item_selection_changed_slot)