在Qtreeview中从父母那里得到孩子

时间:2012-09-28 07:55:30

标签: c++ qt indexing parent-child qtreeview

我正在使用QTreeView和QFileSystemModel开发Qt应用程序。 我能够将父母的孩子送到一个级别,但我无法得到父母的孩子。 例如:

C是B的孩子,

B是A的孩子

我能够让B成为A的孩子,但我也希望C作为A的孩子。 我想要这样的C-> B-> A。

有人可以就此提出一些意见并帮助我。 提前谢谢。

//QItemSelectionModel *sel = ui->dir_tree->selectionModel();
QStringList strings = extractStringsFromModel(ui->dir_tree->model(), ui->dir_tree->rootIndex());

QFileSystemModel* model = (QFileSystemModel*)ui->dir_tree->model();
QModelIndexList indexlist = ui->dir_tree->selectionModel()->selectedIndexes();
QVariant data;

//QList<QModelIndex> modelindex(indexlist);

int row = -1;

for(int i=0; i<indexlist.size();i=i+4)
{
    QModelIndex mi=indexlist.at(i);
    info1 = model->fileInfo(mi);
    QString childstr = info1.filePath();
    QString childname = info1.fileName();

    QModelIndex mi2= indexlist.at(i).parent();
    info = model->fileInfo(mi2);
    QString parentstr = info.filePath();
    QString parentname = info.fileName();
    QStringList childlist;
    for(int j=0;j<model->rowCount(indexlist.at(i));j++)
    {
        QModelIndex mi3 = indexlist.at(i).child(j, 0);
        info2 = model->fileInfo(mi3);
        QString childrenstr = info2.filePath();
        childlist << childrenstr;
        qDebug()<<"parents' children"<<childrenstr<<j;
    }
}

3 个答案:

答案 0 :(得分:1)

让所有孩子获得广度优先:

QModelIndexList children;

//  Get top-level first.
for ( int i = 0; i < model->rowCount(); ++i ) {
    children << model->index( i, 0 );  //  Use whatever column you are interested in.
}

// Now descend through the generations.
for ( int i = 0; i < children.size(); ++i ) {
    for ( int j = 0; j < model->rowCount( children[i] ); ++j ) {
        children << children[i].child( j, 0 );
    }
}

让所有父母离开孩子:

QModelIndexList parents;
parents << child.parent();
while ( parents.last().isValid() ) {
    parents << parents.last().parent();
}

请注意,我没有尝试过这些样品!

答案 1 :(得分:1)

我喜欢使用递归来做这种事情:

void MyTreeView::GetAllChildren(QModelIndex &index, QModelIndexList &indicies)
{
    indicies.push_back(index);
    for (int i = 0; i != model()->rowCount(index); ++i)
        GetAllChildren(index.child(i,0), indicies);
}

用法(从树视图中的某个位置):

QModelIndexList list;
GetAllChildren(model()->index(0,0), list);

答案 2 :(得分:0)

//Delete
    QList<QTreeWidgetItem *> selected = ui->twg->selectedItems();
    QTreeWidgetItem *item = selected.first();
    QTreeWidgetItem *parent = item->parent();
    if(parent) {
        int index = parent->indexOfChild(item);
        delete parent->takeChild(index);
    }

//Add
QList<QTreeWidgetItem *> selected = ui->twg->selectedItems();
QTreeWidgetItem *item = selected.first();
QTreeWidgetItem *parent = item->parent();
if(parent) {
    QTreeWidgetItem *tmp = new QTreeWidgetItem(parent);
    tmp->setText(0, "Dude");
    parent->addChild(tmp);
}