以下代码会创建一个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_())
答案 0 :(得分:1)
我不知道如何使用字典作为元素,但使用列表:
self.elements=['Bison','Panther','Elephant','Duck','Hawk','Pigeon','Shark','Salmon','Piranha']
您只需在self.elements[index.row()]
方法中返回data()
即可。例如:
class MyClass(QtCore.QAbstractListModel):
def __init__(self):
super(MyClass, self).__init__()
self.elements=['Bison','Panther','Elephant','Duck','Hawk','Pigeon','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
if index.isValid() and role == QtCore.Qt.DisplayRole:
return QtCore.QVariant(self.elements[index.row()])
else:
return QtCore.QVariant()