Как сделать модель из QAbstractListModel с подгрузкой данных?
У меня есть итератор, неизвестно сколько в нем данных, нужно отобразить их пользователю.
Пусть это будет список. Тогда, думаю, нужно использовать модель QAbstractListModel.
Знаю, что у моделей есть специальные методы для подгрузки данных: canFetchMore и fetchMore
А как нужно их реализовывать, чтобы модель работала?
Ответы (3 шт):
Шаги:
- Метод
canFetchMoreдолжен возвращать булевое значение, отвечающий есть ли еще данные. Т.к. нам неизвестно сколько данных есть, то заведем флаг, пусть будетself._at_end. Значение флага будем менять при подгрузке данных вfetchMore, когда загрузили всё - В методе
fetchMoreперебираем итератор через функцию next, заполняем полученные из итератора данные в список (чтобы модель могла отобразить данные их нужно откуда-то брать, из итератора их уже не взять, т.к. нужно точная индексация, поэтому храним в списке) и ловим исключениеStopIteration, которое произойдет, когда итератор закончится. И обязательно, при получении новых данных нужно вызывать методы beginInsertRows и endInsertRows, чтобы уведомить о новых строках - Для возврата данных итератора используем метод
data. Он возвращает данные разных типов и для разных ролей, например, через этот метод можно показать разное значение для отображения (Qt.DisplayRole) и при редактировании (Qt.EditRole) - Чтобы представление знало сколько в модели на данный момент строк нужно использовать метод
rowCount
from typing import Iterator
from PyQt5.QtWidgets import QApplication, QListView
from PyQt5.QtCore import QAbstractListModel, QModelIndex, Qt, QVariant
class IteratorListModel(QAbstractListModel):
def __init__(self, it: Iterator, prefetch=100, parent=None):
super().__init__(parent)
self._at_end = False
self._it = iter(it)
self._items = []
self._prefetch = prefetch
def canFetchMore(self, parent: QModelIndex = None) -> bool:
return not self._at_end
def fetchMore(self, parent: QModelIndex = None):
if self._at_end:
return
old_rows = len(self._items)
for _ in range(self._prefetch):
try:
value = next(self._it)
self._items.append(value)
# Если данные закончились
except StopIteration:
self._at_end = True
break
new_rows = len(self._items)
if old_rows != new_rows:
self.beginInsertRows(QModelIndex(), old_rows, new_rows)
self.endInsertRows()
def data(self, index: QModelIndex, role: int = Qt.DisplayRole) -> QVariant:
if not index.isValid():
return QVariant()
if index.row() >= len(self._items) or index.row() < 0:
return QVariant()
if role == Qt.DisplayRole:
return self._items[index.row()]
return QVariant()
def rowCount(self, parent: QModelIndex = None) -> int:
return len(self._items)
if __name__ == '__main__':
app = QApplication([])
model = IteratorListModel(it=range(1_000_000))
model.rowsInserted.connect(lambda: mw.setWindowTitle(f'Rows: {model.rowCount()}'))
mw = QListView()
mw.setModel(model)
mw.show()
app.exec()
Результат:
Для тестирования модели накидал пример с большим количеством итераторов разного вида:
from string import printable
from typing import Iterator
from PyQt5.QtWidgets import QApplication, QWidget, QListView, QGroupBox, QHBoxLayout
from iterator_list_model import IteratorListModel
def get_infinity_generator():
i = 0
while True:
yield i
i += 1
class MainWindow(QWidget):
def __init__(self):
super().__init__()
main_layout = QHBoxLayout(self)
main_layout.addWidget(self._add_view_with_it('infinity_generator', get_infinity_generator()))
main_layout.addWidget(self._add_view_with_it('range(1_000_000)', range(1_000_000)))
main_layout.addWidget(self._add_view_with_it('list of pow2', [str(i ** i) for i in range(1_000)]))
main_layout.addWidget(self._add_view_with_it('str', printable * 100))
main_layout.addWidget(self._add_view_with_it('dict', dict.fromkeys(dir(self))))
def _add_view_with_it(self, title: str, it: Iterator) -> QWidget:
group_box = QGroupBox()
group_box.setTitle('1111')
model = IteratorListModel(it=it)
model.rowsInserted.connect(lambda: group_box.setTitle(f'[{title}] rows: {model.rowCount()}'))
view = QListView()
view.setModel(model)
layout = QHBoxLayout(group_box)
layout.addWidget(view)
return group_box
if __name__ == '__main__':
app = QApplication([])
mw = MainWindow()
mw.show()
app.exec()
Результат:
Вот еще пример для практического использования методов canFetchMore и fetchMore.
Как показать количество детей рядом с папкой QTreeView?
Чтобы получить количество строк,
это необходимо сделать после вызова метода fetchMore.
Все вышеперечисленное должно быть реализовано в делегате.
import sys
from PyQt5.QtCore import QDir
from PyQt5.QtWidgets import (QApplication, QFileSystemModel,
QStyledItemDelegate, QTreeView,
)
class StyledItemDelegate(QStyledItemDelegate):
def initStyleOption(self, option, index):
super().initStyleOption(option, index)
if index.column() != 0:
return
model = index.model()
if model.hasChildren(index):
if model.canFetchMore(index):
model.fetchMore(index)
option.text += " ({})".format(model.rowCount(index))
if __name__ == "__main__":
app = QApplication(sys.argv)
view = QTreeView()
view.resize(640, 480)
view.show()
model = QFileSystemModel()
model.setRootPath(QDir.currentPath())
view.setModel(model)
view.setRootIndex(model.index(QDir.currentPath()))
delegate = StyledItemDelegate(view)
view.setItemDelegate(delegate)
sys.exit(app.exec_())
а как вам официальный пример
#!/usr/bin/env python
#############################################################################
##
## Copyright (C) 2013 Riverbank Computing Limited
## Copyright (C) 2010 Darryl Wallace <[email protected]>.
## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
## All rights reserved.
##
## This file is part of the examples of PyQt.
##
## $QT_BEGIN_LICENSE:BSD$
## You may use this file under the terms of the BSD license as follows:
##
## "Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions are
## met:
## * Redistributions of source code must retain the above copyright
## notice, this list of conditions and the following disclaimer.
## * Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in
## the documentation and/or other materials provided with the
## distribution.
## * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
## the names of its contributors may be used to endorse or promote
## products derived from this software without specific prior written
## permission.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
## $QT_END_LICENSE$
##
#############################################################################
from PyQt5.QtCore import (pyqtSignal, QAbstractListModel, QDir, QLibraryInfo,
QModelIndex, Qt)
from PyQt5.QtWidgets import (QApplication, QGridLayout, QLabel, QLineEdit,
QListView, QSizePolicy, QTextBrowser, QWidget)
class FileListModel(QAbstractListModel):
numberPopulated = pyqtSignal(int)
def __init__(self, parent=None):
super(FileListModel, self).__init__(parent)
self.fileCount = 0
self.fileList = []
def rowCount(self, parent=QModelIndex()):
return self.fileCount
def data(self, index, role=Qt.DisplayRole):
if not index.isValid():
return None
if index.row() >= len(self.fileList) or index.row() < 0:
return None
if role == Qt.DisplayRole:
return self.fileList[index.row()]
if role == Qt.BackgroundRole:
batch = (index.row() // 100) % 2
if batch == 0:
return QApplication.palette().base()
return QApplication.palette().alternateBase()
return None
def canFetchMore(self, index):
return self.fileCount < len(self.fileList)
def fetchMore(self, index):
remainder = len(self.fileList) - self.fileCount
itemsToFetch = min(100, remainder)
self.beginInsertRows(QModelIndex(), self.fileCount,
self.fileCount + itemsToFetch)
self.fileCount += itemsToFetch
self.endInsertRows()
self.numberPopulated.emit(itemsToFetch)
def setDirPath(self, path):
dir = QDir(path)
self.beginResetModel()
self.fileList = dir.entryList()
self.fileCount = 0
self.endResetModel()
class Window(QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
model = FileListModel(self)
model.setDirPath(QLibraryInfo.location(QLibraryInfo.PrefixPath))
label = QLabel("Directory")
lineEdit = QLineEdit()
label.setBuddy(lineEdit)
view = QListView()
view.setModel(model)
self.logViewer = QTextBrowser()
self.logViewer.setSizePolicy(QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred))
lineEdit.textChanged.connect(model.setDirPath)
lineEdit.textChanged.connect(self.logViewer.clear)
model.numberPopulated.connect(self.updateLog)
layout = QGridLayout()
layout.addWidget(label, 0, 0)
layout.addWidget(lineEdit, 0, 1)
layout.addWidget(view, 1, 0, 1, 2)
layout.addWidget(self.logViewer, 2, 0, 1, 2)
self.setLayout(layout)
self.setWindowTitle("Fetch More Example")
def updateLog(self, number):
self.logViewer.append("%d items added." % number)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())



