Esempio n. 1
0
    def testWidgetIterator(self):
        treeWidget = QTreeWidget()
        treeWidget.setColumnCount(1)
        items = []
        for i in range(10):
            items.append(QTreeWidgetItem(None, ['item: %d' % i]))
        treeWidget.insertTopLevelItems(0, items)

        index = 0
        for it in QTreeWidgetItemIterator(treeWidget):
            self.assertEqual(it.value().text(0), 'item: %d' % index)
            index += 1
    def fill_dependents(self, a_tw_dependents_root, a_sc):
        """
        Add the items which depend on a_sc.
        :param a_tw_dependents_root: dependents item root.
        :param a_sc: s/c
        """
        sonet_log(SonetLogType.INFO, 'SonetCanvasQt.fill_dependents')

        sc_dependents = self.get_dependents_sc(a_sc)

        for dependent in sc_dependents:
            new_item = QTreeWidgetItem(a_tw_dependents_root, [dependent, sc_dependents.get(dependent)])
    def fill_dependencies(self, a_tw_dependencies_root, a_sc):
        """
        Add the items which a_sc depends on.
        :param a_tw_dependencies_root: dependencies item root.
        :param a_sc: s/c
        """
        sonet_log(SonetLogType.INFO, 'SonetCanvasQt.fill_dependencies')

        sc_dependencies = self.get_dependencies_sc(a_sc)

        for dependency in sc_dependencies:
            new_item = QTreeWidgetItem(a_tw_dependencies_root, [dependency, sc_dependencies.get(dependency)])
 def slot_add_primitive(self):
     selected_action = self.graphTreeWidget.currentItem()
     selected_primitive = self.modelListWidget.currentItem()
     if selected_action is not None and selected_primitive is not None:
         action_name = str(selected_action.text(0))
         type_str = str(selected_action.text(1))
         if type_str == "action":
             mp_id = int(selected_primitive.data(Qt.UserRole))
             mp_name = str(selected_primitive.text())
             mp_key = str(mp_id)
             if mp_key not in self.data["nodes"][action_name]:
                 mpItem = QTreeWidgetItem(selected_action,
                                          [mp_name, "primitive"])
                 mpItem.setData(0, Qt.UserRole, mp_id)
                 mp_dict = dict()
                 mp_dict["transitions"] = dict()
                 mp_dict["type"] = "standard"
                 mp_dict["name"] = mp_name
                 self.data["nodes"][action_name][mp_key] = mp_dict
             else:
                 print(mp_name, "already part of action", action_name)
Esempio n. 5
0
    def get_pak_content(self, command):
        status, output = subprocess.getstatusoutput(command)
        result_list = output.splitlines()
        sep_file_list = []
        for line in result_list:
            pattern = r'LogPakFile: Display: "(.+)" offset: (.+), size: (.+) bytes, sha1: (.+)\.'
            res = re.match(pattern, line)
            if res is not None:
                # print(res.groups())
                sep_file = PakFileSepFile(res.group(1), res.group(2),
                                          res.group(3), res.group(4))
                sep_file_list.append(sep_file)

                path_sections = sep_file.path.split("/")
                path_connect = ""
                parent_item: QTreeWidgetItem = None
                for path_section in path_sections[:-1]:
                    path_connect += path_section + "/"
                    if path_connect in self.items:
                        parent_item = self.items[path_connect]
                    else:
                        tmp_item = QTreeWidgetItem(None, [path_section])
                        self.items[path_connect] = tmp_item
                        if parent_item is None:
                            print(path_section, sep_file.path)
                            self.ui.pak_content_tree_view.addTopLevelItem(
                                tmp_item)
                        else:
                            parent_item.addChild(tmp_item)
                        parent_item = tmp_item

                item = QTreeWidgetItem(None, [
                    path_sections[-1], sep_file.offset, sep_file.size,
                    sep_file.sha1
                ])
                if parent_item is None:
                    self.ui.pak_content_tree_view.addTopLevelItem(item)
                else:
                    parent_item.addChild(item)
                self.items[sep_file.path] = item
Esempio n. 6
0
 def update_node_data(self,
                      child_node: QTreeWidgetItem,
                      item: Union[JenkinsJob, JenkinsFolder]):
     icon = "job.png" if isinstance(item, JenkinsJob) else "folder.png"
     child_node.setText(0, item.name)
     child_node.setIcon(0, get_icon(icon))
     child_node.setCheckState(0, as_qt_selection(item.selected))
