PyQt4的在QTableView中所选项目的文本通过点击
问题描述:
延迟我使用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)
答
,并在同一行什么也没有发生内选择一个新列。
这是因为您正在使用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())
更简单和完美的作品,谢谢。 (我没有意识到这种新风格,但看起来更干净,再次感谢。) –