一、获取QTreeWidget中的所有可见行的行数
int TreeWidgetFocus::treeCount(QTreeWidget *tree, QTreeWidgetItem *parent)
{
Q_ASSERT(tree != NULL);
int count = 0;
if (parent == 0) {
int topCount = tree->topLevelItemCount();
for (int i = 0; i < topCount; i++) {
QTreeWidgetItem *item = tree->topLevelItem(i);
if (item->isExpanded()) {
count += treeCount(tree, item);
}
}
count += topCount;
} else {
int childCount = parent->childCount();
for (int i = 0; i < childCount; i++) {
QTreeWidgetItem *item = parent->child(i);
if (item->isExpanded()) {
count += treeCount(tree, item);
}
}
count += childCount;
}
return count;
}
二、获取当前选中行的行号
int TreeWidgetFocus::curRow(QTreeWidget *tree, QTreeWidgetItem *parent, QTreeWidgetItem *curItem)
{
Q_ASSERT(tree != NULL);
Q_ASSERT(curItem != NULL);
int count = 0;
if (parent == 0) {
int topCount = tree->topLevelItemCount();
for (int i = 0; i < topCount; i++) {
if(findedCurRow)
{
break;
}
count ++;
QTreeWidgetItem *item = tree->topLevelItem(i);
if(item == curItem)
{
break;
}
if (item->isExpanded()) {
count += curRow(tree, item, curItem);
}
}
} else {
int childCount = parent->childCount();
for (int i = 0; i < childCount; i++) {
if(findedCurRow)
{
break;
}
count ++;
QTreeWidgetItem *item = parent->child(i);
if(item == curItem)
{
findedCurRow = true;
break;
}
if (item->isExpanded()) {
count += curRow(tree, item, curItem);
}
}
}
return count;
}
其中,findedCurRow是类成员变量。