第三步,将“性别”列数据的代理(编辑器)由默认的单行文本编辑框(QLineEdit)替换为组合框(QComboBox)。
C:\Users\Minwei\Projects\Qt\Table\comboboxdelegate.h:
xxxxxxxxxx
231
2
3
4
5
6
7class ComboBoxDelegate : public QStyledItemDelegate
8{
9public:
10 ComboBoxDelegate();
11
12protected:
13 QWidget* createEditor(QWidget* parent,
14 QStyleOptionViewItem const& option, QModelIndex const& index) const;
15 void setEditorData(QWidget* editor,
16 QModelIndex const& index) const;
17 void setModelData(QWidget* editor,
18 QAbstractItemModel* model, QModelIndex const& index) const;
19 void updateEditorGeometry(QWidget* editor,
20 QStyleOptionViewItem const& option, QModelIndex const& index) const;
21};
22
23// COMBOBOXDELEGATE_H
C:\Users\Minwei\Projects\Qt\Table\comboboxdelegate.cpp:
xxxxxxxxxx
401
2
3ComboBoxDelegate::ComboBoxDelegate()
4{
5}
6
7QWidget* ComboBoxDelegate::createEditor(QWidget* parent,
8 QStyleOptionViewItem const& option, QModelIndex const& index) const
9{
10 Q_UNUSED(option)
11 Q_UNUSED(index)
12
13 QComboBox* editor = new QComboBox(parent);
14 editor->addItem("男");
15 editor->addItem("女");
16
17 return editor;
18}
19
20void ComboBoxDelegate::setEditorData(QWidget* editor,
21 QModelIndex const& index) const
22{
23 static_cast<QComboBox*>(editor)->setCurrentText(
24 index.model()->data(index, Qt::EditRole).toString());
25}
26
27void ComboBoxDelegate::setModelData(QWidget* editor,
28 QAbstractItemModel* model, QModelIndex const& index) const
29{
30 model->setData(index,
31 static_cast<QComboBox*>(editor)->currentText(), Qt::EditRole);
32}
33
34void ComboBoxDelegate::updateEditorGeometry(QWidget* editor,
35 QStyleOptionViewItem const& option, QModelIndex const& index) const
36{
37 Q_UNUSED(index)
38
39 editor->setGeometry(option.rect);
40}
C:\Users\Minwei\Projects\Qt\Table\tablewindow.cpp:
xxxxxxxxxx
121...
2
3...
4TableWindow::TableWindow(QWidget *parent)
5 : QMainWindow(parent)
6 ...
7{
8 ...
9 ui->m_table->setItemDelegateForColumn(3, new ComboBoxDelegate);
10 ...
11}
12...
运行效果如图所示: