<p>我在<a href="https://stackoverflow.com/questions/5219946/how-do-i-create-a-tree-view-with-checkbox-inside-a-combo-box-pyqt/5291844#5291844">How do I create a tree view (with checkbox) inside a combo box - PyQt</a>回答了一个类似的问题,但无论如何,为了完整起见,我将您粘贴在这里:</p>
<p>您应该创建一个模型,在data和SetData方法中支持Qt.CheckStateRole,在flags方法中支持标记Qt.ItemIsUserCheckable。</p>
<p>我在这里粘贴一个我在一个项目中使用的示例,这是一个QSortFilterProxyModel泛型实现,可以在任何模型中使用,但是您可以在模型实现中使用相同的思想,显然我在这个子类中使用的内部结构不是PyQt中直接使用的,而是附加到我的内部实现(self.booleanSet和self.readOnlySet)。</p>
<pre><code>def flags(self, index):
if not index.isValid():
return Qt.ItemIsEnabled
if index.column() in self.booleanSet:
return Qt.ItemIsUserCheckable | Qt.ItemIsSelectable | Qt.ItemIsEnabled
elif index.column() in self.readOnlySet:
return Qt.ItemIsSelectable | Qt.ItemIsEnabled
else:
return QSortFilterProxyModel.flags(self, index)
def data(self, index, role):
if not index.isValid():
return QVariant()
if index.column() in self.booleanSet and role in (Qt.CheckStateRole, Qt.DisplayRole):
if role == Qt.CheckStateRole:
value = QVariant(Qt.Checked) if index.data(Qt.EditRole).toBool() else QVariant(Qt.Unchecked)
return value
else: #if role == Qt.DisplayRole:
return QVariant()
else:
return QSortFilterProxyModel.data(self, index, role)
def setData(self, index, data, role):
if not index.isValid():
return False
if index.column() in self.booleanSet and role == Qt.CheckStateRole:
value = QVariant(True) if data.toInt()[0] == Qt.Checked else QVariant(False)
return QSortFilterProxyModel.setData(self, index, value, Qt.EditRole)
else:
return QSortFilterProxyModel.setData(self, index, data, role)
</code></pre>