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

2024-04-25 19:27:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用编程的方式在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-------------------------

Tags: 方法答案视图here信号编程方式事件
1条回答
网友
1楼 · 发布于 2024-04-25 19:27:32

因此,由于第一个信号是由select()方法发送的,所以在侦听selectionChanged()信号而不是currentRowChanged()信号时,找到了答案。在

这需要很少的修改:

#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)

相关问题 更多 >