我正在尝试从模型中的TableView
插入一些数据,但我做错了,因为没有插入数据。该表将使用列和行进行更新。
所以我有GraphicsView
我正在绘制一些自定义GraphicsItems
。每次将新项目添加到场景时,模型应该更新并向我的TableView
发送信号以在其中插入数据。
这里我在添加新项目时更新模型:
Clothoid *temp = new Clothoid(); temp->setStartPoint(p1); temp->setEndPoint(p2); clothoids.append(temp); scene->addItem(temp); model.setColumnCount(3); model.setRowCount(clothoids.size()); QModelIndex index = model.index(clothoids.size(), 1, QModelIndex()); model.setData(index, clothoids.last()->startCurvature); index = model.index(clothoids.size(), 2, QModelIndex()); model.setData(index, clothoids.last()->endCurvature); index = model.index(clothoids.size(), 3, QModelIndex()); model.setData(index, clothoids.last()->clothoidLength); emit clothoidAdded(&model);
Clothoids是我自定义graphicsItems的列表:
QList < Clothoid *> clothoids;
信号连接到主窗口中的插槽:
ui->setupUi(this); SpinBoxDelegate delegate; ui->clothoidTable->setItemDelegate(&delegate); connect(ui->graphicsView, SIGNAL(clothoidAdded(QStandardItemModel*)), ui->clothoidTable, SLOT(onClothoidAdded(QStandardItemModel*)));
插槽位于:
void TableViewList::onClothoidAdded(QStandardItemModel *model) { setModel(model); }
我做错了什么?
答案 0 :(得分:1)
您不希望直接调用setData()。以下是您需要采取的几个关键步骤:
您的模型应该包含Clothoid
指针的容器(可能是QList)(无论是否负责释放资源)。容器中的索引应直接映射到它在视图中占用的行。
您的data()
和setData()
需要正确实施,以便模型知道给定行的每个单元格中的Clothoid信息。他们应该在代表列号的switch()
上有enum
个语句,如下所示:
// in data() after the usual error checking, etc
if(role == Qt::DisplayRole)
{
Clothoid* cloth = myListOfClothoids.at(index.row());
switch(index.column())
{
// This enum is defined in the header for the Clothoid class
// and represents the COLUMN NUMBER in which to show the data
case Clothoid::START:
return cloth->startCurvature; // these probably shouldn't be public members btw
case Clothoid::END:
return cloth->endCurvature;
case Clothoid::LENGTH:
return cloth->clothoidLength;
}
}
// in setData()
if(role == Qt::DisplayRole)
{
Clothoid* cloth = myListOfClothoids.at(index.row());
switch(index.column())
{
case Clothoid::START:
cloth->startCurvature = variant.toWhatever();
break;
case Clothoid::END:
cloth->endCurvature = variant.toWhateverElse();
break;
case Clothoid::LENGTH:
cloth->clothoidLength = variant.toYetSomethingElse();
break;
default:
return false;
}
emit dataChanged(index,index);
return true;
}
addClothoid()
功能。在此功能中,您需要执行以下操作:int rowIndexFirst = 0; // insert into first row
int rowIndexLast = rowIndexFirst; // only inserting one row/Clothoid
beginInsertRows(QModelIndex(), rowIndexFirst, rowIndexLast);
myListOfClothoids.prepend(newClothoidPtr); // insert clothoid into first index, as well
endInsertRows(); // begin and end take care of signalling the view for you!
我真的建议这样做。是的,它在很大程度上需要重构,但它值得,相信我。
希望这有帮助。