程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

PyQt:使用QDataStream保存本机QTreeWidgets

发布于2019-12-04 23:49     阅读(786)     评论(0)     点赞(29)     收藏(4)


我最近花了一些时间研究如何在PyQt中将QDataStream与QTreeWidget一起使用。我从未找到具体的示例来执行此操作,而且QDataStream的pyqt文档似乎总体上很少。因此,我想在这里将问题作为面包屑线索发布,以防其他人需要提示。我会稍等一下,以防有人想进来一枪,然后我会尽力而为。

问题是:在PyQt中,如何使用QDataStream将QTreeWidgetItems作为本地QT对象保存到文件,然后读回文件以完全还原保存的树结构?

埃里克


解决方案


我将继续展示我使用的方法。希望我在知道如何解决自己的问题方面没有不公平的优势:-)

如果有人对此有更清洁的了解或更喜欢python,请随时关注。谢谢!

import sys,os.path
from PyQt4 import QtGui, QtCore

class TreeExperiment(QtGui.QWidget):
    def __init__(self,parent=None):
        QtGui.QWidget.__init__(self,parent)

        self.tree=QtGui.QTreeWidget(self)                # 
        self.tree.setObjectName("treeWidget")            # 
        self.add_button=QtGui.QPushButton("Add", self)   # Initialize a simple
        self.save_button=QtGui.QPushButton("Save", self) # form containing a  
        gridlayout = QtGui.QGridLayout(self)             # treeWidget, an     
        gridlayout.addWidget(self.tree,1,0,1,9)          # 'Add' button, and a
        gridlayout.addWidget(self.add_button,2,0,2,3)    # 'Save' button
        gridlayout.addWidget(self.save_button,2,3,2,3)   #
        self.tree.headerItem().setText(0,"Label")        # 


        if os.path.isfile('native_tree_save.qfile'):
            # First look for a previously saved tree. If found, define
            # it as a QFile named 'file', open it, and define a datastream
            # to read from it.
            #
            # Each tree node is saved to and read from the file in pairs:
            # first, the QTreeWidgetItem itself, then the number of children
            # the item has so that the tree structure can be re-created
            # 
            # The first item is added directly as the root for simplicity,
            # and is sent to the function which begins the tree reconstruction

            file = QtCore.QFile('native_tree_save.qfile')
            file.open(QtCore.QIODevice.ReadOnly)         
            datastream = QtCore.QDataStream(file)        
            child=QtGui.QTreeWidgetItem(self.tree.invisibleRootItem())
            child.read(datastream)
            num_childs=datastream.readUInt32()
            self.restore_item(datastream,child,num_childs)
        else: # Otherwise if this is the first use, create a root item
            new_item=QtGui.QTreeWidgetItem(self.tree)
            self.tree.setCurrentItem(self.tree.topLevelItem(0))
            self.tree.currentItem().setText(0,'root')

        self.tree.setItemSelected(self.tree.topLevelItem(0),1)
        self.tree.setCurrentItem(self.tree.topLevelItem(0))

        self.connect(self.add_button, QtCore.SIGNAL("clicked()"), self.add_item)
        self.connect(self.save_button, QtCore.SIGNAL("clicked()"), self.save_tree)
        self.added_item_count=0

    def add_item(self): # Adds an item to whatever is selected
        self.added_item_count+=1
        label=str(self.added_item_count)
        new_item=QtGui.QTreeWidgetItem(self.tree.currentItem())
        new_item.setText(0,label)
        self.tree.setCurrentItem(new_item)

    def restore_item(self,datastream,item,num_childs):
        for i in range(0, num_childs):
            child=QtGui.QTreeWidgetItem(item)
            child.read(datastream)
            num_childs=datastream.readUInt32()
            self.restore_item(datastream,child,num_childs)

    def save_item(self,item,datastream):
        num_childs=item.childCount()
        for i in range(0,num_childs):
            child = item.child(i)
            child.write(datastream)
            num_childs=child.childCount()
            datastream.writeUInt32(num_childs)
            self.save_item(child,datastream)

    def save_tree(self):
        file = QtCore.QFile('native_tree_save.qfile')
        file.open(QtCore.QIODevice.WriteOnly)
        datastream = QtCore.QDataStream(file)
        self.save_item(self.tree.invisibleRootItem(),datastream)


if __name__=='__main__':
    app = QtGui.QApplication(sys.argv)
    window = TreeExperiment()
    window.resize(200, 120)
    window.show()
    sys.exit(app.exec_())


所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:https://www.pythonheidong.com/blog/article/168252/a50c5da8bafe8de92a60/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

29 0
收藏该文
已收藏

评论内容:(最多支持255个字符)