ListView QML中图像的来源是什么

问题描述

我需要实现图像列表,这些图像由用户文件夹)选择并在列表中实现。 我在对象图片中使用遇到了一些麻烦。这样,我在控制台中看到“您选择了 path ..”,但是没有出现我的图像。为什么?正确的来源途径是什么?

该路径不是静态的,因为用户选择了其中包含许多图片文件夹,那我该怎么办?

FALSE

解决方法

我认为您误解了fileDialog.fileUrls给您的东西。它不会为您提供所选文件夹中文件的列表。它为您提供了所选文件或文件夹的列表。您仍然需要在目录中搜索所需的文件。值得庆幸的是,Qt提供了FolderListModel来做到这一点。因此,这是一个执行此操作的清理示例:

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.15
import QtQuick.Dialogs 1.2
import Qt.labs.folderlistmodel 2.15

Window {
    id: window
    width: 640
    height: 480
    visible: true

    Button {
        id: btn
        text: "Open"
        onClicked: fileDialog.open();
    }

    FileDialog {
        id: fileDialog;
        selectFolder: true;
        onAccepted: folderModel.folder = fileDialog.fileUrl;
    }

    ListView {
       id: listView
       anchors.top: btn.bottom
       width: 200
       height: 400
       model: FolderListModel {
           id: folderModel
           nameFilters: ["*.jpg","*.png","*.jpeg"]
           showDirs: false
       }
       delegate: Image {
            id: img
            width: 40
            height: 40
            source: fileUrl
        }
    }
}
,

首先,您需要将URL路径添加到模型中,然后使用它。注意文件前缀。像这样的东西:

FileDialog {
        id: fileDialog;
        selectFolder: true;
        onAccepted: updateFiles(fileDialog.files)
}

ListView {
           id: listView
           anchors.top: btn.bottom
           width: 200
           height: 400
           model: FolderListModel {
               id: folderModel
           }
           delegate: Image {
                id: img
                width: 40
                height: 40
                source: listView.model.get(index).fileUrl
            }
}

function updateFiles(fileList){
        console.log(fileList)
        console.log("You chose file(s): " + fileList.fileUrls)
        console.log("Num files: " + fileList.length)
        for(var i = 0; i < fileList.length; i++){
            var path = fileList[i];
            path = stripFilePrefix(path);
            var newFileUrl = {
                "fileUrl": path
            };
            folderModel.append(newFileUrl);
        } 
}

function stripFilePrefix(filePath) {
    if (Qt.platform.os === "windows") {
        return filePath.replace(/^(file:\/{3})|(file:)|(qrc:\/{3})|(http:\/{3})/,"")
    }
    else {
        return filePath.replace(/^(file:\/{2})|(qrc:\/{2})|(http:\/{2})/,"");
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...