简体   繁体   中英

Remembering Scroll value of a QTreeWidget in PyQt

I have a QTreeWidget that reads data from an XML file. If at any point the XML file is changed (think many users accessing said file at one time), the QTreeWidget is repopulated with clear and a re-read. If a user is anywhere but the top of the QTreeWidget, scroll-wise, and it gets repopulated after a clear, they're taken back to the top by default.

Question is, can one get the 'scroll value' of a QTreeWidget and then go back to that same value after a repopulation? If so, how? Thanks in advance!

You could scroll to the actual previous values, like you are asking, but are you sure your results will always be the same size? Those numbers could be meaningless in terms of taking you to the right spot again. But just for reference, you would have to access the scroll bar, take its value, then perform your repopulation, and then scroll that value again:

bar = treeWidget.verticalScrollBar()
yScroll = bar.value()
# repopulate here ...
treeWidget.scrollContentsBy(0, yScroll)

But a more useful approach would be to find the item that is current in view or of interest, then repopulate your tree, and then tell the tree to scroll to that actual item. Then it won't matter where in the tree the item now exists (if the data structure has changed significantly).

First save the current item by some criteria:

item = treeWidget.currentItem() # one way
item = treeWidget.itemAt(centerOfTree) # another way

# either save the text value or whatever the custom 
# identifying value is of your item
text = item.text()

Once you have that data value, be it the text value or some other custom data value, you can repopulate your tree, then look up that item again.

# this is assuming the item is both present, 
# and referencing it by its string value
newItem = treeWidget.findItems(text)[0]
treeWidget.scrollToItem(newItem)

You can modify this to suit your actual type of items. You may be storing some other custom value on the items to find them again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM