我继承了这里描述的 QAbstractTableModel 。我已将 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();
}