2

QStyledItemDelegate在我的模型上为特定领域设置一个,并QComboBoxQStyledItemDelegate::createEditor

QComboBox* createEditor(QWidget* parent)
{
    QComboBox* cb = new QComboBox(parent);

    cb->addItem("UNDEFINED");
    cb->addItem("TEST");
    cb->addItem("OSE");
    cb->addItem("TSE");

    return cb;
}

void setEditorData(QWidget* editor, const QModelIndex& index)
{
    QComboBox* cb = qobject_cast<QComboBox*>(editor);
    if (!cb)
        throw std::logic_error("editor is not a combo box");

    QString value = index.data(Qt::EditRole).toString();
    int idx = cb->findText(value);
    if (idx >= 0)
        cb->setCurrentIndex(idx);

    cb->showPopup();
}

这工作正常,当我选择有问题的字段时,我会看到一个组合框。

组合框打开

当我从下拉列表中选择一个选项时,组合框会关闭,并且该项目旁边会显示一个下拉图标:

选择

此时我希望QStyledItemDelegate::setModelData调用该函数,以便在列表中选择一个项目将数据提交给模型。

但是,我需要先按Enter提交数据(下拉图标消失)

坚定的

void setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index)
{
    QComboBox* cb = qobject_cast<QComboBox*>(editor);
    if (!cb)
        throw std::logic_error("editor is not a combo box");

    model->setData(index, cb->currentText(), Qt::EditRole);
}

问题:

当用户选择列表中的一个项目并且组合框列表关闭时,我如何配置我QComboBox自动Enter提交数据,而不是需要额外按下?

4

1 回答 1

3

您必须发出信号commitData,并且closeEditor在选择项目时,如以下示例所示:

#include <QApplication>
#include <QStandardItemModel>
#include <QListView>
#include <QStyledItemDelegate>
#include <QComboBox>

class ComboBoxDelegate: public QStyledItemDelegate{
public:
    using QStyledItemDelegate::QStyledItemDelegate;
    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const{
        Q_UNUSED(option)
        Q_UNUSED(index)

        QComboBox* editor = new QComboBox(parent);
        connect(editor,  QOverload<int>::of(&QComboBox::activated),
                this, &ComboBoxDelegate::commitAndCloseEditor);
        editor->addItems({"UNDEFINED", "TEST", "OSE", "TSE"});

        return editor;
    }
    void setEditorData(QWidget *editor, const QModelIndex &index) const{
        QComboBox* cb = qobject_cast<QComboBox*>(editor);
        if (!cb)
            throw std::logic_error("editor is not a combo box");

        QString value = index.data(Qt::EditRole).toString();
        int idx = cb->findText(value);
        if (idx >= 0)
            cb->setCurrentIndex(idx);
        cb->showPopup();
    }
private:
    void commitAndCloseEditor(){
        QComboBox *editor = qobject_cast<QComboBox *>(sender());
        emit commitData(editor);
        emit closeEditor(editor);
    }
};


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QListView view;

    QStandardItemModel model;

    for(int i=0; i<10; i++){
        model.appendRow(new QStandardItem("UNDEFINED"));
    }
    view.setItemDelegate(new ComboBoxDelegate(&view));
    view.setModel(&model);
    view.show();
    return a.exec();
}
于 2018-06-12T21:24:24.823 回答