from PySide6.QtWidgets import QApplication, QListView
from PySide6.QtCore import QAbstractListModel, QModelIndex, Qt
import sys
import typing
class ChoiceModel(QAbstractListModel):
def __init__(self, data: typing.List[dict]) -> None:
super().__init__()
self._data = data
def rowCount(self, parent: QModelIndex = QModelIndex()) -> int:
if parent == QModelIndex():
return len(self._data)
return 0
def data(self, index: QModelIndex, role: int = Qt.DisplayRole) -> typing.Any:
if not index.isValid():
return None
if role == Qt.DisplayRole:
return self._data[index.row()]["name"]
if role == Qt.CheckStateRole:
return Qt.Checked if self._data[index.row()]["checked"] else Qt.Unchecked
def setData(
self, index: QModelIndex, value: typing.Any, role: int = Qt.CheckStateRole
) -> bool:
if role != Qt.CheckStateRole:
return False
if not index.isValid() or index.column() > 0:
return False
# Update the checked state
self._data[index.row()]["checked"] = True if value == Qt.Checked else False
state = "checked" if value == Qt.Checked else "unchecked me"
print(f"Item '{self._data[index.row()]['name']}' is now {state}")
# Notify the view of the change
self.dataChanged.emit(index, index, [Qt.CheckStateRole])
return True
def flags(self, index: QModelIndex) -> Qt.ItemFlags:
if not index.isValid():
return Qt.NoItemFlags
return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsUserCheckable
def checked_items(self):
return [it["name"] for it in self._data if it["checked"]]
if __name__ == "__main__":
app = QApplication(sys.argv)
view = QListView()
model = ChoiceModel(
[{"name": "Item 1", "checked": True}, {"name": "Item 2", "checked": False}]
)
view.setModel(model)
view.show()
app.exec()
what is wrong? check box not working , anyone fix this codes for me? checkbox not working