在后台使用大数据集填充QListview

时间:2017-12-01 01:28:25

标签: python pyside

我的工具循环遍历几千张图像,并将图像的缩略图加载到我的列表视图中,如下所示。但是我的应用程序会冻结,直到处理完所有图像。我想知道是否有一种方法可以在列表视图中填充已加载的图像,防止UI冻结并让用户在填充图像时继续使用应用程序?

这一切都是通过python和pyside完成的。

enter image description here

代码:

import os
import sys
from PySide import QtGui, QtCore

class Example(QtGui.QMainWindow):

    def __init__(self):
        super(Example, self).__init__()
        self.resize(800, 400)
        self.setWindowTitle('Image Viewer')

        self.image_dir = "C:/Users/JokerMartini-Asus/Desktop/textures/thumbs"

        self.ui_image_viewer = QtGui.QListView()
        self.ui_image_viewer.setViewMode(QtGui.QListView.IconMode)
        self.ui_image_viewer.setResizeMode(QtGui.QListView.Adjust)
        self.ui_image_viewer.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.ui_image_viewer.setIconSize(QtCore.QSize(300,300))
        self.ui_image_viewer.setMovement(QtGui.QListView.Static)
        self.ui_image_viewer.setModel(QtGui.QStandardItemModel())

        for img in os.listdir(self.image_dir):
            img_path = os.path.join(self.image_dir, img)
            pixmap = QtGui.QPixmap(img_path)

            name = os.path.splitext(os.path.basename(img_path))[0]
            item = QtGui.QStandardItem(QtGui.QIcon(pixmap), name)
            self.ui_image_viewer.model().appendRow(item)

        # Layout
        grid = QtGui.QVBoxLayout()
        grid.setContentsMargins(10,10,10,10)
        grid.addWidget(self.ui_image_viewer)

        main_widget = QtGui.QWidget()
        main_widget.setLayout(grid)
        self.setCentralWidget(main_widget)
        self.show()

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:1)

生成重载的过程是QPixmap的创建,因此如果我们随着时间推移分配该负载,我们可以改善响应,我们可以通过QTimer来完成。

import os
import sys
from PySide import QtGui, QtCore

class Example(QtGui.QMainWindow):

    def __init__(self):
        super(Example, self).__init__()
        self.resize(800, 400)
        self.setWindowTitle('Image Viewer')

        self.image_dir = "C:/Users/JokerMartini-Asus/Desktop/textures/thumbs"

        self.ui_image_viewer = QtGui.QListView()
        self.ui_image_viewer.setViewMode(QtGui.QListView.IconMode)
        self.ui_image_viewer.setResizeMode(QtGui.QListView.Adjust)
        self.ui_image_viewer.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.ui_image_viewer.setIconSize(QtCore.QSize(300,300))
        self.ui_image_viewer.setMovement(QtGui.QListView.Static)
        self.ui_image_viewer.setModel(QtGui.QStandardItemModel())

        self.imgs = iter(os.listdir(self.image_dir))
        timer = QtCore.QTimer(self)
        timer.timeout.connect(self.load)
        timer.start(100)

        # Layout
        grid = QtGui.QVBoxLayout()
        grid.setContentsMargins(10,10,10,10)
        grid.addWidget(self.ui_image_viewer)

        main_widget = QtGui.QWidget()
        main_widget.setLayout(grid)
        self.setCentralWidget(main_widget)
        self.show()

    def load(self):
        try:
            img = next(self.imgs)
            img_path = os.path.join(self.image_dir, img)
            pixmap = QtGui.QPixmap(img_path)
            name = os.path.splitext(os.path.basename(img_path))[0]
            item = QtGui.QStandardItem(QtGui.QIcon(pixmap), name)
            self.ui_image_viewer.model().appendRow(item)
        except StopIteration:
            self.sender().stop()

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

另一种解决方案是在必要时加载图像,也就是说移动滚动条时,但为此我们必须覆盖模型的方法数据,同时我们必须创建一个新角色来存储路径但是我分析了QStandardItemModel的数据逻辑我发现它调用了SizeHintRole角色,它调用了角色DecorationRole,产生了同样的错误,所以我们应该做的是放一个预定义的大小,以避免调用DecorationRole,从而避免过载:

import os
import sys

from PySide.QtCore import *
from PySide.QtGui import *


class StandardItem(QStandardItem):
    PathRole = Qt.UserRole +1

    def __init__(self, *args, **kwargs):
        QStandardItem.__init__(self, *args, **kwargs)
        self.path = ""

    def setData(self, value, role=Qt.UserRole + 1):
        if role == StandardItem.PathRole:
            self.path = value
        else:
            QStandardItem.setData(self, value, role)
            # self.emitDataChanged()

    def data(self, role=Qt.UserRole+1):
        if role == StandardItem.PathRole:
            return self.path
        return QStandardItem.data(self, role)

    def type(self):
        return Qt.UserType


class StandardItemModel(QStandardItemModel):
    def __init__(self, *args, **kwargs):
        QStandardItemModel.__init__(self, *args, **kwargs)
        self.setItemPrototype(StandardItem())

    def data(self, index, role=Qt.DisplayRole):
        if role == Qt.DecorationRole:
            it = self.itemFromIndex(index)
            value = it.data(Qt.DecorationRole)
            if value is None:
                path = it.data(StandardItem.PathRole)
                value = QIcon(QPixmap(path))
                it.setData(value, Qt.DecorationRole)
            return value
        elif role == Qt.SizeHintRole:
            return QSize(300, 250)
        else:
            return QStandardItemModel.data(self, index, role)


class Example(QMainWindow):
    def __init__(self):
        super(Example, self).__init__()
        self.resize(800, 400)
        self.setWindowTitle('Image Viewer')

        self.image_dir = "C:/Users/JokerMartini-Asus/Desktop/textures/thumbs"

        self.ui_image_viewer = QListView()
        self.ui_image_viewer.setViewMode(QListView.IconMode)
        self.ui_image_viewer.setResizeMode(QListView.Adjust)
        self.ui_image_viewer.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.ui_image_viewer.setIconSize(QSize(300, 300))
        self.ui_image_viewer.setMovement(QListView.Static)
        self.ui_image_viewer.setModel(StandardItemModel())

        for img in os.listdir(self.image_dir):
            img_path = os.path.join(self.image_dir, img)
            name = os.path.splitext(os.path.basename(img_path))[0]
            item = StandardItem(name)
            item.setData(img_path)
            self.ui_image_viewer.model().appendRow(item)

        # Layout
        grid = QVBoxLayout()
        grid.setContentsMargins(10, 10, 10, 10)
        grid.addWidget(self.ui_image_viewer)

        main_widget = QWidget()
        main_widget.setLayout(grid)
        self.setCentralWidget(main_widget)
        self.show()


def main():
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()