class Xx : public QWidget
{
Q_OBJECT struct ItemState{
ItemState();
int _id;
bool _isExpend;
}; public:
Xx(QWidget *parent = 0);
~Xx(); void updateTree(); private:
void saveItemState();
void popItemState();
const ItemState itemState(int id); private:
Ui::Xx ui;
QVector<ItemState> _itemState;
};

  

Xx::ItemState::ItemState(){
_isExpend = true;
_id = -1;
} void Xx::updateTree(){
saveItemState();//更新前保存展开状态 ui.treeWidget->clear(); QTreeWidgetItem *rootItem = new QTreeWidgetItem(ui.treeWidget);
rootItem->setText(0, "xx");
rootItem->setData(0, Qt::UserRole,QString::number(id));
rootItem->setExpanded(true); popItemState();//恢复展开状态
} void Xx::saveItemState(){
_itemState.clear();
QTreeWidgetItemIterator it(ui.treeWidget);
while (*it){
ItemState itemState;
itemState._id = (*it)->data(0, Qt::UserRole).toInt();
itemState._isExpend = (*it)->isExpanded();
_itemState.push_back(itemState);
++it;
}
} void Xx::popItemState(){
QTreeWidgetItemIterator it(ui.treeWidget);
QTreeWidgetItem *curItem(*it);
while (*it){
ItemState state = itemState((*it)->data(0, Qt::UserRole).toInt());
if(state.id != -1){
(*it)->setExpanded(state._isExpend);
}
++it;
}
} const ShowCtrlWgt::ItemState ShowCtrlWgt::itemState(int id){
ItemState state;
for each (ItemState var in _itemState){
if (var._id == id)
return var;
}
return state;
}

  原文来自微信公众号"程序员成长日志",已经工作的程序员朋友可以关注下,分享日常工作中解决的问题即可赚取稿费,大家一起成长~
QTreeWidget更新后保存节点的展开状态-LMLPHP

05-20 20:13