我希望您能在QTableView中设置一个可编辑的列。目前我尝试了子类化QTableView并重新实现Qt :: ItemFlags flags(const QModelIndex&index) const,子类化QSqlQueryModel并重新实现Qt :: ItemFlags flags(const QModelIndex&index) const,最后是子类化QAbstractItemView,但这导致编译器错误的出现。
QTableView子类化:
为什么所有这些方法都没能实现我想要的目标?
QTableView子类化:
#include "exqtableview.h"
ExQTableView::ExQTableView(QWidget *parent) :
QTableView(parent)
{
}
Qt::ItemFlags ExQTableView::flags(const QModelIndex & index) const
{
if (!index.isValid())
return Qt::ItemIsEnabled;
if (index.column() == 2)
return index.parent().flags() & ~Qt::ItemIsEditable;
}
子类化QSqlQueryModel
#include "exsqlquerymodel.h"
ExSqlQueryModel::ExSqlQueryModel(QObject *parent) :
QSqlQueryModel(parent)
{
}
Qt::ItemFlags ExSqlQueryModel::flags( const QModelIndex &index) const
{
Qt::ItemFlags flags = QSqlQueryModel::flags(index);
if (index.column() == 2 )
flags &= ~Qt::ItemIsEditable;
return flags;
}
继承 QAbstractItemView
#include "exitemdelegate.h"
#include <QTableWidgetItem>
ExItemDelegate::ExItemDelegate(QObject *parent) :
QItemDelegate(parent)
{
}
QWidget *ExItemDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem & ,
const QModelIndex & index ) const
{
QTableWidgetItem *item = new QTableWidgetItem;
return item;
}
void ExItemDelegate::setEditorData(QWidget *editor,
const QModelIndex &index) const
{
float value = index.model()->data(index, Qt::EditRole).toFloat();
QTableWidgetItem *cell = static_cast<QTableWidgetItem*>(editor);
cell->setData(0, value);
}
void ExItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const
{
QTableWidgetItem *cell = static_cast<QTableWidgetItem*>(editor);
float value = cell->data(Qt::DisplayRole);
model->setData(index, value, Qt::EditRole);
}
void ExItemDelegate::updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option, const QModelIndex &) const
{
editor->setGeometry(option.rect);
}
为什么所有这些方法都没能实现我想要的目标?