QML:在GridView中加载图像

时间:2018-07-02 14:09:58

标签: image performance qt qml

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

然后,我想将它们加载到GridView中。 SwipeView有助于将图像分割为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
                }
            }
        }

    }
}

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

感谢和问候,

Eddie

1 个答案:

答案 0 :(得分:1)

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

作为一种快速解决方案,我建议您仅在当前页面上将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),则可以使用Image的{​​{3}}属性