Я создал модель для отображения данных в QListview
и вложил QAbstractListModel
для создания модели. Поведение подкласса QAbstractListModel
вызвало некоторые вопросы.
из документов для модели Sublcassed требуется несколько обязательных методов. который я реализовал
class OurModel(qtc.QAbstractListModel):
def __init__(self, todos=None):
# todos=None defines a named optional argument
super().__init__()
self.todos = todos or []
def data(self, index, role):
if role == qtc.Qt.DecorationRole:
# See below for the data structure.
text = self.todos[index.row()]
return text
def rowCount(self, index):
return len(self.todos)
Похоже, что методы модели инициализируются при создании экземпляра этой модели
Мне остается неясным, почему эти методы требуют аргументов для правильной работы, например def data(self, index, role):
но "работать", не вставляя в них значения? Какие значения вставляются в эти методы?
полный код
import sys
from PyQt5 import QtWidgets as qtw
from PyQt5 import QtCore as qtc
from PyQt5 import QtGui as qtg
class OurModel(qtc.QAbstractListModel):
def __init__(self, todos=None):
# todos=None defines a named optional argument
super().__init__()
self.todos = todos or []
def data(self, index, role):
if role == qtc.Qt.DecorationRole:
# See below for the data structure.
text = self.todos[index.row()]
return text
def rowCount(self, index):
return len(self.todos)
class MainWindow(qtw.QWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# your code will go here
list_view = qtw.QListView(self)
red = qtg.QColor(255, 0, 0)
green = qtg.QColor(0, 255, 0)
blue = qtg.QColor(0, 0, 255)
self.model = OurModel(todos=[green, red, blue])
list_view.setModel(self.model)
# layout
vboxlayout = qtw.QVBoxLayout()
vboxlayout.addWidget(list_view)
self.setLayout(vboxlayout)
# your code ends here
self.show()
if __name__ == '__main__':
app = qtw.QApplication(sys.argv)
w = MainWindow()
sys.exit(app.exec_())