我使用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()
,将数据放入模型中。有什么方法可以在构造函数中进行操作,因此每次将数据放入模型中(无论我的数据是什么),所有项目(父母和孩子)都会自动扩展?
您的最佳选择可能是连接到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);
});
编辑:在评论(@patrick Parker)中指出,如果插入的行本身具有一个或多个后代,则简单地调用m_view->expand(parent)
将无效。已经更改了使用m_view->expandRecursively(parent)
(按 @M7913D建议)来处理的代码。