本小节属于《QTreeView使用代理实现表项编辑、定制显示控件》:系列教程之八的子章节。
由于本章节内容较多,放在一起可能大家看起来比较费劲,所以进行了拆分,大家可以从这里《QTreeView使用系列教程目录》找到其他的小节内容。
接下来开始讲解,QTreeView中嵌入QComboBox实现选择数据。
从委托类QItemDelegate继承,
createEditor()创建Editor并返回,
setEditorData()用于初始化Editor数据,
setModelData()用于Editor修改数据后写回model,
updateEditorGeometry()用于设置Editor位置。
class ComboBoxDelegate : public QItemDelegate
{
Q_OBJECT
public:
ComboBoxDelegate(QObject *parent = nullptr)
: QItemDelegate(parent) { }
void setItems(const QStringList &texts) { _texts = texts; }
public:
QWidget *createEditor(QWidget *parent,
const QStyleOptionViewItem &option,
const QModelIndex &index) const override
{
QComboBox *editor = new QComboBox(parent);
editor->addItems(_texts);
return editor;
}
void setEditorData(QWidget *editor, const QModelIndex &index) const override
{
QString text = index.model()->data(index, Qt::EditRole).toString();
QComboBox *comboBox = static_cast<QComboBox*>(editor);
int tindex = comboBox->findText(text);
comboBox->setCurrentIndex(tindex);
}
void setModelData(QWidget *editor,
QAbstractItemModel *model,
const QModelIndex &index) const override
{
QComboBox *comboBox = static_cast<QComboBox*>(editor);
QString text = comboBox->currentText();
model->setData(index, text, Qt::EditRole);
}
void updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option,
const QModelIndex &index) const override
{
editor->setGeometry(option.rect);
}
private:
QStringList _texts;
};
给第3列指定委托,那么第3列使用QComboBox修改数据。
ComboBoxDelegate* comboBox = new ComboBoxDelegate(ui->treeView);
comboBox->setItems(QStringList()<<"支出"<<"收入");
ui->treeView->setItemDelegateForColumn(3, comboBox);
效果:
若对你有帮助,欢迎点赞、收藏、评论,你的支持就是我的最大动力!!!
同时,阿超为大家准备了丰富的学习资料,欢迎关注公众号“超哥学编程”,即可领取。
本文涉及工程代码,公众号回复:34EditorDelegate,即可下载。