【问题标题】:How to always expand items in QTreeView?如何始终在 QTreeView 中展开项目?
【发布时间】:2019-02-28 17:10:31
【问题描述】:

我正在自己创建一个完成程序,使用 ComboBox 和 QTreeView(用于提案列表)。

MyComboBox::MyComboBox( QWidget *p_parent ) : QComboBox( p_parent )
{
  setEditable(true);

  m_view = new QTreeView();
  m_view->expandAll();     // this command does not work!!!

  m_view->setItemDelegate( new CompleterDelegate(m_view));
  CompleterSourceModel *m_sourceModel = new CompleterSourceModel(this);
  CompleterProxyModel *m_proxyModel = new CompleterProxyModel(this);
  m_proxyModel->setSourceModel(m_sourceModel);

  setView(m_view);
  setModel(m_proxyModel);

  connect(this, &QComboBox::currentTextChanged, this, &MyComboBox::showProposalList);
}

我这里树模型的数据结构是父子关系。有了上面的构造函数,当我把我的数据放入模型中后,孩子们被隐藏了,只有父母们可以看到。 为了查看所有项目(儿童),我必须使用 m_view->expandAll() after 我将数据放入模型中。有什么办法可以在构造函数中做到这一点,所以每次我将数据放入模型(无论我的数据是什么)时,所有项目(父母和孩子)都会自动展开?

【问题讨论】:

    标签: qt qtreeview


    【解决方案1】:

    您最好的选择可能是连接到QAbstractItemModel::rowsInserted 信号,以确保项目及时扩展。因此,在设置视图模型后立即使用...

    connect(m_view->model(), &QAbstractItemModel::rowsInserted,
            [this](const QModelIndex &parent, int first, int last)
            {
    
                /*
                 * New rows have been added to parent.  Make sure parent
                 * is fully expanded.
                 */
                m_view->expandRecursively(parent);
            });
    

    编辑:在 cmets (@Patrick Parker) 中指出,如果插入的行本身具有一层或多层后代,则仅调用 m_view->expand(parent) 将不起作用。已更改代码以使用 m_view->expandRecursively(parent)(如 @m7913d 建议的那样)来处理。

    【讨论】:

    • 请注意,QTreeView::expand 已经针对树项已展开的情况进行了优化。所以,这个条件是不需要的。
    • 人们可能更喜欢expandRecursively,而不是expand
    • 它不适用于 qt 5.9.3 ...我在 QStandardItemModel 上调用 appendRow 并带有一个有子项和孙子项的项目。这在 parent=invalid (0,0) 处只给了我一个 rowsInserted 信号。在无效的父对象上调用 expand 然后什么都不做。
    • @PatrickParker 编辑答案以使用 QTreeView::expandRecursively 而不是 QTreeView::expand 。假设我对您的理解正确,这似乎可以解决问题。
    • @G.M.谢谢。不幸的是,这对我没有帮助,因为 expandRecursively 仅在 Qt 5.13 中可用。但是我能够编写自己的递归辅助函数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 2010-12-13
    • 2012-02-11
    • 2017-08-16
    • 1970-01-01
    • 2014-05-17
    相关资源
    最近更新 更多