在QListView中显示具有相同缩略图大小的图像保持纵横比

时间:2013-12-04 06:29:45

标签: pyqt qlistview qabstractlistmodel

所以我想出了如何在QListView中显示图像:这是我做的方式

import sys
import os

from PyQt4 import QtGui, QtCore

class MyListModel(QtCore.QAbstractListModel): 
    def __init__(self, datain, parent=None, *args): 
        """ datain: a list where each item is a row
        """
        QtCore.QAbstractListModel.__init__(self, parent, *args) 
        self.listdata = datain

    def rowCount(self, parent=QtCore.QModelIndex()): 
        return len(self.listdata) 

    def data(self, index, role):
        if index.isValid() and role == QtCore.Qt.DecorationRole:
            return QtGui.QIcon(QtGui.QPixmap(self.listdata[index.row()]))
        if index.isValid() and role == QtCore.Qt.DisplayRole:
            return QtCore.QVariant(os.path.splitext(os.path.split(self.listdata[index.row()])[-1])[0])
        else: 
            return QtCore.QVariant()

class MyListView(QtGui.QListView):
    """docstring for MyListView"""
    def __init__(self):
        super(MyListView, self).__init__()
        # show in Icon Mode
        self.setViewMode(QtGui.QListView.IconMode)

        crntDir = "/usr/test1/Desktop"
        # create table
        list_data = []
        philes = os.listdir(crntDir)
        for phile in philes:
            if phile.endswith(".png"):
                list_data.append(os.path.join(crntDir, phile))
        lm = MyListModel(list_data, self)
        self.setModel(lm)
        self.show()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    window =  MyListView()
    window.show()
    window.raise_()
    sys.exit(app.exec_())

但现在我需要如何让所有图像显示相同的缩略图大小,文件名不应该移动它们而不是文件名应该换行到下一行!我应该怎样实现这一点。

2 个答案:

答案 0 :(得分:0)

Qt中缩略图的宽高比由scaled()的{​​{1}} method控制。此方法还提供控制缩略图大小的选项。在原始像素图上调用此方法,它将返回一个包含指定QPixmapsize的新像素图。

答案 1 :(得分:0)

class MyListView(QtWidgets.QListView):
"""docstring for MyListView"""
def __init__(self):
    super(MyListView, self).__init__()
    # show in Icon Mode
    self.setViewMode(QtWidgets.QListView.IconMode)
    self.setIconSize(QtCore.QSize(80, 80))  #set icon size
    self.setGridSize(QtCore.QSize(100, 100)) #set icon grid display
    # self.selectionModel(self.selectedIndexes())
    crntDir = "D:/temp"
    # create table
    list_data = []
    philes = os.listdir(crntDir)
    for phile in philes:
        if phile.endswith(".png"):
            list_data.append(os.path.join(crntDir, phile))
    lm = MyListModel(list_data, self)
    self.setModel(lm)
    self.show()