问题:如何在使用QSortFilterProxyModel时自动扩展新QTreeView项的父项

时间:2010-04-17 05:30:22

标签: python qt pyqt pyqt4

我正在创建一个应用程序,用户可以随时向QTreeModel添加新数据。放置它的父级会自动展开以显示新项目:

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)

这可以按预期工作。如果我将QSortFilterProxyModel添加到混音中:

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)

父母不再扩张。知道我做错了吗?

1 个答案:

答案 0 :(得分:2)

我相信你应该在为它调用expand之前将扩展项索引映射到代理模型项索引。 QSortFilterProxyModel::mapFromSource方法应该做你需要的。请检查下面的示例是否适合您(这是c ++,如果您遇到将其转换为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());
}

希望这有帮助,尊重