10

で使用するためにQComboBoxをに入れようとしています。私は周りを見回していますが、答えが見つかりません。何かアイデアはありますか?QStandardItemQStandardItemModel

4

1 に答える 1

14

QComboBoxaに a を格納しませんQStandardItemModel。次の選択肢があるとします。

あいうえお

a に 2 つの項目を持つリストがありQListView、最初の値は A、2 番目の値は D です。

 QListView* pView = new QListView();
 QStandardItemModel* pModel = new QStandardItemModel();
 pView->setModel(pModel);
 pModel->appendRow(new QStandardItem("A"));
 pModel->appendRow(new QStandardItem("D"));

上で作成したのは、「A」と「D」の値を表示するリスト ウィジェットです。さて、へQComboBox。リスト内の「A」と「D」の値を編集したいと思います。このためには、 を作成する必要がありますQItemDelegate

http://doc.qt.io/qt-4.8/qitemdelegate.htmlを参照してください。

試み:

 class ComboBoxDelegate : public QItemDelegate
 {
    Q_OBJECT

 public:
    ComboBoxDelegate(QObject *parent = 0);

    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
                       const QModelIndex &index) const;

    void setEditorData(QWidget *editor, const QModelIndex &index) const;
    void setModelData(QWidget *editor, QAbstractItemModel *model,
                   const QModelIndex &index) const;

    void updateEditorGeometry(QWidget *editor,
     const QStyleOptionViewItem &option, const QModelIndex &index) const;
};

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

QWidget *ComboBoxDelegate::createEditor(QWidget *parent,
 const QStyleOptionViewItem &/* option */,
 const QModelIndex &/* index */) const
{
   QComboBox *editor = new QComboBox(parent);
   editor->addItem("A");
   editor->addItem("B");
   editor->addItem("C");
   editor->addItem("D");

   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 &/* index */) const
{
   editor->setGeometry(option.rect);
}

そして、それを機能させるためにデリゲートを設定する必要がありますQListView。以下を参照してください。

pView->setItemDelegate(new ComboBoxDelegate(pView));
于 2010-06-28T23:27:15.337 に答える