PDA

View Full Version : amount of items in QTreeWidget



supergillis
1st August 2008, 21:31
As the title says, is there a way to get the amount of QTreeWidgetItems in a QTreeWidget?

Is there also a way to get a specified item by its location in the QTreeWidget? For example:

QTreeWidget* tree = new QTreeWidget();
QTreeWidgetItem* item = new QTreeWidgetItem();
int index = tree->addTopLevelItem(item);
QTreeWidgetItem* itemAtIndex = tree->getItemAtIndex(index);
if(item == itemAtIndex)
cout << "works!";
int amount = tree->getItemCount();
for(int i = 0; i < amount; i++)
cout << tree->getItemAtIndex(i).text(0).toStdString();

jpn
1st August 2008, 21:43
You can access top level items via QTreeWidget::topLevelItem(int index) and children of particular items via QTreeWidgetItem::child(int index). But there is no way to access arbitrary items in the tree with an "universal" index. However, QTreeWidgetItemIterator might become handy in case of looking for certain items.

supergillis
1st August 2008, 21:50
Thanks for the fast reply.

I found out QWidgetItemIterator already but it was just not I was looking for... I need these functions actually for a music player to go to a random next song. Example:

void MP3::playNextSong()
{
std::cout << "void MP3::playNextSong() called" << std::endl;
timer->stop();
QTreeWidgetItemIterator it(g_main->musicList);
bool found = false;
int random = rand()%10;
while(random == id)
random = rand()%10;
std::cout << "void MP3::playNextSong() rand=" << random << std::endl;
while(*it)
{
QTreeWidgetItem* item = *it;
if(item && item->text(1).toInt() == random)
{
load(item->text(0).toStdString(), random);
play();
found = true;
break;
}
++it;
}
if(!found)
{
std::cout << "void MP3::playNextSong() found=false " << std::endl;
playNextSong();
}
}

Now I'm using "rand()%10" only for testing with 10 items. But I need to know the actual count of the items in the tree, or I would have to manually change the count all the time...

Of course I can also try to make my own extended class and do this:

MyTreeWidget::addTopLevelItem(QTreeWidgetItem* item)
{
this->count++;
QTreeWidget::addTopLevelItem(item);
}

EDIT: I just saw this function too: QTreeWidget::topLevelItemCount (). Is this the function I'm looking for?
EDIT 2: Works now :). But is there a way to hide a column of a QTreeWidget?

jpn
1st August 2008, 22:25
EDIT: I just saw this function too: QTreeWidget::topLevelItemCount (). Is this the function I'm looking for?

Sure, if you have top level items only ie. you don't have hierarchical structure. :)



EDIT 2: Works now :). But is there a way to hide a column of a QTreeWidget?
See QTreeView::setColumnHidden().

supergillis
1st August 2008, 22:38
Great man! Thanks!