C++ 调整QTreeView的QSqlTableModel
我正在尝试将MySQL表放入C++ 调整QTreeView的QSqlTableModel,c++,mysql,qt,treeview,qsqltablemodel,C++,Mysql,Qt,Treeview,Qsqltablemodel,我正在尝试将MySQL表放入treeView 每个条目在数据库中有三个值-id,text,parentId。 这个treeView需要编辑,因此我非常喜欢QSqlTableModel方法,因为保存回数据库的功能已经内置 现在,treeView显示了同一行中的所有条目,当然,我需要一个层次结构。在维护编辑和保存功能的同时,构建此层次结构的最佳方法是什么? (我正在使用MySQL。) main window.h private:QSqlTableModel*goalModel main window
treeView
每个条目在数据库中有三个值-id
,text
,parentId
。
这个treeView
需要编辑,因此我非常喜欢QSqlTableModel
方法,因为保存回数据库的功能已经内置
现在,treeView
显示了同一行中的所有条目,当然,我需要一个层次结构。在维护编辑和保存功能的同时,构建此层次结构的最佳方法是什么?
(我正在使用MySQL。)
main window.h
private:QSqlTableModel*goalModel代码>
main window.cpp
(这形成了一个平面表层次结构。该表根据在另一个表中单击的条目进行过滤)
我试过这个。这是错误的,但我真的不知道为什么。(第三列包含parentId值,如果条目中有该值)
for(int row=0;rowrowCount();++row)
{
//如果该条目在parentId列中的值超过0
如果(目标模型->索引(第2行).data().toInt()>0)
{
//获取第2列中的数字
int-parentId;
parentId=goalModel->index(第2行).data().toInt();
QModelIndex newChild=goalModel->index(行,0);
//在列0中查找编号匹配的QModelIndex行
对于(int row=0;rowrowCount();++row)
{
if(goalModel->index(行,0).data().toInt()==parentId)
{
//将此条目设为该条目的子条目
QModelIndex newParent=goalModel->index(行,0);
newChild=goalModel->index(0,0,newParent);
}
}
}
}
所有索引都已创建,因此不需要创建新索引,只需为所有具有索引的索引分配一个父级即可。如何最好地做到这一点?您想实现一个视图模型—源表模型和视图之间的代理。谢谢。你是说一个QSortFilterProxyModel
?我想我需要重新实现mapToSource()
和mapFromSource()
。这会保留QSqlTableModel
提供给我的编辑和保存功能吗?您想实现一个视图模型-源表模型和视图之间的代理。谢谢。你是说一个QSortFilterProxyModel
?我想我需要重新实现mapToSource()
和mapFromSource()
。这会保留QSqlTableModel
提供给我的编辑和保存功能吗?
void MainWindow::on_tableViewGoals_clicked(const QModelIndex &index)
{
goalModel = new QSqlTableModel(this);
goalModel->setTable("goals");
//Gets the id from the clicked entry to use as filter
QString idGoals = index.sibling(row,0).data().toString();
goalModel->setFilter( "id_goals=" + idGoals );
goalModel->setEditStrategy(QSqlTableModel::OnRowChange);
goalModel->select();
ui->treeView->setModel(goalModel);
...
for (int row = 0; row < goalModel->rowCount(); ++row)
{
//if the entry has a value over 0 in the parentId column
if (goalModel->index(row,2).data().toInt() > 0)
{
//get number in column 2
int parentId;
parentId = goalModel->index(row,2).data().toInt();
QModelIndex newChild = goalModel->index(row,0);
//find QModelIndex row with matching number in column 0
for (int row = 0; row < goalModel->rowCount(); ++row)
{
if (goalModel->index(row,0).data().toInt() == parentId )
{
//make this entry that entry's child
QModelIndex newParent = goalModel->index(row,0);
newChild = goalModel->index(0,0,newParent);
}
}
}
}