1

I'm trying to put a MySQL table into a treeView.

Each entry has three values in the database - id, text, parentId. This treeView needs to be editable so I really like the QSqlTableModel approach, as the functionality to save back to database is already built in.

Now, the treeView is showing all entries in the same line, of course, and I need a hierarchy. What would be the best way to build this hierarchy, while maintaining the editing and saving capabilities? (I'm using MySQL.)

mainwindow.h

private: QSqlTableModel* goalModel;

mainwindow.cpp

(this makes a flat table hierarchy. the table is filtered based on which entry is clicked in another table)

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);
    ...

I tried this. It's wrong, but I don't really know why. (the third column contains the parentId value, if the entry has it)

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);
            }
        }
    }
}

All indexes are already made, so no need to make new ones, just assign a parent to all those who have one. How best to do that?

L.Corvus
  • 23
  • 4
  • You want to implement a view model - a proxy between the source table model and the view. – Kuba hasn't forgotten Monica Nov 05 '16 at 02:07
  • Thank you. Do you mean a `QSortFilterProxyModel`? I guess I would need to reimplement `mapToSource()` and `mapFromSource()`. Would that keep the editing and saving capabilities that `QSqlTableModel` gives me? – L.Corvus Nov 05 '16 at 12:11

0 Answers0