views:

270

answers:

1

I'm making an app wherein the user can add new data to a QTreeModel at any time. The parent under which it gets placed is automatically expanded to show the new item:

self.tree = DiceModel(headers)
self.treeView.setModel(self.tree)
expand_node = self.tree.addRoll()
#addRoll makes a node, adds it, and returns the (parent) note to be expanded
self.treeView.expand(expand_node)

This works as desired. If I add a QSortFilterProxyModel to the mix:

self.tree = DiceModel(headers)
self.sort = DiceSort(self.tree)
self.treeView.setModel(self.sort)
expand_node = self.tree.addRoll()
#addRoll makes a node, adds it, and returns the (parent) note to be expanded
self.treeView.expand(expand_node)

the parent no longer expands. Any idea what I am doing wrong?

+2  A: 

I believe you should map your expanding item index into the proxy model item index before calling expand for it. QSortFilterProxyModel::mapFromSource method should do what you need. Please check if an example below would work for you (it's c++, let me know if you're having troubles converting it to python):

// create models
QStandardItemModel* model = new (QStandardItemModel);
QSortFilterProxyModel* proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(model);

// set model
ui->treeView->setModel(proxyModel);   
ui->treeView->setSortingEnabled(true);

// generate items
QStandardItem* parentItem0 = model->invisibleRootItem();
QModelIndex index = parentItem0->index();
for (int i = 0; i < 4; ++i)
{
    QStandardItem* item = new QStandardItem(QString("new item %0").arg(i));
    parentItem0->appendRow(item);
    parentItem0 = item;

    // expand items using proxyModel->mapFromSource 
    ui->treeView->expand(proxyModel->mapFromSource(item->index()));
    // line below doesn't work for you
    //ui->treeView->expand(item->index());
}

hope this helps, regards

serge_gubenko
That's exactly what I needed, thanks!
taynaron