Ejemplo n.º 1
0
    def _update_list(self, parent_obj: QObject, parent_node: QTreeWidget
                     or QTreeWidgetItem,
                     new_id_dict: Dict[int, Tuple[List[str], int]]):
        count = 0

        for obj in parent_obj.children():
            name_list = self._get_name_list(obj)
            item = TreeWidgetItem(parent_node, name_list)

            obj_count = 0

            for o in obj.children():
                obj_count += self._update_list(o, item, new_id_dict)

            item.setText(2, str(obj_count))

            name_list[2] = str(obj_count)
            self.item_dict[str(obj.__class__.__name__)].add(tuple(name_list))

            id_ = id(obj)
            new_id_dict[id_] = [item.text(i) for i in range(4)], obj_count

            _, prev_count = self.id_dict.pop(id_, (None, None))

            if prev_count is None:
                fr = 1
            elif prev_count + obj_count == 0:
                fr = 0
            else:
                fr = abs(prev_count - obj_count) / (prev_count + obj_count)
            item.setBackground(3, get_color(fr))

            count += 1 + obj_count

        return count
Ejemplo n.º 2
0
 def children(self, action):
     """List of children of action
     """
     if action is None:
         return [
             object
             for object in QObject.children(self)
             if isinstance(object, QAction) and object in iter(self._pathToAction.values())
         ]
     else:
         return [object for object in action.children() if object in iter(self._pathToAction.values())]
Ejemplo n.º 3
0
 def children(self, action):
     """List of children of action
     """
     if action is None:
         return [object
                 for object in QObject.children(self)
                 if isinstance(object, QAction) and
                 object in iter(self._pathToAction.values())]
     else:
         return [object
                 for object in action.children()
                 if object in iter(self._pathToAction.values())]
Ejemplo n.º 4
0
 def set_font_sizes(cls, parent: QObject, standard_size: int,
                    title_prefix: str, title_increment: int,
                    subtitle_prefix: str, subtitle_increment: int):
     """Set font sizes of all UI elements"""
     # print(f"set_font_sizes({parent},{standard_size},{title_prefix},"
     #       f"{title_increment},{subtitle_prefix},{subtitle_increment})")
     children = parent.children()
     for child in children:
         # We'll only change the font size of labels and controls,
         # not collections
         desired_font_size = standard_size
         set_size = False
         child_name = child.objectName()
         if isinstance(child, QLabel):
             # Set label to standard size or an increment depending on name
             set_size = True
             if child_name.startswith(title_prefix):
                 # print(f"Increment title label: {child_name}")
                 desired_font_size = standard_size + title_increment
             elif child_name.startswith(subtitle_prefix):
                 # print(f"Increment subtitle label: {child_name}")
                 desired_font_size = standard_size + subtitle_increment
             else:
                 pass
                 # print(f"Increment normal label: {child_name}")
         elif isinstance(child, QCheckBox) \
                 or isinstance(child, QRadioButton) \
                 or isinstance(child, QLineEdit) \
                 or isinstance(child, QPushButton) \
                 or isinstance(child, QDateEdit) \
                 or isinstance(child, QTimeEdit):
             set_size = True
             # print(f"Increment other fontable field: {child_name}")
         if set_size:
             child_font = child.font()
             child_font.setPointSize(desired_font_size)
             child.setFont(child_font)
         # Recursively handle the children of this item as subtrees of their own
         cls.set_font_sizes(child, standard_size, title_prefix,
                            title_increment, subtitle_prefix,
                            subtitle_increment)
