假设您了解 Qt 的模型/视图系统,并且知道您应该使用 View 来可视化您的数据模型,那么您要进一步实现的是 delegate ,它可以为每个字段提供除文本输入之外的额外界面。
根据这个tutorial,你应该这样做:
继承 QStyledItemDelegate ,创建自己的委托类,例如 MyDelegate
class MyDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
enum FIELDS
{
COL_FIELD1,
};
explicit MyDelegate(QObject *parent = nullptr);
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
const QModelIndex &index) const Q_DECL_OVERRIDE;
void setEditorData(QWidget *editor, const QModelIndex &index) const Q_DECL_OVERRIDE;
void setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const Q_DECL_OVERRIDE;
void updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;
};
实现这些功能
-
createEditor,定义为用户提供什么样的小部件来执行编辑任务
-
setEditorData,将数据从DataModel转换为widget
-
setModelData,将数据从Widget转换为DataModel
-
updateEditorGeometry,定义在字段中查找的小部件。
在以下代码中,我试图找出您需要提供 field1 的选项。
#include "mydelegate.h"
MyDelegate::MyDelegate(QObject *parent) : QStyledItemDelegate(parent)
{
}
QWidget* MyDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QComboBox* __comboBox = new QComboBox(parent);
if(index.column()==COL_FIELD1)
{
__comboBox->addItem("none");
__comboBox->addItem("option");
__comboBox->addItem("number");
}
else
{
//! according to your need...
}
return __comboBox;
}
void MyDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
QComboBox* __comboBox = qobject_cast<QComboBox*>(editor);
if(index.column()==COL_FIELD1)
{
__comboBox->setCurrentText(index.model()->data(index).toString());
}
}
void MyDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
QComboBox* __comboBox = qobject_cast<QComboBox*>(editor);
model->setData(index,QVariant::fromValue(__comboBox->currentText()));
}
void MyDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
editor->setGeometry(option.rect);
}
实例化 MyDelegate ,附加到您的视图
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//! prepare a demo model
QStringListModel *model = new QStringListModel();
QStringList list;
list << "a" << "b" << "c";
model->setStringList(list);
//! attach a MyDelegate for Row1
ui->tableView->setModel(model);
ui->tableView->setItemDelegateForRow(0,new MyDelegate(this));
}
MainWindow::~MainWindow()
{
delete ui;
}
演示效果如下:
刚刚尝试更改 MyDelegate 的实现内容以获得您需要的效果(例如 spinBox 或 Field2 的不同选项),玩得开心!