PyQt:以编程方式在QTreeView中选择行并发出信号

时间:2016-11-15 15:28:58

标签: python qt pyqt selection qtreeview

我希望以编程方式在QTreeView中选择一行,我找到了95%的答案here

select()方法完美地完成了这项工作,但它似乎没有触发任何点击视图的事件。

我通过自己调用所需信号找到了一种解决方法 - 但是有没有一种方法可以模拟人工点击并发送所有相关信号?

这是我的解决方法(在Python中):

oldIndex=treeView.selectionModel().currentIndex()
newIndex=treeView.model().indexFromItem(item)
#indexes stored----------------------------------
treeView.selectionModel().select(
    newIndex,
    QtGui.QItemSelectionModel.ClearAndSelect)
#selection changed-------------------------------
treeView.selectionModel().currentRowChanged.emit(
    newIndex,
    oldIndex)
#signal manually emitted-------------------------

1 个答案:

答案 0 :(得分:1)

所以感谢评论,在收听selectionChanged()信号而不是currentRowChanged()时发现了答案,因为第一个是由select()方法发送的。

这需要很少的修改:

#in the signal connections :__________________________________________
    #someWidget.selectionModel().currentRowChanged.connect(calledMethod)
    someWidget.selectionModel().selectionChanged.connect(calledMethod)

#in the called Method_________________________________________________
#selectionChanged() sends new QItemSelection and old QItemSelection
#where currentRowChanged() sent new QModelIndex and old QModelIndex
#these few lines allow to use both signals and to not change a thing
#in the remaining lines
def calledMethod(self,newIndex,oldIndex=None):
    try: #if qItemSelection
        newIndex=newIndex.indexes()[0]
    except: #if qModelIndex
        pass
    #..... the method has not changed further

#the final version of the programmatical select Method:_______________
def selectItem(self,widget,itemOrText):
    oldIndex=widget.selectionModel().currentIndex()
    try: #an item is given--------------------------------------------
        newIndex=widget.model().indexFromItem(itemOrText)
    except: #a text is given and we are looking for the first match---
        listIndexes=widget.model().match(widget.model().index(0, 0),
                          QtCore.Qt.DisplayRole,
                          itemOrText,
                          QtCore.Qt.MatchStartsWith)
        newIndex=listIndexes[0]
    widget.selectionModel().select( #programmatical selection---------
            newIndex,
            QtGui.QItemSelectionModel.ClearAndSelect)