下面的代码创建一个QListView
。MyClass
(从QAbstractListModel继承)的实例被分配给它的self.setModel(self.model)
。如果单击视图,我可以选择列表中的项目(因此它们确实存在)。但没有显示项目的名称。如何控制QListView项的显示方式?你知道吗
from PyQt4 import QtCore, QtGui
app=QtGui.QApplication(sys.argv)
class MyClass(QtCore.QAbstractListModel):
def __init__(self):
super(MyClass, self).__init__()
self.elements={'Animals':['Bison','Panther','Elephant'],'Birds':['Duck','Hawk','Pigeon'],'Fish':['Shark','Salmon','Piranha']}
def rowCount(self, index=QtCore.QModelIndex()):
return len(self.elements)
def data(self, index, role=QtCore.Qt.DisplayRole):
print'MyClass.data():',index,role
class ListView(QtGui.QListView):
def __init__(self):
super(ListView, self).__init__()
self.model=MyClass()
self.setModel(self.model)
self.show()
window=ListView()
sys.exit(app.exec_())
我不知道如何使用字典来查找元素,但是使用列表:
只需在
data()
方法中返回self.elements[index.row()]
。例如:相关问题 更多 >
编程相关推荐