加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – QComboBox不调用Delegate方法

发布时间:2020-12-16 07:33:32 所属栏目:百科 来源:网络整理
导读:我想通过模型和委托插入QWidgets(而不是字符串)来自定义QComboBox: QComboBox *cb = new QComboBox(this);FeatureModel *featureModel = new FeatureModel(cb);cb-setModel(featureModel);ComboBoxItemDelegate *comboBoxItemDelegate = new ComboBoxItemDe
我想通过模型和委托插入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的字符串).
但是,如果我使用QTableView而不是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
}

解决方法

我想我发现了这个问题.

首先,确保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来完成这项任务吗?

希望能帮助到你

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读