Esempio n. 7
0
    def add_tivo(self, name, ip_address):
        item = QTreeWidgetItem()
        item.setText(0, name)
        item.setText(1, ip_address)

        self.tivo_listings.addTopLevelItem(item)
        self.tivos_found.append(item)
Esempio n. 8
0
    def _map_treeitems(self, rootnode):
        """ rootnode: yorick_service.Nodes.Node """

        # PyQt4 is designed to add top level item alone
        rootitem = QTreeWidgetItem(self.widget)
        rootitem.setText(0, rootnode.node_name)
        self.widget.addTopLevelItem(rootitem)

        # add children widget items recursively
        def gen_child(parent, node):
            child = QTreeWidgetItem(parent)
            child.setText(0, node.node_name)

            self.item_to_node[child] = node
            node.listitem = child

            # partial to generate gen_child recurse
            list(map(partial(gen_child, child), node.children))
            return child

        # ignite recursion
        self.item_to_node.clear()
        self.item_to_node[rootitem] = rootnode

        rootitem.addChildren(
            list(map(partial(gen_child, rootitem), rootnode.children)))
Esempio n. 9
0
def iter_props_tree_items(device_path, device_dict):
    subsystem_item = QTreeWidgetItem(None, ['Subsystem: ACPI'])

    if 'path' in os.listdir(device_path):
        QTreeWidgetItem(subsystem_item,
                        ['Path: ' + get_file_contents(device_path, 'path')])
    if 'hid' in os.listdir(device_path):
        hid = get_file_contents(device_path, 'hid')
        hid_vendor = hid[:3]
        hid_device = hid[3:]
        ids_item = QTreeWidgetItem(subsystem_item, ['ID: ' + hid])
        db_vendor = pnp_db.get(hid_vendor.lower())
        db_device = db_vendor[1].get(hid_device.lower()) if db_vendor else None
        QTreeWidgetItem(ids_item, [
            'Vendor: ' + hid_vendor +
            (' (' + db_vendor[0] + ')' if db_vendor else '')
        ])
        QTreeWidgetItem(ids_item, [
            'Device: ' + hid_device +
            (' (' + db_device + ')' if db_device else '')
        ])
    if 'adr' in os.listdir(device_path):
        adr = get_file_contents(device_path, 'adr')
        QTreeWidgetItem(subsystem_item, ['Address: ' + adr])

    yield subsystem_item
Esempio n. 10
0
 def refresh(self):
     self.clear()
     if bool(self.db):
         self._prepare()
         self.queryItem = QTreeWidgetItem(self, ('Queries', ))
         tableItem = QTreeWidgetItem(self, ('Tables', ))
         viewItem = QTreeWidgetItem(self, ('Views', ))
         triggerItem = QTreeWidgetItem(self, ('Triggers', ))
         indexItem = QTreeWidgetItem(self, ('Indexes', ))
         firstItem = None
         for item in self.db.item_summary():
             new_item = QTreeWidgetItem((item.name, ))
             if item.kind == 'table':
                 parent = tableItem
                 self._add_table_item(item.name, new_item, parent)
                 if firstItem is None:
                     firstItem = new_item
             elif item.kind == 'view':
                 parent = viewItem
             elif item.kind == 'trigger':
                 parent = triggerItem
             elif item.kind == 'index':
                 parent = indexItem
             parent.addChild(new_item)
         for item in (self.queryItem, tableItem, viewItem):
             if item.childCount() < 11:
                 self.expandItem(item)
         if firstItem is not None:
             self.setCurrentItem(firstItem)
Esempio n. 11
0
 def add_list_to_view(self):
     """ add list to view """
     self.window.listWidget.invisibleRootItem().takeChildren()
     list_data = []
     for value in self.list_dict.values():
         list_data.append(value)
     for data in list_data:
         item_data = [
             data["function_name"], (data["count"]), (data["total_time"]),
             (data["self_time"]), (data["children_time"])
         ]
         item = QTreeWidgetItem(None, item_data)
         for column_index in [1, 2, 3, 4]:
             item.setTextAlignment(column_index, Qt.AlignRight)
             item.setBackground(
                 column_index,
                 get_brush(item_data[column_index], self.total_time))
             item.setFont(column_index, self.mono_space_font)
             item.setData(column_index, Qt.DisplayRole,
                          item_data[column_index])
         self.window.listWidget.addTopLevelItem(item)
     self.window.listWidget.sortItems(2, Qt.DescendingOrder)
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
Esempio n. 13
0
    def favorite_item(self, item: QtWidgets.QTreeWidgetItem, column: int):
        """Promote or demote an item as favorite

        :param item: The item
        :type item: QtWidgets.QTreeWidgetItem
        :param column: The column clicked
        :type column: int
        """
        ticker = {"ticker": item.ticker, "name": item.name}
        if item.is_checked():
            self.signal.sig_ticker_added_favorite.emit(ticker)
        else:
            self.signal.sig_ticker_removed_favorite.emit(ticker)
