如何在列表视图中显示每个项目的所有QComboBox?

如何在列表视图中显示每个项目的所有QComboBox?

问题描述:

我已经设置了一个QItemDelegate,它有一个QComboBox的编辑器。我已经把这个项目委托给我的列表视图。如何在列表视图中显示每个项目的所有QComboBox?

目前,只有当我点击列表视图中的某个项目时,组合框才会显示该特定项目。我把它做这个点击:

ui->suggestedListView->setEditTriggers(QAbstractItemView::AllEditTriggers); 

我希望的是,在一个列表视图中的每一项显示其组合框,而不是使得它的用户双击就能看到它。

这里是我的项目代表:

#include "include/gui/comboboxdelegate.h" 

ComboBoxDelegate::ComboBoxDelegate(QObject *parent) 
    : QItemDelegate(parent) 
{ 
} 

QWidget *ComboBoxDelegate::createEditor(QWidget *parent, 
     const QStyleOptionViewItem &, 
     const QModelIndex &) const 
{ 
    QComboBox *editor = new QComboBox(parent); 
    editor->addItem("Address"); 
    editor->addItem("Address2"); 
    editor->addItem("City"); 
    editor->addItem("Country"); 
    editor->addItem("Date of Birth"); 
    editor->addItem("Email"); 
    editor->addItem("Fax Number"); 
    editor->addItem("First Name"); 
    editor->addItem("Gender"); 
    editor->addItem("Last Activity Timestamp"); 
    editor->addItem("Last Name"); 
    editor->addItem("Middle Name"); 
    editor->addItem("Mobile Number"); 
    editor->addItem("Phone Number"); 
    editor->addItem("Reference Code"); 
    editor->addItem("Signup Category"); 
    editor->addItem("IP Address"); 
    editor->addItem("Signup Timestamp"); 
    editor->addItem("Signup URL"); 
    editor->addItem("State/Province/Region"); 
    editor->addItem("Zip/Postal Code"); 
    editor->addItem("Discard"); 

    return editor; 
} 

void ComboBoxDelegate::setEditorData(QWidget *editor, 
             const QModelIndex &index) const 
{ 
    QString value = index.model()->data(index, Qt::EditRole).toString(); 

    QComboBox *cBox = static_cast<QComboBox *>(editor); 
    cBox->setCurrentIndex(cBox->findText(value)); 
} 

void ComboBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, 
            const QModelIndex &index) const 
{ 
    QComboBox *cBox = static_cast<QComboBox *>(editor); 
    QString value = cBox->currentText(); 

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

void ComboBoxDelegate::updateEditorGeometry(QWidget *editor, 
     const QStyleOptionViewItem &option, const QModelIndex &) const 
{ 
    editor->setGeometry(option.rect); 
} 

这里是我如何设置我的QList观点:

ui->suggestedListView->setItemDelegate(new ComboBoxDelegate(ui->suggestedListView)); 
ui->suggestedListView->setEditTriggers(QAbstractItemView::AllEditTriggers); 

这甚至可能吗?如果不是,那可能是另一种解决方案?

  1. 通过QStyle::drawControl
  2. 手柄只需点击一下你在明年的方式委托(::editorEvent)画在你的委托组合框:创建一个编辑器(QComboBox),并迫使它显示下拉列表。

P.S.使用QStyledItemDelegate而不是QItemDelegate

+0

这使我朝着正确的方向前进。谢谢!我使用完全相同的功能,除了将QItemDelegate更改为QStyledItemDelegate并添加了paint()函数。 – 2015-02-24 16:56:01