def _init_widgets(self):
        self.clear()

        if self.simgr.am_none:
            return

        for stash_name, stash in self.simgr.stashes.items():
            if not stash and stash_name not in ('active', 'deadended',
                                                'avoided'):
                continue

            item = QTreeWidgetItem(self,
                                   ["%s (%d)" % (stash_name, len(stash))])
            item.setFlags(item.flags() & ~Qt.ItemIsSelectable)

            for state in stash:
                subitem = QTreeWidgetItem(item, [str(state)])
                subitem.setData(0, 1, state)
                item.addChild(subitem)

            self.addTopLevelItem(item)

        # errored states
        if self.simgr.errored:
            item = QTreeWidgetItem(
                self, ["%s (%d)" % ('errored', len(self.simgr.errored))])
            item.setFlags(item.flags() & ~Qt.ItemIsSelectable)

            for estate in self.simgr.errored:
                subitem = QTreeWidgetItem(item, [str(estate)])
                subitem.setData(0, 1, estate.state)
                item.addChild(subitem)

            self.addTopLevelItem(item)
예제 #2
0
        def build_menu_by_recursive(root: QTreeWidgetItem, menu_dict: dict):
            for key in menu_dict:
                item = QTreeWidgetItem()

                item_font = QFont()
                item_font.setPointSize(
                    self.config.getint('master', 'master_item_font_size'))
                try:
                    text = str(menu_dict[key]['text'])
                    item.setText(0, text)
                    item.setFont(0, item_font)
                except KeyError:
                    pass
                try:
                    descript = str(menu_dict[key]['descript'])
                    item.setToolTip(0, descript)
                except KeyError:
                    pass
                try:
                    scl = str(menu_dict[key]['scl'])
                    item.setText(2, scl)
                except KeyError:
                    pass
                try:
                    children = menu_dict[key]['children']
                    build_menu_by_recursive(item, children)
                except KeyError:
                    pass
                try:
                    expanded = menu_dict[key]['expanded']
                    item.setExpanded(expanded)
                except KeyError:
                    pass

                root.addChild(item)
예제 #3
0
def populatebomtree():
    global bom, assy_top, assy_bot, viewtop, bomcolumns, selectionset
    bom = pandas.read_csv(os.path.join(BASE_FOLDER, 'Assembly\\bom.csv'),
                          header=0)
    assy_top = pandas.read_csv(os.path.join(BASE_FOLDER,
                                            'Assembly\\PnP_front.csv'),
                               header=0)
    assy_bot = pandas.read_csv(os.path.join(BASE_FOLDER,
                                            'Assembly\\PnP_back.csv'),
                               header=0)

    tw = window.treeWidget_bom
    tw.clearSelection()
    tw.clear()
    assy_side = assy_top if viewtop else assy_bot
    for index, row in bom.iterrows():
        selected = str.split(row['Parts'], ', ')
        pnp_refdes = assy_side['Name']
        pnp_count = 0
        parts_thisside = ''
        for refdes in selected:
            pnp_row = assy_side[pnp_refdes == refdes]
            if len(pnp_row) > 0:
                if (selectionset == None) or (refdes in selectionset):
                    if pnp_count == 0:
                        twi = QTreeWidgetItem(tw,
                                              row.filter(bomcolumns).tolist())
                    parts_thisside = parts_thisside + ',' + refdes if pnp_count > 0 else refdes
                    pnp_count = pnp_count + 1
                    twi.addChild(
                        QTreeWidgetItem(twi, [pnp_row['Name'].values[0]]))
        if 0 < pnp_count < len(selected):
            twi.setData(0, Qt.DisplayRole, parts_thisside)
        if pnp_count == 1:
            twi.removeChild(twi.child(0))