Esempio n. 14
0
    def _reload_options(self):

        self._treewidget.clear()
        self._qoptions.clear()
        self._qoptipasses.clear()
        self._qpeephole_opts.clear()

        categories = { }

        # populate the tree widget with new options
        for option in sorted(self._options, key=lambda x: x.name):
            if option.category in categories:
                category = categories[option.category]
            else:
                category = QTreeWidgetItem(self._treewidget, [option.category])

            w = QDecompilationOption(category, option, OptionType.OPTION, enabled=option.default_value==True)
            self._qoptions.append(w)

        passes_category = QTreeWidgetItem(self._treewidget, ["Optimization Passes"])
        categories['passes'] = passes_category

        default_passes = set(self.get_default_passes())
        for pass_ in self._opti_passes:
            w = QDecompilationOption(passes_category, pass_, OptionType.OPTIMIZATION_PASS,
                                     enabled=pass_ in default_passes)
            self._qoptipasses.append(w)

        po_category = QTreeWidgetItem(self._treewidget, ["Peephole Optimizations"])
        categories['peephole_opts'] = po_category

        default_peephole_opts = self.get_default_peephole_opts()
        for opt_ in self._peephole_opts:
            w = QDecompilationOption(po_category, opt_, OptionType.PEEPHOLE_OPTIMIZATION,
                                     enabled=opt_ in default_peephole_opts)
            self._qpeephole_opts.append(w)

        # expand all
        self._treewidget.expandAll()
    def fill_table_QTreeWidget(self,
                               a_file_type='',
                               a_file_name='',
                               a_total_rows='0',
                               a_total_cols='0',
                               p_clean_qtw_before_cleaning=False):
        if p_clean_qtw_before_cleaning:
            self.sonet_working_pcp_qtw.clear()

        if a_file_type == 'Earth-Mars':
            self.table_tw_outgoing_root_item.takeChildren()
            the_new_item = QTreeWidgetItem(
                self.table_tw_outgoing_root_item,
                [a_file_name, a_total_rows, a_total_cols])
        else:
            self.table_tw_incoming_root_item.takeChildren()
            the_new_item = QTreeWidgetItem(
                self.table_tw_incoming_root_item,
                [a_file_name, a_total_rows, a_total_cols])
        self.table_tw_outgoing_root_item.setExpanded(True)
        self.table_tw_incoming_root_item.setExpanded(True)
        self.resize_table_tw_columns()
Esempio n. 16
0
def iter_props_tree_items(device_path, device_dict):
    parent_item = None

    subsystem_item = QTreeWidgetItem(parent_item, ['Subsystem: Network'])

    QTreeWidgetItem(subsystem_item,
                    ['Address: ' + get_file_contents(device_path, 'address')])
    try:
        QTreeWidgetItem(
            subsystem_item,
            ['Carrier: ' + get_file_contents(device_path, 'carrier')])
    except OSError as err:
        if err.errno != 22:
            raise
    try:
        QTreeWidgetItem(subsystem_item,
                        ['Speed: ' + get_file_contents(device_path, 'speed')])
    except OSError as err:
        if err.errno != 22:
            raise

    yield subsystem_item