Ejemplo n.º 5
0
    def QObject对象名称和属性(self):
        obj0 = QObject()
        obj1 = QObject()
        obj2 = QObject()
        obj3 = QObject()
        obj4 = QObject()
        obj5 = QObject()
        obj2.setObjectName("2")
        obj3.setObjectName("3")
        print("obj0", obj0)
        print("obj1", obj1)
        print("obj2", obj2)
        print("obj3", obj3)
        print("obj4", obj4)
        print("obj5", obj5)

        obj1.setParent(obj0)
        obj2.setParent(obj0)
        obj3.setParent(obj1)
        obj4.setParent(obj2)
        obj5.setParent(obj2)

        print(obj1.parent())
        print(obj2.parent())
        print(obj0.children())
        print(obj0.findChildren(QObject, None, Qt.FindChildrenRecursively))
        print(obj0.findChild(QObject, "2", Qt.FindChildrenRecursively))
        #********************内存管理***************************开始
        obj1 = QObject()
        self.obj1 = obj1
        obj2 = QObject()
        obj2.setParent(obj1)

        # 监听obj2对象被释放

        obj2.destroyed.connect(lambda _: print("obj2对象被释放了"))
        del self.obj1
Ejemplo n.º 6
0
    def toXml(
        cls,
        obj_: QtCore.QObject,
        include_children: bool = True,
        include_complex_types: bool = False,
    ) -> QtXml.QDomDocument:
        """
        Convert an object to xml.

        @param obj_. Object to be processed
        @param include_children. Include children of the given object
        @param include_complex_types. Include complex children
        @return xml of the given object
        """

        xml_ = QtXml.QDomDocument()

        if not obj_:
            return xml_

        e = xml_.createElement(type(obj_).__name__)
        e.setAttribute("class", type(obj_).__name__)
        xml_.appendChild(e)

        _meta = obj_.metaObject()

        i = 0
        # _p_properties = []
        for i in range(_meta.propertyCount()):
            mp = _meta.property(i)
            # if mp.name() in _p_properties:
            #    i += 1
            #    continue

            # _p_properties.append(mp.name())

            val = getattr(obj_, mp.name(), None)
            try:
                val = val()
            except Exception:
                pass

            if val is None:
                i += 1
                continue

            val = str(val)

            if not val and not include_complex_types:
                i += 1
                continue
            e.setAttribute(mp.name(), val)

            i += 1

        if include_children:

            for child in obj_.children():

                itd = cls.toXml(child, include_children, include_complex_types)
                xml_.firstChild().appendChild(itd.firstChild())
        return xml_
Ejemplo n.º 7
0
 def delete_gui_children(self, widget: QtCore.QObject):
     widget.children()
Ejemplo n.º 8
0
def printTree( qtObject: QObject, indent=0 ):
    print( " " * indent + "object:", qtObject )
    childList = qtObject.children()
    for child in childList:
        printTree( child, indent + 4 )
Ejemplo n.º 9
0
class CommandStack(collections.abc.Collection):
    def __init__(self):
        self._parent = QObject(None)
        self._index = 0
        self._command_number = 1

    def __len__(self):
        return len(self._parent.children())

    def __iter__(self):
        self._index = 0
        return self

    def __next__(self):
        if len(self) == 0:
            raise StopIteration

        if self._index < len(self):
            self._index += 1
            return self._parent.children()[self._index - 1]

        raise StopIteration

    def __contains__(self, item):
        if isinstance(item, str):
            # testing by string name and not reference
            item_name = item
            find_me = self._parent.findChild(item_name)
            if find_me is not None:
                return True
            return False

        # testing by references
        for itm in self:
            if item is itm:
                return True

        return False

    def __eq__(self, other):
        equals = [
            len(self) == len(other),
        ]
        equals = equals + list(
            map(lambda x, y: x is y, iter(self), iter(other)))

        return all(equals)

    def __del__(self):
        self._parent.deleteLater()

    def push(self, command):
        if not isinstance(command, QObject):
            raise TypeError

        if command.parent() is not None:
            raise AttributeError('Command QObject already has a parent!')

        command.setParent(self._parent)
        command.setObjectName('Command_{}'.format(self._command_number))
        self._command_number += 1

    def pop(self):
        last_index = len(self) - 1
        last_guy = self._parent.children()[last_index]

        self._command_number -= 1
        last_guy.setParent(None)
        last_guy.setObjectName(None)
        return last_guy