예제 #4
0
 def add_dir(self, dir_path, parent):
     sorted_list = sorted(self.list_dir(dir_path),
                          key=lambda x:
                          (x[0] not in self.dirs, x[0].lower()))
     for path, mtime in sorted_list:
         basename = os.path.basename(path)
         if len(basename) == 0:
             continue
         item = QTreeWidgetItem()
         item.setText(0, basename)
         self.index[item] = path
         parent.setFlags(parent.flags() | Qt.ItemIsTristate
                         | Qt.ItemIsUserCheckable)
         item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
         item.setCheckState(
             0, Qt.Checked
             if parent.checkState(0) == Qt.Checked else Qt.Unchecked)
         parent.addChild(item)
         item.setText(
             1, time.strftime("%b %d %Y %I:%M:%S %p",
                              time.localtime(mtime)))
         if path in self.dirs and len(self.list_dir(path)) != 0:
             sub_item = QTreeWidgetItem()
             self.hidden[item] = sub_item
             item.addChild(sub_item)
             item.setIcon(0, QIcon(get_resource_path("images/folder.png")))
예제 #5
0
 def on_btn_test_clicked(self):
     item = QTreeWidgetItem(None, ["Test", "a"])
     child = QTreeWidgetItem(None, ["Test", "a"])
     g_c = QTreeWidgetItem(None, ["Test", "a"])
     child.addChild(g_c)
     item.addChild(child)
     self.ui.pak_content_tree_view.addTopLevelItem(item)
예제 #6
0
    def __init__(self, title: str, data: Dict[str, str]):

        super().__init__()

        # ─────────────────── Add content ────────────────── #

        self.setColumnCount(2)
        parent_item = QTreeWidgetItem(self, [f'{title} : '])
        parent_item.set_selectable(False)
        self.addTopLevelItem(parent_item)

        for key, val in data.items():
            item = QTreeWidgetItem(parent_item, [f'{key} : ', val])
            parent_item.addChild(item)

            # Cosmetics
            item.set_selectable(False)
            item.setTextAlignment(0, Qt.AlignRight)

        # ──────────────────── Cosmetics ─────────────────── #

        # Hide header
        self.header().hide()

        # No background
        self.setStyleSheet('background-color: transparent;')

        # Dynamically change height when widget is collapsed or expanded
        # You have to update the maximum height of the widget, based on
        # its contents. For each top item you need to get the height for
        # that row using rowHeight() and do the same recursively for
        # child items whenever the item is expanded. Also, you need to
        # overwrite the sizeHint and minimumSizeHint.
        self.expanded.connect(self.update_height)
        self.collapsed.connect(self.update_height)
예제 #7
0
 def __add_words_to_speech_part(self, speech_part_item: QTreeWidgetItem,
                                words: list):
     """
     Adds words as a QTreeWidgetItem objects to the specified speech part item
     """
     for word in words:
         word_item = QTreeWidgetItem(word)
         word_item.setText(self.DEFAULT_COLUMN, word)
         speech_part_item.addChild(word_item)
예제 #8
0
 def addChildFileItem(self, file: str, rootFolder: str, folderpath: str,
                      folderItem: QtWidgets.QTreeWidgetItem):
     item = QtWidgets.QTreeWidgetItem()
     item.setText(0, file.split('/')[-1])
     item.setText(1, "{0:.3f} MB".format(os.path.getsize(file) / 1000000))
     item.setText(2, "Pending")
     item.setText(3, file)
     item.setText(4, self.getChildFolderName(rootFolder, folderpath))
     item.setIcon(0, getFileIcon(file))
     folderItem.addChild(item)
예제 #9
0
 def addChildFolderItem(self, folder: str, rootFolder: str,
                        folderItem: QtWidgets.QTreeWidgetItem):
     item = QtWidgets.QTreeWidgetItem()
     item.setText(0, folder.split('/')[-1])
     item.setText(1, "{0:.3f} MB".format(os.path.getsize(folder) / 1000000))
     item.setText(2, "")
     item.setText(3, "/".join(folder.split('/')[0:-1]))
     item.setIcon(0, getFileIcon(folder))
     folderItem.addChild(item)
     self.addChildFolder(item, folder, rootFolder)
예제 #10
0
 def __add_speech_part(self, speech_part: str,
                       aspect_item: QTreeWidgetItem) -> QTreeWidgetItem:
     """
     Adds a QTreeWidgetItem with specified text to the aspect item
     :return: added QTreeWidgetItem item
     """
     item = QTreeWidgetItem()
     item.setText(self.DEFAULT_COLUMN, speech_part)
     aspect_item.addChild(item)
     return item