Esempio n. 17
0
def iter_props_tree_items(device_path, device_dict):
    parent_item = None

    subsystem_item = QTreeWidgetItem(parent_item,
                                     ['Subsystem: Hardware monitoring'])

    QTreeWidgetItem(subsystem_item, ['Chip name: ' + device_dict['chip_name']])

    sensors_dict = {}
    for item in device_dict['listdir']:
        if any(
                item.startswith(k) and len(item) > len(k)
                and item[len(k)].isdigit() for k in sensors_params_dict):
            add_sensor(item, sensors_dict, device_dict, device_path,
                       subsystem_item)
        elif item.startswith('fan'):
            name, param = item.split('_')
            if name not in sensors_dict:
                if name + '_label' in device_dict['listdir']:
                    label = get_file_contents(device_path, name + '_label')
                sensors_dict[name] = QTreeWidgetItem(
                    subsystem_item, ['Fan ' + name[len('fan'):]])
            if item == name + '_label':
                continue
            QTreeWidgetItem(sensors_dict[name], [
                fan_params_dict.get(param, param) + ': ' +
                get_file_contents(device_path, item)
            ])
        elif item.startswith('freq'):
            add_sensor(item)
        elif item.startswith('power'):
            pass
        elif item.startswith('pwm'):
            pass
        elif item.startswith('temp'):
            pass

    yield subsystem_item
    def fill_filter(self, a_sc, a_trip, a_tw_trip_root):
        if a_trip == 'Earth - Mars':
            a_trip = 0
        elif a_trip == 'Mars - Earth':
            a_trip = 1

        the_filters_dict = \
            SonetTrajectoryFilter._get_activated_filters_of_a_given_type(
                a_sc.get_filter(p_get_list=True)[a_trip]._data, True, 'All')
        filters_list = the_filters_dict.keys()
        for f in filters_list:
            filter = the_filters_dict.get(f)
            for ff in filter:
                new_item = QTreeWidgetItem(a_tw_trip_root, ['', f, ' '.join(ff)])
Esempio n. 19
0
 def add_widget(self, button, widget):
     """creates a QWidgetItem containing the widget,
     as child of the button-QWidgetItem
     """
     section = QTreeWidgetItem(button)
     section.setDisabled(True)
     section.setBackgroundColor(0, QColor(3, 169, 229))
     self.tree.setItemWidget(section, 0, widget)
     return section
Esempio n. 20
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)
Esempio n. 21
0
    def __init__(self, data):
        super().__init__()

        self.items = 0
        self.data = data
        self.tree = JsonTreeWidget()

        # testing
        tree_top = [
            QTreeWidgetItem(self.tree, ['foo']),
            QTreeWidgetItem(self.tree, ['bar']),
            QTreeWidgetItem(self.tree, ['baz']),
        ]
        tree_top[0].addChild(QTreeWidgetItem(['child', 'value']))
        tree_top[1].addChild(
            QTreeWidgetItem([
                'child2',
                'value of something really big and should hopefully wrap'
            ]))

        self.quit = QPushButton("Quit")
        self.search_box = QLineEdit()

        # QWidget Layout
        self.layout = QVBoxLayout()
        self.layout.setMargin(10)
        self.layout.addWidget(QLabel("Search"))
        self.layout.addWidget(self.search_box)
        self.layout.addWidget(self.tree)
        self.layout.addWidget(self.quit)

        # Set the layout to the QWidget
        self.setLayout(self.layout)

        # Signals and Slots
        self.quit.clicked.connect(self.quit_application)
        self.search_box.textChanged[str].connect(self.update_search)
Esempio n. 22
0
    def testCase(self):
        treeWidget = QTreeWidget()
        treeWidget.setColumnCount(1)
        items = []
        for i in range(10):
            items.append(QTreeWidgetItem(None, ["item: %i" % i]))

        treeWidget.insertTopLevelItems(0, items);
        _iter = QTreeWidgetItemIterator(treeWidget)
        index = 0
        while(_iter.value()):
            item = _iter.value()
            self.assertTrue(item is items[index])
            index += 1
            _iter += 1
Esempio n. 23
0
    def _create_item_for_packet(self, viewsb_packet):
        """ Creates a QTreeWidgetItem for a given ViewSBPacket.

        Args:
            viewsb_packet -- The ViewSBPacket to create the QTreeWidgetItem from.

        Returns a QTreeWidgetItem.
        """

        stringify_list = lambda l : [str(x) if x is not None else '' for x in l]

        def get_packet_string_array(viewsb_packet):
            """ Tiny helper to return and stringify the common fields used for the columns of tree items. """

            direction = viewsb_packet.direction.name if viewsb_packet.direction is not None else ''

            length = len(viewsb_packet.data) if viewsb_packet.data is not None else ''

            return stringify_list([
                viewsb_packet.summarize(),
                viewsb_packet.device_address,
                viewsb_packet.endpoint_number,
                direction,
                length,
                viewsb_packet.timestamp,
                viewsb_packet.summarize_status(),
                viewsb_packet.summarize_data()
                ]) + [viewsb_packet]


        item = QTreeWidgetItem(get_packet_string_array(viewsb_packet))

        # Give the item a reference to the original packet object.
        item.setData(0, QtCore.Qt.UserRole, viewsb_packet)

        return item
