python-在PyQT4中使用QTreeWidgetItemIterator从QTreeWidget返回isChecked作为字典(或其他)

检查编辑的最终代码!

所以…我承认由于缺乏知识,我在这里画了一个绝对的空白,我只会介绍我的代码并祈祷一下.

使用这个神奇的xml到QTreeWidget生成器(已将ekhumoro编码),我已经在复选框(父节点的三态)中添加了该代码,现在我试图遍历这些复选框并返回字典或列表列表,或者…与父项关联:children(此树中的server:services)关系,以便我可以从树的检查结果中构建到文件夹的路径.这将是在按“开始”按钮作为系列中的第一个功能时发生的.

最终目标是要有一个工具,可以根据用户提供的开始和停止时间从平台上的多个服务器和每个服务器的服务中提取日志,并将这些日志传递到具有相同文件夹结构的管理框中.

我已经成功浏览了一个测试字典,基于os.path.getctime和getmtime搜索并找到了文件,将它们压缩,然后将它们复制到具有相同文件夹结构的单独驱动器中,该文件夹结构是函数的一部分…

但是,我发现TreeWidgetItemIterator上几乎没有文档(仅http://pyqt.sourceforge.net/Docs/PyQt4/qtreewidgetitemiterator.html#details),这对我不是很有帮助.因此,这个难题必不可少的(也是最后一个)让我迷失了!

XMLHandler:

from PyQt4 import QtCore, QtGui, QtXml
from PyQt4.QtXml import *


class XmlHandler(QXmlDefaultHandler):
    def __init__(self, root):
        QtXml.QXmlDefaultHandler.__init__(self)
        self._root = root
        self._item = None
        self._text = ''
        self._error = ''

    def startElement(self, namespace, name, qname, attributes):
        if qname == 'Machine' or qname == 'Feature':
            if self._item is not None:
                self._item = QtGui.QTreeWidgetItem(self._item)
            else:
                self._item = QtGui.QTreeWidgetItem(self._root)
            self._item.setData(0, QtCore.Qt.UserRole, qname)
            self._item.setText(0, 'Unknown Machine')
            if qname == 'Machine':
                self._item.setExpanded(False)
                self._item.setCheckState(0, QtCore.Qt.Unchecked)
                self._item.setFlags(QtCore.Qt.ItemIsSelectable|QtCore.Qt.ItemIsDragEnabled|QtCore.Qt.ItemIsUserCheckable|QtCore.Qt.ItemIsEnabled|QtCore.Qt.ItemIsTristate)
            elif qname == 'FeatureName':
                self._item.setText(1, self._text)
        self._text = ''
        return True

    def endElement(self, namespace, name, qname):
        if qname == 'FeatureName' or qname == 'MachineName':
            if self._item is not None:
                self._item.setText(0, self._text)
                self._item.setCheckState(0, QtCore.Qt.Unchecked)
        elif qname == 'Feature' or qname == 'Machine':
            self._item = self._item.parent()
        return True

    def characters(self, text):
        self._text += text
        return True

    def fatalError(self, exception):
        print('Parse Error: line %d, column %d:\n  %s' % (
              exception.lineNumber(),
              exception.columnNumber(),
              exception.message(),
              ))
        return False

使用XmlHandler制作窗口小部件的类:

class MakeWidget(QtGui.QTreeWidget):
    def __init__(self):
        QtGui.QTreeWidget.__init__(self)
        self.header().setResizeMode(QtGui.QHeaderView.Stretch)
        self.setHeaderLabels(['Servers and Services'])
        source = QtXml.QXmlInputSource()
        source.setData(xml)
        handler = XmlHandler(self)
        reader = QtXml.QXmlSimpleReader()
        reader.setContentHandler(handler)
        reader.setErrorHandler(handler)
        reader.parse(source) 

在我的GUI中创建小部件:

        self.treeServiceSelection = MakeWidget(xml, parent=self.ui.groupBoxServiceSelection)

小部件有两个层次,包括父母和孩子,仅此而已:

http://i.imgur.com/npPhG41.jpg

现在我们来到了我被困住的地方.我可以将信号绑定到按下按钮,我可以做其他所有事情,但是要从QTreeWidget中获取已检查的项目.看来我需要构造一个迭代器,并在它的init中添加Checked标志,但是我尝试过的所有事情都带有bupkiss.我很乐于为您提供一个解决方案,而不是提供给我一个解决方案,但是没有起点令人沮丧.

编辑:因此,我实际发布的内容均无用,但ekhumoro理解了我的问题的症结所在并提供了他的解决方案(已接受的答案).我添加了一个elif来处理父母检查过的任何事情(因为似乎没有看到孩子被检查过了):

def exportTree(self):
    mapping = defaultdict(list)
    root = self.tree.invisibleRootItem()
    for index in range(root.childCount()):
        parent = root.child(index)
        if parent.checkState(0) == QtCore.Qt.PartiallyChecked:
            features = mapping[parent.text(0)]
            for row in range(parent.childCount()):
                child = parent.child(row)
                if child.checkState(0) == QtCore.Qt.Checked:
                    features.append(child.text(0))
        elif parent.checkState(0) == QtCore.Qt.Checked:
            features = mapping[parent.text(0)]
            for row in range(parent.childCount()):
                features.append((parent.child(row)).text(0))
    return mapping

然后可以使用此示例根据gui中其他位置的另一个comboBox选择特定的子代:

def checkbox2mods(self):
    d = {'DMD2K8COR2VM': ['CC2DCP', 'Centercord'],
         'DMD2K8COR1VM': ['CC2DCP', 'Centercord']}
    root = self.tree.invisibleRootItem()
    if self.checkBox2.checkState() == QtCore.Qt.Checked:
        for index in range(root.childCount()):
            parent = root.child(index)
            for row in range(parent.childCount()):
                child = parent.child(row)
                x = d.values()
                y = d.keys()
                for _ in x:
                    if child.text(0) in _:
                        if parent.text(0) in y:
                            child.setCheckState(0, QtCore.Qt.Checked)
                            parent.setExpanded(True)

我确定代码很讨厌,但是通过仅选择子代,它会部分检查父代,这可以使导出功能正常工作.

解决方法:

我假设您问题的核心是您要遍历树小部件并构建包含已检查项目的字典.

下面的示例假定树的深度为两层,并且不尝试对检查状态进行任何管理:

# not needed for python 3
import sip
sip.setapi('QString', 2)

from collections import defaultdict
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.tree = QtGui.QTreeWidget(self)
        self.tree.header().hide()
        for index in range(5):
            parent = QtGui.QTreeWidgetItem(self.tree, ['NUS2K%s' % index])
            if index % 3:
                parent.setCheckState(0, QtCore.Qt.PartiallyChecked)
            else:
                parent.setCheckState(0, QtCore.Qt.Unchecked)
            features = 'Loader Reports Logging'.split()
            for count, item in enumerate(features):
                child = QtGui.QTreeWidgetItem(parent, [item])
                if index % 3 and count % 3:
                    child.setCheckState(0, QtCore.Qt.Checked)
                else:
                    child.setCheckState(0, QtCore.Qt.Unchecked)
            parent.setExpanded(True)
        self.button = QtGui.QPushButton('Export', self)
        self.button.clicked.connect(self.handleExport)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.tree)
        layout.addWidget(self.button)

    def handleExport(self):
        mapping = self.exportTree()
        for machine, features in mapping.items():
            print('%s:' % machine)
            for feature in features:
                print('  %s' % feature)

    def exportTree(self):
        mapping = defaultdict(list)
        root = self.tree.invisibleRootItem()
        for index in range(root.childCount()):
            parent = root.child(index)
            if parent.checkState(0) == QtCore.Qt.PartiallyChecked:
                features = mapping[parent.text(0)]
                for row in range(parent.childCount()):
                    child = parent.child(row)
                    if child.checkState(0) == QtCore.Qt.Checked:
                        features.append(child.text(0))
        return mapping

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(800, 300, 300, 300)
    window.show()
    sys.exit(app.exec_())
上一篇:机器学习实战笔记(Python实现)-00-readme


下一篇:Python Qt:pyqtProperty,样式表和事件处理程序