예제 #11
0
파일: main.py 프로젝트: yassinz/mcircuit
    def create_from_dict(self, d):
        for category in d:
            category_item = QTreeWidgetItem()
            category_item.setText(0, category)

            for elem_name in d[category]:
                it = QTreeWidgetItem()
                it.setText(0, elem_name)
                category_item.addChild(it)

            self.addTopLevelItem(category_item)
예제 #12
0
class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)
        # Set the headers
        self.dataTreeWidget.setHeaderLabels(['ID', 'NAME', 'STATUS'])
        # Create dummy users
        user_1 = UserData("Alan", "Online", {"Task_A": 25, "Task_B": 60})
        user_2 = UserData("Max", "Online", {"Task_A": 68})
        user_3 = UserData("Scarlet", "Offline", {
            "Task_A": 5,
            "Task_B": 55,
            "Task_C": 25
        })
        users_list = [user_1, user_2, user_3]
        # Loop through users to get the value and insert for each row
        self.dataTreeWidget.clear()
        for index, user in enumerate(users_list):
            self.user_data = QTreeWidgetItem()
            progress_bar_tracker = TrackUserProgress()
            self.user_data.setData(0, Qt.DisplayRole, index)
            self.user_data.setData(1, Qt.DisplayRole, user.name)
            self.user_data.setData(2, Qt.DisplayRole, user.status)
            self.dataTreeWidget.addTopLevelItem(self.user_data)
            # Loop through each user's tasks and display it's progress bar.
            for user_task in sorted(list(user.tasks.keys())):
                user_task_child = QTreeWidgetItem()
                user_task_progress = QProgressBar()
                user_task_progress.setStyleSheet(
                    (progress_bar_tracker.return_progress_color(
                        user.tasks[user_task])))
                user_task_progress.setValue(user.tasks[user_task])
                user_task_child.setData(0, Qt.DisplayRole, user_task)
                self.user_data.addChild(user_task_child)
                self.dataTreeWidget.setItemWidget(user_task_child, 1,
                                                  user_task_progress)
        # Variable that handles when to expand and collapse all the columns
        self.click_counter = 2
        self.treeButton.clicked.connect(self.view_hide_clicked)

    def view_hide_clicked(self):
        if self.click_counter % 2 == 0:
            self.dataTreeWidget.expandAll()

        elif self.click_counter % 2 != 0:
            self.dataTreeWidget.collapseAll()

        self.click_counter += 1
예제 #13
0
    def __init__(self):

        super().__init__()

        # Add content
        self.setColumnCount(1)
        parent_item = QTreeWidgetItem(self, ['Disclosure triangle'])
        self.addTopLevelItem(parent_item)
        parent_item.addChild(QTreeWidgetItem(parent_item, 'AAA'))
        parent_item.addChild(QTreeWidgetItem(parent_item, 'BBB'))
        parent_item.addChild(QTreeWidgetItem(parent_item, 'CCC'))

        # Cosmetics
        self.header().hide()
        self.setStyleSheet('background-color: transparent;')
예제 #14
0
    def __init__(self):
        super().__init__()
        self.setHeaderHidden(True)

        self.addTopLevelItem(QTreeWidgetItem(["Library"]))

        for i in range(10):
            group = QTreeWidgetItem()
            group.setText(0, "Group" + str(1))
            group.setIcon(0, QIcon("images/count.png"))
            self.addTopLevelItem(group)

            content = QTreeWidgetItem()
            group.addChild(content)
            self.setItemWidget(content, 0, ExpandedList(self))
예제 #15
0
    def onPushButton(self):
        try:
            self.mac_addr = self.devices[self.listWidget.currentRow()].address
            self.discover.getServices(self.mac_addr)
        except:
            print("Could not get GATT services.")
        else:
            svcs = self.discover.svcs
            for serviceKey, serviceValue in svcs.services.items():
                item = QTreeWidgetItem(None, [serviceValue.description, serviceValue.uuid])
                
                for characteristic in serviceValue.characteristics:
                    for property in characteristic.properties:
                        child = QTreeWidgetItem(["", "", characteristic.uuid, property])
                        item.addChild(child)

                self.treeWidget.addTopLevelItem(item)
