How can I display the image as a thumbnail

2019-05-27 01:44发布

问题:

I have a QTreeView to display the hard drives and Directories. also I have a QListView to display the images files as the following:

But I want to display the images as thumbnails, like the following:

My code:

mainWidget::mainWidget(QWidget *parent) : QWidget(parent), ui(new Ui::mainWidget){
    ui->setupUi(this);
    dirsModel = new QFileSystemModel;
    filesModel = new QFileSystemModel;
    dirsModel->setRootPath("");
    ui->treeView->setModel(dirsModel);
    ui->listView->setModel(filesModel);
    dirsModel->setFilter(QDir::AllDirs | QDir::NoDotAndDotDot);
    filesModel->setFilter(QDir::Files);
    ui->treeView->hideColumn(1);
    ui->treeView->hideColumn(2);
    ui->treeView->hideColumn(3);
    ui->treeView->header()->hide();
}

void mainWidget::on_treeView_clicked(const QModelIndex &index){
    ui->listView->setRootIndex(filesModel->setRootPath(dirsModel->filePath(index)));
}

Unfortunately, I don't know what is the way of changing the image view from icon to thumbnail.

回答1:

You should use special ViewMode:

 ui->listView->setViewMode(QListView::IconMode);

But it will show you only icons(not whole images), so I think you should create for example QStandardItemModel (because QFileSystemModel is not very suitable) and set pixmap to this model with Qt::DecorationRole, but scale this images to smaller size. As you understand if there are many images in the dir, this process can be long.

As you can see, you should every time (every on_treeView_clicked) get new list of images in the directory, You can do this with:

QStringList QDir::entryList(const QStringList & nameFilters, Filters filters = NoFilter, SortFlags sort = NoSort) const

with special filters. When you have list of files, in the loop you can create pixmaps, scale it and set to model.

By default QListView::IconMode provide Free movement. If you want avoid this you should use:

ui->listView->setMovement(QListView::Static);


回答2:

Depending on what you are after there are better ways to go about it I think, but here is an example based on a project of mine in python:

What you can do is subclass the QFileIconProvider:

ICON_SIZE = QSize(64,64)
accepted_types = (".jpg",".tiff",".png",".exr",".psd")

# this depends on the plugins you have installed,
# PSD and EXR requires external ones).

class IconProvider(QFileIconProvider):

    def __init__(self) -> None:
        super().__init__()

    def icon(self, type: 'QFileIconProvider.IconType'):

        fn = type.filePath()

        if fn.endswith(accepted_types):
            a = QPixmap(ICON_SIZE)
            a.load(fn)
            return QIcon(a)
        else:
            return super().icon(type)

Then on the Model you use:

self.fileSystemModel.setIconProvider(IconProvider)

Example on TreeView: