QListView水平滚动条没有显示

时间:2018-02-01 15:45:54

标签: python qlistview

我注意到在用数据填充QListView的sourceModel后,水平滚动条没有出现?我该如何解决这个问题?

即使我将它们设置为始终显示,当内容超出窗口小部件的宽度时,它们也不会正确展开。

我猜这些问题是因为我将尺寸提示设置为图标大小。我这样做的原因是我可以控制图标的大小。

enter image description here

import os, sys
import tempfile
from PySide import QtGui, QtCore

class MyModel(QtCore.QAbstractTableModel):

    def __init__(self, *args, **kwargs):
        QtCore.QAbstractTableModel.__init__(self, *args, **kwargs)
        self._items = []
        self._iconSize = QtCore.QSize(18, 18)

    def rowCount(self, index=QtCore.QModelIndex()):
        return len(self._items)

    def columnCount(self, index=QtCore.QModelIndex()):
        return 1

    def addItem(self, obj):
        self.beginInsertRows(QtCore.QModelIndex(), self.rowCount(), self.rowCount())
        self._items.append(obj)
        self.endInsertRows()

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if not index.isValid():
            return None
        if 0 <= index.row() < self.rowCount():
            item = self._items[index.row()]
            if role == QtCore.Qt.DisplayRole:
                return item
            elif role == QtCore.Qt.SizeHintRole:
                return self._iconSize

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None,):
        super(MainWindow, self).__init__(parent)
        self.resize(300, 300)

        # controls
        model = QtGui.QSortFilterProxyModel()
        model.setSortCaseSensitivity(QtCore.Qt.CaseInsensitive)
        model.setSourceModel(MyModel())

        self.ui_list = QtGui.QListView()
        self.ui_list.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.ui_list.setModel(model)
        self.ui_list.setWordWrap(False)
        self._populate_model()

        # layout        
        self.setCentralWidget(self.ui_list)


    def _populate_model(self):
        root = tempfile.gettempdir() 
        for f in os.listdir(root):
            self.ui_list.model().sourceModel().addItem(os.path.join(root,f))

def main():
    app = QtGui.QApplication(sys.argv)
    ex = MainWindow()
    ex.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:0)

默认情况下,我们使用textElideModeQAbstractItemView)中启用的QListView属性,为了解决此问题,我们可以建立委托并覆盖sizeHint()方法,计算我们使用的宽度QFontMetrics

class Delegate(QtGui.QStyledItemDelegate):
    def sizeHint(self, option, index):
        h = QtGui.QStyledItemDelegate.sizeHint(self, option, index).height()
        text = index.data()
        fm = QtGui.QFontMetrics(option.font)
        w = fm.width(text)
        return QtCore.QSize(w, h)

然后成立代表:

    self.ui_list = QtGui.QListView()
    self.ui_list.setItemDelegate(Delegate(self))

enter image description here