예제 #16
0
def build_oc_tree(tree, source_dict):
    oc_dict = build_oc_dict(source_dict)
    # entry = QTreeWidgetItem(None)
    for char, weapons in oc_dict.items():
        # dwarves[dwarf] = QTreeWidgetItem(tree)
        char_entry = QTreeWidgetItem(None)
        char_entry.setText(0, char)
        for weapon, oc_names in weapons.items():
            weapon_entry = QTreeWidgetItem(None)
            weapon_entry.setText(0, weapon)
            for name, uuid in oc_names.items():
                oc_entry = QTreeWidgetItem(None)
                oc_entry.setText(0, name)
                oc_entry.setText(1, source_dict[uuid]["status"])
                oc_entry.setText(2, uuid)
                weapon_entry.addChild(oc_entry)
            char_entry.addChild(weapon_entry)
        tree.addChild(char_entry)
예제 #17
0
 def on_objects_listbox(self, current_index):
     selected = self._objects[current_index][1]
     self._props.clear()
     common_item = QTreeWidgetItem([_("Common properties")])
     specific_item = QTreeWidgetItem([_("Specific properties")])
     other_item = QTreeWidgetItem([
         _("Other properties - they can not be searched and are not processed in any way"
           )
     ])
     common_fields = list(
         EntityMetadata.for_discriminator("OSMEntity").fields.keys())
     selected_metadata = EntityMetadata.for_discriminator(
         selected.discriminator)
     known_fields = selected_metadata.all_fields
     formatted_values = {}
     for field_name in selected.defined_field_names():
         raw_value = selected.value_of_field(field_name)
         if field_name not in known_fields:
             # By the mere fact that the other fields have no defined order, we can add them there without losing anything.
             other_item.addChild(
                 QTreeWidgetItem([
                     "%s: %s" %
                     (underscored_to_words(field_name), raw_value)
                 ]))
         else:
             value_str = "%s: %s" % (
                 underscored_to_words(field_name),
                 format_field_value(raw_value,
                                    known_fields[field_name].type_name))
             formatted_values[field_name] = value_str
     for common in common_fields:
         del known_fields[common]
         common_item.addChild(QTreeWidgetItem([formatted_values[common]]))
     for specific in known_fields.keys(
     ):  # Because we deleted the common ones in the loop before this, only the specific remain.
         if specific in formatted_values:
             specific_item.addChild(
                 QTreeWidgetItem([formatted_values[specific]]))
     # We add the entity ID mainly for debugging purposes, and that's the reason why it is added the last and so special in the first place.
     common_item.addChild(
         QTreeWidgetItem([_("Object id: {}").format(selected.id)]))
     self._props.addTopLevelItem(common_item)
     if specific_item.childCount() > 0:
         self._props.addTopLevelItem(specific_item)
         self._props.expandItem(specific_item)
         #self._props.setCurrentItem(specific_item) # Breaks focus behavior slightly, but annoingly enough.
     if other_item.childCount() > 0:
         self._props.addTopLevelItem(other_item)
     self._object_actions.clear()
     for action in self._all_actions:
         if action.executable(selected):
             mi = self._object_actions.addAction(action.label)
             mi.triggered.connect(
                 action_execution_handler_factory(action, selected, self))
예제 #18
0
    def addIndex(self, index):
        indexTree = self.applicationWindow.mainWindow.indexes

        if index.type == 'PRIMARY':
            name = 'PRIMARY KEY'
        else:
            name = index.name

        indexItem = QTreeWidgetItem()
        indexItem.setIcon(0, QIcon('../resources/icons/key.png'))
        indexItem.setText(0, name)
        indexItem.setText(1, index.type)

        for column in index.columns:
            columnItem = QTreeWidgetItem()
            columnItem.setIcon(0, QIcon('../resources/icons/bullet_black.png'))
            columnItem.setText(0, column.name)
            indexItem.addChild(columnItem)

        indexTree.addTopLevelItem(indexItem)
예제 #19
0
# ---------------------------
# Treeにitemに子itemを追加する
# ---------------------------
import sys
from PySide2.QtWidgets import QApplication, QTreeWidget, QTreeWidgetItem

app = QApplication(sys.argv)

