4

我想通过模型委托QComboBox插入QWidgets(而不是字符串)来自定义 a :

QComboBox *cb = new QComboBox(this);

FeatureModel *featureModel = new FeatureModel(cb);
cb->setModel(featureModel);

ComboBoxItemDelegate *comboBoxItemDelegate = new ComboBoxItemDelegate(cb);
cb->setItemDelegate(comboBoxItemDelegate);

FeatureModel 继承自 QAbstractListModel,ComboBoxItemDelegate 继承自 QStyledItemDelegate。

问题是从未调用过委托方法,因此没有插入我的自定义小部件(我只看到 的字符串FeatureModel)。但是,如果我使用 aQTableView而不是 a QComboBox,它可以正常工作。

有人知道错误在哪里吗?我错过了 QT模型/视图概念的一些重要方面吗?

编辑: 这是我的代表。除了构造函数(当然),没有调用以下方法(控制台上没有输出)。

ComboBoxItemDelegate::ComboBoxItemDelegate(QObject *parent) :
QStyledItemDelegate(parent)
{
    qDebug() << "Constructor ComboBoxItemDelegate";
}

ComboBoxItemDelegate::~ComboBoxItemDelegate()
{
}

QWidget* ComboBoxItemDelegate::createEditor( QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index ) const
{
    qDebug() << "createEditor"; // never called
    QWidget *widget = new QWidget(parent);

    Ui::ComboBoxItem cbi;
    cbi.setupUi(widget);

    cbi.label->setText(index.data().toString());
    widget->show();

    return widget;
}


void ComboBoxItemDelegate::setEditorData ( QWidget *editor, const QModelIndex &index ) const
{
    qDebug() << "setEditorData"; // never called
}


void ComboBoxItemDelegate::setModelData ( QWidget *editor, QAbstractItemModel *model, const QModelIndex &index ) const
{
    qDebug() << "setModelData"; // never called
}
4

1 回答 1

3

我想我找到了问题所在。

首先,确保QComboBox允许编辑中的视图:

cb->view()->setEditTriggers(QAbstractItemView::AllEditTriggers);

我不确定这是否是一个好的做法,但这是我让它发挥作用的唯一方法。editTriggers默认值为QAbstractItemView::NoEditTriggers

其次,确保您的模型允许编辑:

Qt::ItemFlags MyModel::flags(const QModelIndex &index) const
{
    if (!index.isValid())
        return Qt::ItemIsEnabled;

    return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
}

bool MyModel::setData(const QModelIndex &index,
                           const QVariant &value, int role)
{
    if (index.isValid() && role == Qt::EditRole) {
        // Modify data..

        emit dataChanged(index, index);
        return true;
    }
    return false;
}

不过,它有一个问题。第一次看到 时ComboBox,您可以更改当前项目文本,并且不会调用委托方法进行编辑。您必须选择一项,然后才能对其进行编辑。

无论如何,我发现将 aQComboBox用于可编辑项目是违反直觉的。你确定你需要一个QComboBox来完成这个任务吗?

希望能帮助到你

于 2012-11-18T18:39:31.080 回答