2016-11-15 3 views
0

Я искал выбор строки в QTreeView программно, и я нашел 95% ответа here.PyQt: выбрать строку в QTreeView программно и испускать сигналы

Метод 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

Какие конкретно связаны сигналы вы referrring к? – ekhumoro

+1

@ekhumoro Вероятно, это сигнал выбора. Однако это должно было быть испущено, не так ли? – Trilarion

+0

на самом деле мне нужен сигнал currentRowChanged, так что взлом работает в моем случае, но мне было интересно, есть ли способ имитировать щелчок человека и ВСЕ сигналы, которые исходят из этого. – Gui3

ответ

1

Так благодаря комментариям ответ был найден в listenning на 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) 
+0

'if isinstance (QtGui.QItemSelection, newIndex): ...' – ekhumoro

+0

да, это было бы более точно , Я парень с тех пор, как я пошел от 20 до 0,5 с, заменив IF с помощью TRY в некоторой функции загрузки, но я думаю, в этом случае нет необходимости в этом – Gui3

Смежные вопросы