PDA

View Full Version : Getting child's ModelIndex while traversing tree



db
22nd October 2007, 14:24
So I now have a QTreeWidget established and a signal connected to a slot that processes updateChecked when an item is checked. Problem I’m having now is that I cn’t figure out how to get a QTreeWidget’s ModelIndex as I’m traversing the tree. I would like to used it to compare it to the one that was just cheked.

There is an indexFromItem() method but it is protected so I can’t use it. Anyone have a suggestion??

See code below

Thanks


void CtreeCU::updateChecked()
{
// get index to item just checked
QModelIndex idx = twMain->currentIndex();
qDebug("internalId: %ld",idx.internalId());

// if item was checked then need to process the rest of the tree
if ( twMain->currentItem()->checkState(0) == Qt::Checked )
{
qDebug("Item is checked");

// save current index in tree
currentCheckedIdx = idx;

// search for other items that are checked and remove them
processTree();

}
else
qDebug("Item is NOT checked");
}


void CtreeCU::processTree()
{
// loop through all branches and nodes of the tree
for ( int i=0; i< twMain->topLevelItemCount(); i++)
{
QTreeWidgetItem *item = twMain->topLevelItem(i);
processItem(item);
}
}


void CtreeCU::processItem(QTreeWidgetItem * parent)
{
// process for each child associated with the top node
// this will recurse to lower children on tree
for (int i=0; i< parent->childCount(); i++)
{
QTreeWidgetItem *child = parent->child(i);

// ****** PROBLEM AREA *************
QModelIndex idx = twMain->indexFromItem(child);
// qDebug("index of child is: %d ",idx.internalId());
// ************************************

// if it is checked that will determine if it is the one to remain
// checked or if it needs its state changed
if ( child->checkState(0) == Qt::Checked )
{
QModelIndex idx = twMain->currentIndex();

if ( currentCheckedIdx.internalId() != idx.internalId() )
{
// testing - uncheck selected item
child->setCheckState(0,Qt::Unchecked);
qDebug("internal indexes DID NOT match");

}
else
{
// print out sample data
QMap<QString,QVariant> nodeData = twMain->currentItem()->data(0, Qt::UserRole).toMap();
qDebug("method: %s",qPrintable(nodeData.value("method").toString()));
}

}
processItem(child);
}
}

marcel
22nd October 2007, 14:47
You either subclass QTreeWidget so you get access to the protected members or change the way you traverse the tree.

You can use the model and the root QModelIndex to traverse it. See QTreeWidget::model() and QTreeWidget::rootIndex(). It think it can be done.