如何创建一个代理模型,将QAbstractItemModel的节点展平为PySide中的列表?

时间:2014-02-04 22:33:42

标签: qt pyqt pyside

我有一个由自定义QAbstractItemModel表示的节点层次结构。是否有可能创建一个代理模型,将层次结构展平为一个列表,以允许我在QListView中显示所有节点/项目(没有代理只显示树的第一级)?

A                           A
+---1                       1
    2                       2
    +--3                    3
    4            =>         4
B                           B
+---5                       5
    6                       6
    +--7                    7
       8                    8

谢谢, FIPS

1 个答案:

答案 0 :(得分:8)

QTreeView强制显示为列表视图更容易:

view = QtGui.QTreeView()
view.setModel(model)
view.expandAll()
view.setIndentation(0)
view.header().hide() 

如果您真的希望这样做,代理不是最琐碎的事情,因为它需要保留源模型的结构模型。对于更改其结构的源模型,代理还必须跟踪源模型的结构。

作为起点,下面是具有静态结构的模型的最小实现。我只在Python 3.3上测试过它。更改在视图之间传播 - 您可以在任一视图中编辑项目的文本,并且将修改基础树模型,并适当地通知另一个视图。

代理应该简单地传递列表模型,因为它们已经是平坦的。为了演示此透明度,右窗格是附加到中间窗格中查看的代理的代理的列表视图。在中间窗格中查看的代理将附加到在左窗格中查看的树模型。

screenshot

很乐意接受那些真正了解Python / PySide的人的编辑。我对Python的了解非常有趣。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from PySide import QtCore, QtGui

class FlatProxyModel(QtGui.QAbstractProxyModel):
    @QtCore.Slot(QtCore.QModelIndex, QtCore.QModelIndex)
    def sourceDataChanged(self, topLeft, bottomRight):
        self.dataChanged.emit(self.mapFromSource(topLeft), \
                              self.mapFromSource(bottomRight))
    def buildMap(self, model, parent = QtCore.QModelIndex(), row = 0):
        if row == 0:
            self.m_rowMap = {}
            self.m_indexMap = {}
        rows = model.rowCount(parent)
        for r in range(rows):
            index = model.index(r, 0, parent)
            print('row', row, 'item', model.data(index))
            self.m_rowMap[index] = row
            self.m_indexMap[row] = index
            row = row + 1
            if model.hasChildren(index):
                row = self.buildMap(model, index, row)
        return row
    def setSourceModel(self, model):
        QtGui.QAbstractProxyModel.setSourceModel(self, model)
        self.buildMap(model)
        print(flush = True)
        model.dataChanged.connect(self.sourceDataChanged)
    def mapFromSource(self, index):
        if index not in self.m_rowMap: return QtCore.QModelIndex()
        #print('mapping to row', self.m_rowMap[index], flush = True)
        return self.createIndex(self.m_rowMap[index], index.column())
    def mapToSource(self, index):
        if not index.isValid() or index.row() not in self.m_indexMap:
            return QtCore.QModelIndex()
        #print('mapping from row', index.row(), flush = True)
        return self.m_indexMap[index.row()]
    def columnCount(self, parent):
        return QtGui.QAbstractProxyModel.sourceModel(self)\
               .columnCount(self.mapToSource(parent))
    def rowCount(self, parent):
        #print('rows:', len(self.m_rowMap), flush=True)
        return len(self.m_rowMap) if not parent.isValid() else 0
    def index(self, row, column, parent):
        #print('index for:', row, column, flush=True)
        if parent.isValid(): return QtCore.QModelIndex()
        return self.createIndex(row, column)
    def parent(self, index):
        return QtCore.QModelIndex()
    def __init__(self, parent = None):
        super(FlatProxyModel, self).__init__(parent)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)

    model = QtGui.QStandardItemModel()
    names = ['Foo', 'Bar', 'Baz']
    for first in names:
        row = QtGui.QStandardItem(first)
        for second in names:
            row.appendRow(QtGui.QStandardItem(first+second))
        model.appendRow(row)

    proxy = FlatProxyModel()
    proxy.setSourceModel(model)

    nestedProxy = FlatProxyModel()
    nestedProxy.setSourceModel(proxy)

    w = QtGui.QWidget()
    layout = QtGui.QHBoxLayout(w)
    view = QtGui.QTreeView()
    view.setModel(model)
    view.expandAll()
    view.header().hide()
    layout.addWidget(view)
    view = QtGui.QListView()
    view.setModel(proxy)
    layout.addWidget(view)
    view = QtGui.QListView()
    view.setModel(nestedProxy)
    layout.addWidget(view)
    w.show()

    sys.exit(app.exec_())