c – QComboBox不调用Delegate方法
我想通过模型和委托插入QWidgets(而不是字符串)来自定义QComboBox:
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的字符串). 有人知道错误在哪里吗? 编辑: 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 } 解决方法
我想我发现了这个问题.
首先,确保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时,您可以更改当前项目文本,并且不会调用委托方法进行编辑.您必须选择一个项目,然后您才能编辑它. 无论如何,我发现使用QComboBox进行可编辑的项目是违反直觉的.你确定你需要一个QComboBox来完成这项任务吗? 希望能帮助到你 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |