首页 > 解决方案 > QML:在 GridView 中加载图像

问题描述

我是 QML 初学者,想在我的应用程序中加载一些图片。FileDialog我选择包含大约 1000 张图像的文件夹。

然后,我想将它们加载到GridView. ASwipeView有助于将图像拆分为 40 个图像/屏幕。所以SwipeView有25页。

现在如何在不等待 1 小时加载图像的情况下加载图像?

这是我的代码:

import QtQuick 2.6
import QtQuick.Controls 2.1
import QtQuick 2.5
import QtQuick.Window 2.2
import QtQuick.Layouts 1.1
import Qt.labs.folderlistmodel 1.0
import QtQuick.Controls 1.4
import QtQuick.Controls 2.1
import QtQuick.Dialogs 1.1
import QtQml.Models 2.1


Window{
    visible: true
    width: 1000
    height: 600

    FolderListModel{
        id: lm
        showDirs: false
    }

    FileDialog {
        id: fileDialog
        selectFolder: true
        title: "Please choose a folder"
        folder: shortcuts.home
        onAccepted: {
            lm.folder = fileUrl+"/"
        }
        onRejected: {
            console.log("Canceled")
            Qt.quit()
        }
        Component.onCompleted: visible = true
    }

    SwipeView {
        width: 800
        height: 500
        clip: true
        currentIndex: 0

        Repeater {
            model: Math.ceil(lm.count / 40)
            delegate: gridView
        }
    }
    Component{
        id: gridView

        GridView{
            interactive: false
            width: 800
            height: 500
            property int viewIndex: index
            model: DelegateModel {
                model: lm
                groups: DelegateModelGroup { name: 'filter' }
                Component.onCompleted: {
                    for (var i = viewIndex * 40; i < lm.count && i < (viewIndex * 40) + 40; i++) {
                        items.setGroups(i, 1, ['items', 'filter'])
                    }
                }

                filterOnGroup: 'filter'

                delegate: Image {
                    width: 80
                    height: 120
                    source: lm.folder+fileName
                    asynchronous: true
                }
            }
        }

    }
}

如果有人可以帮助我,我会很高兴。

谢谢并恭祝安康,

埃迪

标签: imageperformanceqtqml

解决方案


问题是您正在加载所有 1000 张图像,而不仅仅是当前页面。

作为一个快速的解决方案,我建议您将 a 定义filterOnGroup'filter'GridView在当前页面上时,例如:

// note: `swipeViewId` is an id of the SwipeView
filterOnGroup: swipeViewId.currentIndex == index ? 'filter' : ''

另一种方法是Loader用作委托,如果它是当前SwipeView的,则将其设置sourceComponent为,gridView否则设置为 null。

Repeater {
    model: Math.ceil(lm.count / 40)
    delegate: Loader {
        sourceComponent: SwipeView.isCurrentItem ? gridView : null
        onLoaded: {
            item.viewIndex = index
        }
    }
}

此外,如果实际图像大于其预览(在您的示例中为 80x120),您可以使用sourceSize属性Image


推荐阅读