简体   繁体   English

在PyQt中记住QTreeWidget的Scroll值

[英]Remembering Scroll value of a QTreeWidget in PyQt

I have a QTreeWidget that reads data from an XML file. 我有一个QTreeWidget,它从XML文件读取数据。 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. 如果在任何时候更改了XML文件(认为许多用户一次访问了该文件),则将QTreeWidget重新填充为clear并重新读取。 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. 如果用户位于QTreeWidget顶部以外的任何位置(按滚动方式),并且在清除后重新填充,默认情况下会将他们带回顶部。

Question is, can one get the 'scroll value' of a QTreeWidget and then go back to that same value after a repopulation? 问题是,是否可以获取QTreeWidget的“滚动值”,然后在重新填充后返回到相同的值? 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. 您可能会在项目上存储一些其他自定义值以再次找到它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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