下面的代码会创建一个包含两个视图的对话框窗口:左侧为QListView
,右侧为QTableView
。两个视图共享相同的DataModel
实例。左视图显示动物的相同名称三次。如何调整代码,以便左视图不会列出重复的动物。
import os,sys
from PyQt4 import QtCore, QtGui
app=QtGui.QApplication(sys.argv)
elements={'Animals':{1:'Bison',2:'Panther',3:'Elephant'},'Birds':{1:'Duck',2:'Hawk',3:'Pigeon'},'Fish':{1:'Shark',2:'Salmon',3:'Piranha'}}
class ListModel(QtCore.QAbstractTableModel):
def __init__(self):
QtCore.QAbstractTableModel.__init__(self)
self.items=[]
def rowCount(self, parent=QtCore.QModelIndex()):
return len(self.items)
def columnCount(self, index=QtCore.QModelIndex()):
return 4
def data(self, index, role):
if not index.isValid() or not (0<=index.row()<len(self.items)): return QtCore.QVariant()
key=str(self.items[index.row()])
column=index.column()
if role==QtCore.Qt.DisplayRole:
if not column: return key
else: return elements.get(key,{}).get(column)
def buildItems(self):
for species in elements:
for number in elements[species]:
number=self.rowCount()
self.beginInsertRows(QtCore.QModelIndex(), number+1, 0)
self.items.append(species)
self.endInsertRows()
class TableModel(QtGui.QSortFilterProxyModel):
def __init__(self, parent=None):
super(TableModel, self).__init__(parent)
def headerData(self, column, orientation, role=QtCore.Qt.DisplayRole):
if role==QtCore.Qt.TextAlignmentRole:
if orientation==QtCore.Qt.Horizontal:
return QtCore.QVariant(int(QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter))
return QtCore.QVariant(int(QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter))
if role!=QtCore.Qt.DisplayRole:
return QtCore.QVariant()
if orientation==QtCore.Qt.Horizontal:
return QtCore.QVariant("Species %s"%column)
return QtCore.QVariant(int(column+1))
class Window(QtGui.QWidget):
def __init__(self):
super(Window, self).__init__()
mainLayout=QtGui.QHBoxLayout()
self.setLayout(mainLayout)
self.listModel=ListModel()
self.listModel.buildItems()
self.tableModel=TableModel()
self.tableModel.setFilterKeyColumn(0)
self.tableModel.setSourceModel(self.listModel)
self.viewA=QtGui.QListView()
self.viewA.setModel(self.listModel)
self.viewA.clicked.connect(self.onClick)
self.viewB=QtGui.QTableView()
self.viewB.setModel(self.tableModel)
mainLayout.addWidget(self.viewA)
mainLayout.addWidget(self.viewB)
self.show()
def onClick(self):
index=self.viewA.currentIndex()
key=self.listModel.data(index, QtCore.Qt.DisplayRole)
value=self.listModel.data(index, QtCore.Qt.ItemDataRole)
self.tableModel.setFilterRegExp('%s'%key)
window=Window()
sys.exit(app.exec_())
答案 0 :(得分:1)
很可能您不希望每species
number
次添加一次。所以删除这一行:
for number in elements[species]:
此外,您还可以在下一行为此变量提供值。
答案 1 :(得分:0)
当您插入项目时,错误位于for
函数的buildItems
循环中,请尝试检查此项。