qw_tree = QTreeWidget()
qw_tree.setHeaderLabels(["name", "tel", "mail"])
qw_tree_parent_item = QTreeWidgetItem(['family'])
qw_tree_parent_item.addChild(
    QTreeWidgetItem(['A', '111-111-111', '*****@*****.**']))  # Itemに子Itemを追加
qw_tree.addTopLevelItem(qw_tree_parent_item)
qw_tree.expandAll()  # TreeのItemを全て開く
qw_tree.show()

sys.exit(app.exec_())
예제 #20
0
파일: testTree.py 프로젝트: zizle/ADSYSTEM
    def __init__(self):
        super(TreeWidget, self).__init__()
        self.setColumnCount(3)
        self.setColumnWidth(0, 80)
        self.setColumnWidth(1, 80)
        self.setColumnWidth(2, 80)
        self.setIndentation(0)
        self.setHeaderHidden(True)
        self.foreground_font = QFont()
        self.foreground_font.setBold(True)
        self.normal_font = QFont()
        self.normal_font.setBold(False)
        self.setExpandsOnDoubleClick(False)
        p = QTreeWidgetItem(self)
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        p.setFont(0, font)
        p.setText(0, "父级1父级1父级1父级1父级1父级1")
        p.setIcon(0, QIcon("icons/arrow_right.png"))
        p.setFirstColumnSpanned(True)

        c = QTreeWidgetItem(p)

        c.setText(0, "子级1")
        c.setText(1, "子级2")
        c.setText(2, "子级3")
        c.setTextAlignment(0, Qt.AlignCenter)
        c.setTextAlignment(1, Qt.AlignCenter)
        c.setTextAlignment(2, Qt.AlignCenter)
        c.setData(0, Qt.UserRole, "c_00")
        c.setData(1, Qt.UserRole, "c_01")
        c.setData(2, Qt.UserRole, "c_02")

        c = QTreeWidgetItem(p)

        c.setText(0, "子级1")
        c.setText(1, "子级2")
        c.setTextAlignment(0, Qt.AlignCenter)
        c.setTextAlignment(1, Qt.AlignCenter)
        c.setData(0, Qt.UserRole, "c_03")
        c.setData(1, Qt.UserRole, "c_04")

        p.addChild(c)

        p = QTreeWidgetItem(self)
        p.setText(0, "父级2父级2父级2父级2父级2父级2")
        p.setIcon(0, QIcon("icons/arrow_right.png"))
        p.setFirstColumnSpanned(True)

        p.setFont(0, font)
        c = QTreeWidgetItem(p)

        c.setText(0, "子级2")
        c.setText(1, "子级22")
        c.setText(2, "子级23")
        c.setTextAlignment(0, Qt.AlignCenter)
        c.setTextAlignment(1, Qt.AlignCenter)
        c.setTextAlignment(2, Qt.AlignCenter)
        c.setData(0, Qt.UserRole, "c_10")
        c.setData(1, Qt.UserRole, "c_11")
        c.setData(2, Qt.UserRole, "c_12")

        p.addChild(c)
        self.itemClicked.connect(self.click)
        self.setFocusPolicy(Qt.NoFocus)
        self.setObjectName("tree")
        self.setStyleSheet(
            "#tree::item:selected{background-color:rgb(255,255,255);color:rgb(180,12,34);}"
            "#tree::item:hover{background-color:rgb(255,255,255);color:rgb(10,160,10)}"
        )
        self.setAnimated(True)
        self.setSelectionBehavior(QAbstractItemView.SelectItems)
        self.setSelectionMode(QAbstractItemView.SingleSelection)
