延遲我使用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)
更簡單和完美的作品,謝謝。 (我沒有意識到這種新風格,但看起來更乾淨,再次感謝。) –