我在实现__getitem__
和__setitem__
.
此类的实例是 a 的数据后端QAbstractListModel
。data(index)
我在执行模型时返回这些实例,role==Qt.UserRole
以便能够从模型外部访问对象。
我想要执行此操作的一种情况是,当用户单击QListView
使用我的模型显示数据的任何项目时。__getattr__
现在的问题是,只要我尝试从用户单击的索引中检索数据,我的程序就会开始在无限循环中运行(在 内)。
下面是一个完整的、可复制/可粘贴的代码片段,它再现了所描述的行为。程序将index.data(Qt.UserRole)
在testfunc
.
我是否在某处遗漏了一点,或者我在 PySide 中遇到了错误?
#!/usr/bin/python
from PySide.QtCore import QAbstractListModel, Qt, QObject
from PySide.QtGui import QApplication, QListView
import sys
###############################################################################
class TestObject(QObject):
def __init__(self, parent=None):
"""Creates new instance of TestObject.
@param parent Qt parent."""
super(TestObject, self).__init__(parent)
self._data = {}
def __getitem__(self, key):
"""Gets an item from self._data"""
if key in self._data.keys():
return self._data[key]
def __setitem__(self, key, value):
"""Sets the value for key."""
self._data[key] = value
###############################################################################
class TestModel(QAbstractListModel):
def __init__(self, parent=None):
"""Creates a new instance of TestModel.
@param parent Qt parent."""
super(TestModel, self).__init__(parent)
self._objects = []
for i in range(5):
obj = TestObject(self)
obj[i] = str(i)
self._objects.append(obj)
def rowCount(self, parent):
"""Returns the amount of datasets."""
return len(self._objects)
def columnCount(self):
"""Returns the amount of columns, which is 1."""
return 1
def data(self, index, role=Qt.DisplayRole):
"""Returns the data for the given model index"""
if index.isValid():
obj = self._objects[index.row()]
if role == Qt.DisplayRole:
return str(obj)
elif role == Qt.UserRole:
return obj
return None
###############################################################################
def testfunc(index):
"""Does something with index."""
print "getting..."
index.data(Qt.UserRole)
print "never getting here :/"
###############################################################################
if __name__ == "__main__":
app = QApplication(sys.argv)
view = QListView()
view.setModel(TestModel())
view.clicked.connect(testfunc)
view.show()
app.exec_()