예제 #21
0
    def __init__(self, *args, **kwargs):
        super(ExchangeLibTree, self).__init__(*args, **kwargs)
        self.itemClicked.connect(self.item_clicked)
        # self.setIndentation(0)  # 设置子项不缩进
        self.header().hide()
        # self.setRootIsDecorated(False)
        self.setFocusPolicy(Qt.NoFocus)
        # self.setLayoutDirection(Qt.RightToLeft)
        self.setColumnCount(1)
        # 添加交易所数据
        lib = [
            {
                "id": "cffex", "name": "中国金融期货交易所", "logo": "icons/cffex_logo.png",
                "children": [
                    {"id": "daily", "name": "日交易数据", "logo": "icons/daily.png"},
                    {"id": "rank", "name": "日交易排名", "logo": "icons/rank.png"},
                ]
            },
            {
                "id": "shfe", "name": "上海期货交易所", "logo": "icons/shfe_logo.png",
                "children": [
                    {"id": "daily", "name": "日交易数据", "logo": "icons/daily.png"},
                    {"id": "rank", "name": "日交易排名", "logo": "icons/rank.png"},
                ]
            },
            {
                "id": "czce", "name": "郑州商品交易所", "logo": "icons/czce_logo.png",
                "children": [
                        {"id": "daily", "name": "日交易数据", "logo": "icons/daily.png"},
                        {"id": "rank", "name": "日交易排名", "logo": "icons/rank.png"},
                        {"id": "receipt", "name": "每日仓单", "logo": "icons/receipt.png"},
                    ]
             },
            {
                "id": "dce", "name": "大连商品交易所", "logo": "icons/dce_logo.png",
                "children": [
                    {"id": "daily", "name": "日交易数据", "logo": "icons/daily.png"},
                    {"id": "rank", "name": "日交易排名", "logo": "icons/rank.png"},
                ]
             },
        ]

        for item in lib:
            tree_item = QTreeWidgetItem(self)
            tree_item.setText(0, item["name"])
            setattr(tree_item, "id", item["id"])
            # tree_item.setTextAlignment(0, Qt.AlignRight | Qt.AlignVCenter)
            tree_item.setIcon(0, QIcon(item["logo"]))
            for child_item in item["children"]:
                child = QTreeWidgetItem(tree_item)
                child.setText(0, child_item["name"])
                setattr(child, "id", child_item["id"])
                child.setIcon(0, QIcon(child_item["logo"]))
                # child.setTextAlignment(0, Qt.AlignRight | Qt.AlignVCenter)
                tree_item.addChild(child)
        self.setObjectName("exchangeTree")
        self.setStyleSheet("#exchangeTree{font-size:14px;border:none;border-right: 1px solid rgba(50,50,50,100)}"
                           "#exchangeTree::item:hover{background-color:rgba(0,255,0,50)}"
                           "#exchangeTree::item:selected{background-color:rgba(255,0,0,100)}"
                           "#exchangeTree::item{height:28px;}"
                           )
예제 #22
0
class DisclosureTriangle(QTreeWidget):
    """
    An (very basic) implementation of a DisclosureTriangle, i.e. a
    widget that looks like this:

    ____________________
    |                  |
    |  |> Title:       |
    |      key1: val1  |
    |      key2: val2  |
    |      …           |
    --------------------

    This triangle can be expanded or collapsed and is instanciated with
    a title and a dictionnary of keys and values. Made with the help of
    musicamente on Stackoverflow:  https://stackoverflow.com/questions/
    63862724/
    qtreeview-dynamic-height-according-to-content-disclosure-triangle.
    """
    def __init__(self, title: str, data: Dict[str, str]):
        """
        Init self with a title and a dictionnary of keys and values (see
        self docstring).

        :param title: The title of the disclosure tree (e.g. 'Details'
            in dEAduction's course and exercise choosers.
        :param data: The data to be displayed in the disclosure
            triangle.
        """

        super().__init__()

        # ─────────────────── Add content ────────────────── #

        self.setColumnCount(2)
        self.__parent_item = QTreeWidgetItem(self, [f'{title} : '])
        self.__parent_item.set_selectable(False)
        self.addTopLevelItem(self.__parent_item)

        for key, val in data.items():
            item = QTreeWidgetItem(self.__parent_item, [f'{key} : ', val])
            self.__parent_item.addChild(item)

            # Cosmetics
            item.set_selectable(False)
            item.setTextAlignment(0, Qt.AlignRight)

        # ──────────────────── Cosmetics ─────────────────── #

        # Hide header
        self.header().hide()

        # No background
        self.setStyleSheet('background-color: transparent;')

        # Dynamically change height when widget is collapsed or expanded
        # You have to update the maximum height of the widget, based on
        # its contents. For each top item you need to get the height for
        # that row using rowHeight() and do the same recursively for
        # child items whenever the item is expanded. Also, you need to
        # overwrite the sizeHint and minimumSizeHint.
        self.expanded.connect(self.update_height)
        self.collapsed.connect(self.update_height)

    def expand(self, yes: bool = True):
        """
        Expand the tree is yes is True, collapse it otherwise.

        :param yes: See above.
        """

        if yes:
            self.expandItem(self.__parent_item)
        else:
            self.collapseItem(self.__parent_item)

    #####################
    # Redifined methods #
    #####################

    # See
    # https://stackoverflow.com/questions/63862724/
    # qtreeview-dynamic-height-according-to-content-disclosure-triangle

    def update_height(self):
        self.setMaximumHeight(self.sizeHint().height())

    def get_height(self, parent=None):
        height = 0
        if not parent:
            parent = self.rootIndex()
        for row in range(self.model().rowCount(parent)):
            child = self.model().index(row, 0, parent)
            height += self.rowHeight(child)
            if self.isExpanded(child) and self.model().hasChildren(child):
                height += self.get_height(child)
        return height

    def sizeHint(self):
        hint = super().sizeHint()
        # The + 10 avoids an ugly scroll bar
        hint.setHeight(self.get_height() + 10 + self.frameWidth() * 2)
        return hint

    def minimumSizeHint(self):
        return self.sizeHint()