Esempio n. 24
0
    def treeWidget_load(self, surpac_scl_cfg):
        self.clear()
        self.treeWidget = QTreeWidgetItem(self)
        self.setColumnCount(1)
        self.setHeaderHidden(True)
        self.itemClicked.connect(self.__on_item_clicked)

        # 加入相对路径,处理pyinstaller打包后yml导入错误问题
        self.scl_path = Path.get_resource_path(surpac_scl_cfg)

        # 加入menu菜单配置yml文件
        menus = self.build_toplevel_menu(surpac_scl_cfg=self.scl_path)
        for item in menus:
            self.addTopLevelItem(item)
            self.setItemExpanded(item, True)
Esempio n. 25
0
    def __init__(self, ui_file):
        super(Form, self).__init__()
        ui_file = QFile(ui_file)
        ui_file.open(QFile.ReadOnly)
        loader = QUiLoader()
        self.window = loader.load(ui_file)
        self.window.setFixedSize(self.window.width(), self.window.height());
        ui_file.close()

        self.tree = self.window.findChild(QTreeWidget, 'treeMenu')
        #        self.tree.itemSelectionChanged.connect(self.itemSelection)
        self.tree.currentItemChanged.connect(self.itemSelection)
        self.tree.itemClicked.connect(self.itemSelection)
        menulist = ["Cadastro de Pessoa"]
        itemlist = ["Inserir", "Atualizar", "Excluir", "Listar"]
        for str in menulist:
            parent = QTreeWidgetItem(self.tree)
            parent.setText(0, str)
            for opcao in itemlist:
                child = QTreeWidgetItem(parent)
                child.setText(0, opcao)
            parent.setExpanded(1)
        self.window.show()
        return
Esempio n. 26
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
Esempio n. 27
0
 def _add_table_item(self, tablename, item, parent):
     for detail in self.db.item_detail(tablename):
         if detail.pk:
             color = Qt.darkGreen
         elif detail.notnull:
             color = Qt.black
         else:
             color = Qt.darkGray
         child = QTreeWidgetItem((detail.name, detail.type.upper()))
         child.setForeground(0, QBrush(color))
         font = child.font(1)
         font.setPointSize(max(6, font.pointSize() - 1))
         child.setFont(1, font)
         item.addChild(child)
Esempio n. 28
0
    def __create_action_list_item(cls, al):
        list_item = QTreeWidgetItem([al.name])
        list_item.setFlags(cls.item_flags)

        for __a in al.actors.items():
            actor, a = __a
            value = a.get('new_value') or ''
            old_value = a.get('old_value') or ''
            actor_type = a.get('type') or ''

            if not actor:
                actor = ''

            actor_item = QTreeWidgetItem(list_item,
                                         [actor, value, old_value, actor_type])
            actor_item.setFlags(cls.item_flags)

        return list_item
Esempio n. 29
0
def _build_item(name: str, data: type = None) -> QTreeWidgetItem:
    """
    Build a tree item with a display name, and sets its data

    :param data: the class name. If specified it's set at column 1 on Qt.UserRole

    """

    item = QTreeWidgetItem([name])
    flags = Qt.ItemIsSelectable | Qt.ItemIsEnabled
    if data:
        item.setData(1, Qt.UserRole, data)
        # Show the short description as tooltip of the items
        if data.shortDescription():
            item.setData(0, Qt.ToolTipRole, data.shortDescription())
        flags |= Qt.ItemIsDragEnabled
    item.setFlags(flags)
    return item
Esempio n. 30
0
def completeTree(treeWidget, data, parent=None, editable=False):
    if parent is None:
        parent = treeWidget.invisibleRootItem()

    for itemData in data:
        for k, v in itemData.items():
            item = QTreeWidgetItem()
            item.setText(0, k)
            if editable:
                item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsEditable
                              | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled
                              | Qt.ItemIsDropEnabled)
            for idx, cl in enumerate(v, 0):
                if isinstance(cl, list):
                    completeTree(treeWidget, cl, item, editable)
                else:
                    item.setText(idx + 1, cl)
            parent.addChild(item)