如何将model()分配给QListVi

2024-04-27 13:09:16 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码创建一个QListViewMyClass(从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_())

Tags: 项目selfappindexmodelinitdefsys
1条回答
网友
1楼 · 发布于 2024-04-27 13:09:16

我不知道如何使用字典来查找元素,但是使用列表:

    self.elements=['Bison','Panther','Elephant','Duck','Hawk','Pigeon','Shark','Salmon','Piranha']

只需在data()方法中返回self.elements[index.row()]。例如:

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()

相关问题 更多 >