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

gui*_*ui3 0 python qt pyqt selection qtreeview

我想以编程方式在 QTreeView 中选择一行,我在这里找到了 95% 的答案。

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-------------------------
Run Code Online (Sandbox Code Playgroud)

gui*_*ui3 5

因此,多亏了这些评论,我们在侦听 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)
Run Code Online (Sandbox Code Playgroud)