我继承了如上所述的QAbstractTableModel
here
。我已将setData编码为:
bool TableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if(role == Qt::EditRole)
{
Data[index.row()][index.column()]= value.toString();
qDebug()<<Data[index.row()][index.column()];//to check entered data passed or not
}
return true;
}
Qt::ItemFlags TableModel::flags(const QModelIndex &index) const
{
return Qt::ItemIsEditable|Qt::ItemIsEnabled|Qt::ItemIsSelectable;
}
在主窗口中,我将模型和视图连接为:
connect(model,SIGNAL(dataChanged(QModelIndex,QModelIndex)),ui->tableView,SLOT(dataChanged(QModelIndex,QModelIndex)));
但是在编辑之后,在视图中不更新数据。我尝试从setData函数发出dataChanged信号,但它不起作用。我在代码中遗漏了什么?
数据功能:
QVariant TableModel::data(const QModelIndex &index, int role) const
{
switch(role)
{
case Qt::DisplayRole:
if(index.column()==0)
{
return index.row()+1;
}
break;
case Qt::DecorationRole:
if(index.column()==1)
{
QColor c;
c.setRgb(0,200,200,200);
return c;
}
break;
case Qt::ToolTipRole:
if(index.column()==2)
{
return "colum 3";
}
break;
case Qt::StatusTipRole:
return "Not editable";
break;
case Qt::FontRole:
{
QFont f;
f.setFamily("Times");
f.setBold(true);
f.setKerning(true);
return f;
}
break;
case Qt::TextAlignmentRole:
{
return Qt::AlignCenter;
}
break;
case Qt::BackgroundRole:
if(index.column()==2)
{
QColor b;
b.setRgb(100,100,250,200);
return b;
}
break;
case Qt::ForegroundRole:
{
QColor b;
b.setRgb(0,100,250,200);
return b;
}
case Qt::CheckStateRole:
if(index.column()==3)
{
if(index.row()==1) return true;
return false;
}
break;
case Qt::InitialSortOrderRole:
return Qt::AscendingOrder;// use not clear
}
return QVariant();
}