예제 #23
0
class LayerManagerTreeWidget(QTreeWidget):
    def __init__(self):
        super().__init__()
        self.setHeaderHidden(True)
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.viewport().setAcceptDrops(True)
        self.items_dict = {}
        self.default_item = QTreeWidgetItem()
        self.default_item2 = QTreeWidgetItem()
        self.default_item.setText(0, "Avatar")
        self.default_item2.setText(0, "Prop")
        self.items_dict["0(default)"] = {}
        self.items_dict["0(default)"]["0(default)"] = self.default_item
        self.items_dict["0(default)"]["1(default)"] = self.default_item2
        self.addTopLevelItem(self.default_item)
        self.addTopLevelItem(self.default_item2)
        self.all_avatars = global_get_avatars(True)
        self.all_props = global_get_props(True)
        #set avatars menu item
        for item in self.all_avatars:
            _name = item.GetName()
            temp_item = QTreeWidgetItem()
            temp_item.setText(0, _name)
            self.items_dict["0(default)"][_name] = temp_item
            self.default_item.addChild(temp_item)

        #set props menu item
        for item in self.all_props:
            _name = item.GetName()
            if _name != "Shadow Catcher ":  #ignore 'Shadow Catcher' Object
                temp_item = QTreeWidgetItem()
                temp_item.setText(0, _name)
                self.items_dict["0(default)"][_name] = temp_item
                self.default_item2.addChild(temp_item)

        #double click menu item
        self.itemDoubleClicked.connect(self.on_item_selection)

    def on_item_selection(self, _items):
        global camera
        global is_x_arrive
        global is_y_arrive
        global is_z_arrive
        global object_transform
        #set object
        object_Clicked = RLPy.RScene.FindObject(
            RLPy.EObjectType_Avatar | RLPy.EObjectType_Prop, _items.text(0))
        #set camera
        camera_list = RLPy.RScene.FindObjects(RLPy.EObjectType_Camera)
        camera = camera_list[0] if (len(camera_list) > 0) else None
        #set time
        time = RLPy.RGlobal.GetTime()

        if (object_Clicked != None and camera != None):
            #get object postion
            object_transform = object_Clicked.LocalTransform()
            rotation_z = 0.0
            object_control = object_Clicked.GetControl("Transform")
            data_block = object_control.GetDataBlock()
            float_control_z = data_block.GetControl('Rotation/RotationZ')
            temp_z = float_control_z.GetValue(RLPy.RGlobal.GetTime(),
                                              rotation_z)
            rotation_z = self.DegressTransform(temp_z[1])
            #calculate the position by facing object
            Deg2Rad = (RLPy.RMath.CONST_PI * 2) / 360
            angleX = RLPy.RMath.Cos((rotation_z - 90) * Deg2Rad)
            angleY = RLPy.RMath.Sin((rotation_z - 90) * Deg2Rad)
            distanceXY = ((object_transform.S().z * 100) +
                          (object_transform.S().y * 100) / 2) * 5
            object_transform.T().z += (object_transform.S().z * 100) / 2
            object_transform.T().x += distanceXY * angleX
            object_transform.T().y += distanceXY * angleY
            #set camera rotation
            camera.GetControl("Transform").GetDataBlock().GetControl(
                'Rotation/RotationX').SetValue(time, self.AngularTransform(90))
            camera.GetControl("Transform").GetDataBlock().GetControl(
                'Rotation/RotationY').SetValue(time, 0)
            camera.GetControl("Transform").GetDataBlock().GetControl(
                'Rotation/RotationZ').SetValue(time, temp_z[1])
            #reset boolean
            is_x_arrive = False
            is_y_arrive = False
            is_z_arrive = False
            #start timer function
            timer_callback.register_time_out(self.MoveAnimation)
            rl_py_timer.Start()

    def AngularTransform(self, degrees):
        AngularValue = (degrees / 180) * RLPy.RMath.CONST_PI
        return AngularValue

    def DegressTransform(self, Angular):
        DegressValue = (Angular / RLPy.RMath.CONST_PI) * 180
        return DegressValue

    def MoveAnimation(self):
        global timer
        global camera
        global camera_transform
        global object_transform
        #get camera transform
        camera_control = camera.GetControl("Transform")
        camera_transform = RLPy.RTransform(RLPy.RTransform.IDENTITY)
        camera_control.GetValue(RLPy.RGlobal.GetTime(), camera_transform)
        #do MoveAnimation
        self.DoMoveAnimation(object_transform.T().y,
                             camera_transform.T().y, "Y")
        self.DoMoveAnimation(object_transform.T().z,
                             camera_transform.T().z, "Z")
        self.DoMoveAnimation(object_transform.T().x,
                             camera_transform.T().x, "X")
        #set camera position
        camera_control.SetValue(RLPy.RGlobal.GetTime(), camera_transform)

    def DoMoveAnimation(self, pos_obj, pos_camera, xyz):
        global camera_transform
        global is_x_arrive
        global is_y_arrive
        global is_z_arrive

        distance = RLPy.RMath.Abs(pos_obj - pos_camera)
        is_far_away = True if (distance >= 5) else False
        speed = 10

        if (xyz == "X"):
            if (pos_obj > pos_camera and is_far_away):
                camera_transform.T().x += distance / speed
            elif (pos_obj < pos_camera and is_far_away):
                camera_transform.T().x -= distance / speed
            else:
                is_x_arrive = True

        elif (xyz == "Y"):
            if (pos_obj > pos_camera and is_far_away):
                camera_transform.T().y += distance / speed
            elif (pos_obj < pos_camera and is_far_away):
                camera_transform.T().y -= distance / speed
            else:
                is_y_arrive = True

        else:
            #"Z"
            if (pos_obj > pos_camera and is_far_away):
                camera_transform.T().z += distance / speed
            elif (pos_obj < pos_camera and is_far_away):
                camera_transform.T().z -= distance / speed
            else:
                is_z_arrive = True

        #if XYZ arrived to stop timer
        if (is_x_arrive and is_y_arrive and is_z_arrive):
            rl_py_timer.Stop()
예제 #24
0
import sys
from PySide2.QtWidgets import QApplication, QTreeWidget, QTreeWidgetItem

app = QApplication(sys.argv)

qw_tree = QTreeWidget()
qw_tree.setHeaderLabels(["name", "tel", "mail"])

qw_tree_parent_item_1 = QTreeWidgetItem(['family'])
qw_tree_parent_item_1.addChild(QTreeWidgetItem(['A', '111-111-111', '*****@*****.**']))
qw_tree_parent_item_1.addChild(QTreeWidgetItem(['B', '222-222-222', '*****@*****.**']))

qw_tree_parent_item_2 = QTreeWidgetItem(['school'])
qw_tree_parent_item_2.addChild(QTreeWidgetItem(['C', '333-333-333', '*****@*****.**']))
qw_tree_parent_item_2.addChild(QTreeWidgetItem(['D', '444-444-444', '*****@*****.**']))

qw_tree.addTopLevelItem(qw_tree_parent_item_1)
qw_tree.addTopLevelItem(qw_tree_parent_item_2)
qw_tree.expandAll()
qw_tree.show()

sys.exit(app.exec_())