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

时间:2015-02-23 20:55:28

标签: c++ qt

我已经设置了一个QItemDelegate,它有一个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 个答案:

答案 0 :(得分:2)

  1. 通过QStyle::drawControl
  2. 在您的代表中绘制一个组合框
  3. 以下一种方式处理您的委托(::editorEvent)中的单击:创建一个编辑器(QComboBox)并强制它显示下拉列表。
  4. P.S。使用QStyledItemDelegate代替QItemDelegate