如何从.model()存储和获取数据

时间:2014-09-15 18:28:58

标签: python qt pyqt

以下代码会使用QListView创建一个.model()。 在itemClicked我尝试访问index.data()以使用self.setData(index, QtCore.QVariant(inst))更早存储其值。但是,它不是返回存储的值(例如['Bison','Panther','Elephant']['Duck','Hawk','Pigeon']),而是返回键的名称(例如'Animals''Birds''Fish') 。在代码中应该更改什么才能使其按预期工作?

enter image description here

from PyQt4 import QtCore, QtGui
app=QtGui.QApplication(sys.argv) 

class Model(QtCore.QAbstractListModel):
    def __init__(self, *args):
        QtCore.QAbstractListModel.__init__(self, *args)
        self.items=[]    
    def rowCount(self, parent=QtCore.QModelIndex()):
        return len(self.items)    
    def data(self, index, role=QtCore.Qt.DisplayRole):
        if index.isValid():
            if role == QtCore.Qt.ItemDataRole:
                return self.data(index)
            elif role==QtCore.Qt.DisplayRole:                
                return QtCore.QVariant(self.items[index.row()])

    def addItems(self, instDict):
        for key in instDict:
            inst=instDict.get(key)
            index=QtCore.QModelIndex()
            self.beginInsertRows(index, 0, 0)
            self.setData(index, QtCore.QVariant(inst))    
        self.items.extend(instDict)
        self.endInsertRows()

class ListView(QtGui.QListView):
    def __init__(self):
        super(ListView, self).__init__()
        self.model= Model()
        self.model.addItems({'Animals':['Bison','Panther','Elephant'],'Birds':['Duck','Hawk','Pigeon'],'Fish':['Shark','Salmon','Piranha']})
        self.setModel(self.model)
        self.clicked.connect(self.itemClicked)
        self.show()
    def itemClicked(self, index):
        print 'self.data(index).toString(): %s'%index.data().toString()
        print 'self.model.data(index).toString(): %s'%self.model.data(index).toString()

window=ListView()
sys.exit(app.exec_())

以后编辑:

这是一个完整的例子,嵌套字典作为数据参数。

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 Model(QtCore.QAbstractListModel):
    def __init__(self):
        QtCore.QAbstractListModel.__init__(self)
        self.items=[] 
        self.modelDict={}       

    def rowCount(self, parent=QtCore.QModelIndex()):
        return len(self.modelDict)   

    def data(self, index, role):
        if index.isValid():
            if role==QtCore.Qt.ItemDataRole:
                key=str(index.data().toString())
                returnedValue=self.modelDict.get(key)
                return QtCore.QVariant(returnedValue) 

            elif role==QtCore.Qt.DisplayRole:
                return QtCore.QVariant(self.items[index.row()]) 

    def addItems(self):
        for key in self.modelDict:
            index=QtCore.QModelIndex()
            self.beginInsertRows(index, 0, 0)
            self.items.append(key)

            inst=self.modelDict.get(key)
            self.setData(index, QtCore.QVariant(inst), QtCore.Qt.DisplayRole)            

        self.endInsertRows()        

class ListView(QtGui.QListView):
    def __init__(self):
        super(ListView, self).__init__()
        self.model= Model()
        self.model.modelDict=elements
        self.model.addItems()
        self.setModel(self.model)
        self.clicked.connect(self.itemClicked)
        self.show()

    def itemClicked(self, index):
        itemTitle=self.model.data(index, QtCore.Qt.DisplayRole).toString()
        itemData=self.model.data(index, QtCore.Qt.ItemDataRole).toPyObject()
        print 'itemTitle: "%s" itemData: %s'%(itemTitle,itemData)

window=ListView()
sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:1)

from PyQt4 import QtCore, QtGui
app=QtGui.QApplication(sys.argv) 

class Model(QtCore.QAbstractListModel):
    def __init__(self, *args):
        QtCore.QAbstractListModel.__init__(self, *args)
        self.items=[]
        self.modelDict = None

    def rowCount(self, parent=QtCore.QModelIndex()):
        return len(self.items)   

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if index.isValid():
            if role == QtCore.Qt.ItemDataRole:
                return self.data(index)
            elif role==QtCore.Qt.DisplayRole:
                return QtCore.QVariant(self.items[index.row()])

    def getData(self, data):
        return self.modelDict[str(data)]

    def addItems(self, instDict):
        for key in instDict:
            inst=instDict.get(key)
            index=QtCore.QModelIndex()
            self.beginInsertRows(index, 0, 0)
            self.setData(index, QtCore.QVariant(inst), QtCore.Qt.DisplayRole)
        self.items.extend(instDict)
        self.endInsertRows()
        self.modelDict = instDict

class ListView(QtGui.QListView):
    def __init__(self):
        super(ListView, self).__init__()
        self.model= Model()
        self.model.addItems({'Animals':['Bison','Panther','Elephant'],'Birds':['Duck','Hawk','Pigeon'],'Fish':['Shark','Salmon','Piranha']})
        self.setModel(self.model)
        self.clicked.connect(self.itemClicked)
        self.show()

    def itemClicked(self, index):
        print 'self.data(index).toString(): %s'%index.data().toString()
        print 'self.model.data(index).toString(): %s'%self.model.getData(index.data().toString())

window=ListView()
sys.exit(app.exec_())

我不确定这是正确的方法,但这有效:)