从QStringListModel()维护的列表中获取项目的索引

时间:2014-08-05 13:57:36

标签: python-2.7 pyside

由于QStringListModel()只有两个功能:setStringList()& stringList()

如何使用QStringListModel()维护列表中的项目索引?

1 个答案:

答案 0 :(得分:2)

问题有点模糊,所以我试图涵盖多个案例。以下是一些示例,尝试查找具有值' stuff'的列表项的索引。

# Assume that the QStringListModel is called strModel

# Get the QModelIndex of the first matching item
qModelIndex = strModel.match(strModel.index(0, 0), QtCore.Qt.DisplayRole, 'stuff')[0]

# Get a list of all matching QModelIndex'es (if your list has multiples)
qModelIndeces = strModel.match(strModel.index(0, 0), QtCore.Qt.DisplayRole, 'stuff', hits=-1)

# If you are trying to get just an int
# Special note: This line works in PySide because stringList() returns a Python list.
#  But it will not work in PyQt4 because stringList() returns a QStringList object.
index = strModel.stringList().index('stuff')  # raises a ValueError if item not found

# Getting just an int, if your list has multiples
indexList = [i for i, item in enumerate(strList) if item=='stuff']