自动展开在 qtreeview 中作为委托的 qcombobox

问题描述

我实现了自己的 QTreeModel,在第一列中,我使用自定义委托,即 QComboBox,其中会自动完成一些字符串。 委托是通过使用创建的 QWidget* createEditor(QWidget* parent,const qstyleOptionViewItem& option,const QModelIndex& index); 方法。 此外,仅在向某些树模型项添加新行时才创建委托。 我的问题是,在将新项目添加到树后,是否以及如何在创建的 QComboBox 编辑器中自动扩展项目列表以供选择?

解决方法

要进入编辑模式,您可以使用:

void QAbstractItemView::edit(const QModelIndex &index)

组合框将显示,但不会打开。为此,您可以覆盖 QStyledItemDelegate::setEditorData() 并在函数末尾调用 combobox->showPopup();

void setEditorData(QWidget *editor,const QModelIndex &index) const
{
    // check correct index for combobox

    QComboBox *combobox = qobject_cast<QComboBox *>(editor);
    combobox->setCurrentText(index.data(Qt::EditRole).toString());
    combobox->showPopup();
}