前言
最近在学习QT5的QTableView,想要在QTableView上做成下拉框的形式,查找资料总结有两种实现方式。
一、基于setIndexWidget函数
void QAbstractItemView::setIndexWidget(const QModelIndex &index, QWidget *widget)
index 索引,这里为QTableView的索引
widget 小部件,可以是QComboBox、QLineEdit
举个例子,代码如下:
QComboBox* box = new QComboBox();、
QStringList list;
list << "id1" << "id2";
cob->addItems(list);
view->setIndexWidget(index, cob);
setIndexWidget函数,小部件会浮在Item上面,会一直显示小部件。
二、基于QItemDelegate
MyItemDelegate.h 代码如下:
class MyItemDelegate : public QItemDelegate
{
public:
MyItemDelegate ();
MyItemDelegate (QStringList list, QItemDelegate *parent = nullptr);
// 创建编辑器
virtual QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
// 设置编辑器数据
virtual void setEditorData(QWidget *editor, const QModelIndex &index) const override;
// 更新编辑器集合属性
virtual void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
// 设置模型数据
virtual void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override;
private:
// 存储QComBoBox的数据
QStringList m_comboBoxList;
};
MyItemDelegate.cpp 代码如下:
MyItemDelegate::MyItemDelegate()
{
}
MyItemDelegate::MyItemDelegate(QStringList list, QItemDelegate *parent) : QItemDelegate(parent)
{
m_comboBoxList = list;
}
// 创建编辑器
QWidget *MyItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const{
Q_UNUSED(option);
Q_UNUSED(index);
// 创建自己需要的控件进行返回
QComboBox *editor = new QComboBox(parent);
return editor;
}
// 设置编辑器数据
void MyItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const {
Q_UNUSED(index);
// 将参数editor转换为对应创建的控件,再进行数据初始设置就行
QComboBox *cob = static_cast<QComboBox *>(editor);
cob->addItems(m_comboBoxList);
}
// 更新编辑器集合属性
void MyItemDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const {
Q_UNUSED(index);
// 将编辑器设置为矩形属性
editor->setGeometry(option.rect);
}
// 设置模型数据
void MyItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const {
// 类型转换
QComboBox *comboBox = static_cast<QComboBox *>(editor);
// 模型(单元格)显示的数据
model->setData(index, comboBox->currentText());
}
具体使用方法,代码如下:
int column = 1;
int row = 1;
QStringList list;
list << "id1" << "id2" << "id3";
// 创建时指定数据传入
MyItemDelegate* m_cBoxDelegate = new MyItemDelegate(list);
QTableView *tableView = new QTableView;
// 将某一列单元格设置为该委托
tableView->setItemDelegateForColumn(column,m_cBoxDelegate);
// 将某一行单元格设置为该委托
tableView->setItemDelegateForRow(row,m_cBoxDelegate);
// 将全部单元格设置为该委托
tableView->setItemDelegate(m_cBoxDelegate);
使用代理QItemDelegate方法,需要双击,才会显示小部件。
总结
以上就是QtabelView窗口小部件的内容,主要介绍了两种实现小部件的方法,两种方法各有千秋,需要根据需求进行选择,个人偏向第二种。