Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

qt - How to create a proxy model that would flatten nodes of a QAbstractItemModel into a list in PySide?

I have a hierarchy of nodes represented by a custom QAbstractItemModel. Is it possible to create a proxy model that would flatten the hierarchy into a list to allow me to present all the nodes/items in a QListView (without a proxy only the first level of the tree gets presented)?

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

Thanks, FipS

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's way easier to just coerce a QTreeView to look like a list view:

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

If you really wish to do it, the proxy isn't the most trivial affair, since it needs to retain a structural model of the source model. For a source model that changes its structure, the proxy must also keep track of the structure of the source model.

As a starting point, below is a minimal implementation for a model with static structure. I've only tested it on Python 3.3. The changes are propagated between the views - you can edit the text of an item in either view, and the underlying tree model will be modified, and the other view appropriately notified.

The proxy should simply pass-through list models, as they are already flat. To demonstrate this transparency, the right pane is a list view of a proxy attached to the proxy viewed in the middle pane. The proxy viewed in the middle pane is attached to the tree model viewed in the left pane.

screenshot

I gladly accept edits by those who actually know Python/PySide. My knowledge of Python is very recreational at the moment.

#!/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_())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...