2012-09-25 47 views
1

延遲我使用QTableView與使用QSortFilterProxyModel篩選記錄一起顯示QSqlTableModel的內容。在下面的代碼中,我設法讓用戶單擊單元格時顯示所選文本(無論是否應用了過濾器)。但是,它始終是一次點擊,開始後的第一次單擊會導致IndexError: pop from empty list,並且在同一行內選擇新列時什麼也不會發生。PyQt4的在QTableView中所選項目的文本通過點擊

我試過在初始化表格後選擇索引,似乎沒有做任何事情。我無法理解接下來要做什麼?

class TableViewer(QtGui.QWidget): 

    self.model = QSqlTableModel() 
    self._proxyModel = QtGui.QSortFilterProxyModel() 
    self._proxyModel.setSourceModel(self.model) 

    self.tv= QTableView() 
    self.tv.setModel(self._proxyModel) 

    '''Call-able filter - pass in string to filter everything that doesn't match string''' 
    QtCore.QObject.connect(self.textEditFilterBox, QtCore.SIGNAL("textChanged(QString)"),  self._proxyModel.setFilterRegExp) 


    def getItem(self): 
     '''Retruns item text of selected item''' 
     index = self.selectionModel.selectedIndexes().pop() 
     if index.isValid(): 
      row = index.row() 
      column = index.column() 
      model = index.model() 
      if hasattr(model, 'mapToSource'): 
       #proxy model 
       modelIndex = model.mapToSource(index) 
       print (modelIndex.row(), modelIndex.column()) 
       return self.model.record(modelIndex.row()).field(modelIndex.column()).value().toString() 
     return self.model.record(row).field(column).value().toString() 

class MainWindow(QtGui.QMainWindow): 

    #initialize TableViewer 

    self.tblViewer.connect(self.tblViewer.tv.selectionModel(), 
      SIGNAL(("currentRowChanged(QModelIndex,QModelIndex)")), 
      self.tblItemChanged) 

    def tblItemChanged(self, index): 
     '''display text of selected item ''' 
     text = self.tblViewer.getItem() 
     print(text) 

回答

1

,並在同一行什麼也沒有發生內選擇一個新列。

這是因爲您正在使用currentRowChanged信號。如果您在同一行中選擇一列,則不會觸發該信號。您應該使用currentChanged信號。 (和,你應該使用new style connections

而且,如果你僅僅是個數據之後,你不需要這些東西,以獲得非代理QModelIndex,然後問模型等。QModelIndex有一個方便的方法.data只是爲了這個目的。此外,信號會向您發送選定的索引,因此您不需要額外的工作。這使你的代碼這樣簡單:(注:不需要getItem法)

class MainWindow(QtGui.QMainWindow): 
    def __init__(self, parent=None): 
     #initialize TableViewer 
     self.tblViewer.tv.selectionModel().currentChanged.connect(self.tblItemChanged) 

    def tblItemChanged(self, current, previous): 
     '''display text of selected item ''' 
     # `data` defaults to DisplayRole, e.g. the text that is displayed 
     print(current.data().toString()) 
+0

更簡單和完美的作品,謝謝。 (我沒有意識到這種新風格,但看起來更乾淨,再次感謝。) –

相關問題