Python PyQt5.QtWidgets 模块,QTreeWidgetItem() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用PyQt5.QtWidgets.QTreeWidgetItem()

项目:SLP-Annotator    作者:PhonologicalCorpusTools    | 项目源码 | 文件源码
def main(): 
    app     = QApplication (sys.argv)
    tree    = QTreeWidget ()
    headerItem  = QTreeWidgetItem()
    item    = QTreeWidgetItem()

    for i in range(3):
        parent = QTreeWidgetItem(tree)
        parent.setText(0, "Parent {}".format(i))
        parent.setFlags(parent.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable)
        for x in range(5):
            child = QTreeWidgetItem(parent)
            child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
            child.setText(0, "Child {}".format(x))
            child.setCheckState(0, Qt.Unchecked)
    tree.show() 
    sys.exit(app.exec_())
项目:grid-control    作者:akej74    | 项目源码 | 文件源码
def add_cpu_sensors(self):
        """Add selected temperature sensor(s) to the "Selected CPU sensor(s)" three widget."""

        items = [item for item in self.ui.treeWidgetHWMonData.selectedItems()]

        # The new items should have the tree widget itself as parent
        parent = self.ui.treeWidgetSelectedCPUSensors

        for item in items:
            sensor_item = QtWidgets.QTreeWidgetItem(parent)
            sensor_item.setText(0, item.text(0))
            sensor_item.setText(1, item.text(1))
            sensor_item.setForeground(0, QtGui.QBrush(QtCore.Qt.blue))  # Text color blue

        # Deselect all items in the HWMon tree widget after they have been added
        self.ui.treeWidgetHWMonData.clearSelection()
项目:AlphaHooks    作者:AlphaHooks    | 项目源码 | 文件源码
def tree_widget(self, tree, structure):
        """
        Used to traverse a QTreeWidget and adding the items in a
        dict or list.

        :param tree: pass a QTreeWidget instance
        :param structure: pass a dictionary
        """
        if type(structure) is dict:
            for key, val in structure.items():
                child = QTreeWidgetItem()
                child.setText(0, key)
                tree.addChild(child)
                self.tree_widget(child, val)
        elif type(structure) is str:
            child = QTreeWidgetItem()
            child.setText(0, structure)
            tree.addChild(child)
        elif isinstance(structure, QWidget):
            self.index += 1
            tree.setText(1, str(self.index))
            self.display.addWidget(structure)
项目:OpenHWControl    作者:kusti8    | 项目源码 | 文件源码
def add_cpu_sensors(self):
        """Add selected temperature sensor(s) to the "Selected CPU sensor(s)" three widget."""

        items = [item for item in self.treeWidgetHWMonData.selectedItems()]

        # The new items should have the tree widget itself as parent
        parent = self.treeWidgetSelectedCPUSensors

        for item in items:
            sensor_item = QtWidgets.QTreeWidgetItem(parent)
            sensor_item.setText(0, item.text(0))
            sensor_item.setText(1, item.text(1))
            sensor_item.setForeground(0, QtGui.QBrush(QtCore.Qt.blue))  # Text color blue

        # Deselect all items in the HWMon tree widget after they have been added
        self.treeWidgetHWMonData.clearSelection()
项目:continuum    作者:zyantific    | 项目源码 | 文件源码
def update(self):
        # Update files.
        self._ui.project_tree.clear()
        items = []
        icon_provider = QFileIconProvider()

        for cur_file in self.project.files:
            file_info = QFileInfo(cur_file)
            item = QTreeWidgetItem(None, [
                os.path.relpath(cur_file, self.project.proj_dir), 
                "N/A",
            ])
            item.setData(0, Qt.UserRole, Project.file_to_idb(cur_file))
            item.setIcon(0, icon_provider.icon(file_info))
            items.append(item)

        self._ui.project_tree.insertTopLevelItems(0, items)

        # Update other stuff.
        self._ui.project_path.setText(self.project.proj_dir)
项目:pyree-old    作者:DrLuke    | 项目源码 | 文件源码
def discoverWorkers(self):
        """Discover new workers via udp broadcasts"""
        rlist, wlist, elist = select([self.discoverysocket], [], [], 0)
        if rlist:
            received = self.discoverysocket.recvfrom(4096)[0]
            discoverydata = {}
            try:
                discoverydata = json.loads(bytes.decode(received))
            except json.JSONDecodeError:
                pass

            if "ip" in discoverydata and "port" in discoverydata:
                if "host" in discoverydata:
                    name = discoverydata["host"]
                else:
                    name = discoverydata["ip"] + ":" + str(discoverydata["port"])
                if name not in self.workers:
                    treeItem = QTreeWidgetItem(1001)    # Type 1000 for Worker Item
                    treeItem.setText(0, name)
                    self.treeWidget.addTopLevelItem(treeItem)
                    self.grabPeriodicInfos()    # Grab monitor data
                    self.workers[name] = Worker(discoverydata, treeItem, nodeDataJar=self.nodeDataJar)
                    self.workers[name].tick(self.sheetDeltaMemory)
                    self.workers[name].synchronize()
项目:pyree-old    作者:DrLuke    | 项目源码 | 文件源码
def replyMonitors(self, msg):
        """Handle reply to monitors request"""
        self.monitors = msg["replydata"]

        for monitor in self.monitors:
            if monitor not in self.monitorState:    # Monitor is newly available
                self.monitorState[monitor] = {}
                self.monitorState[monitor]["treeItem"] = QTreeWidgetItem(1002)  # Type 1002 for monitor item
                self.monitorState[monitor]["treeItem"].setText(0, monitor)
                self.monitorState[monitor]["treeItem"].setIcon(0, self.monitorOkIcon)
                self.treeItem.addChild(self.monitorState[monitor]["treeItem"])
                self.treeItem.setExpanded(True)
                self.monitorState[monitor]["state"] = "stop"
                self.monitorState[monitor]["sheet"] = None
        for monitor in self.monitorState:
            if monitor not in self.monitors:    # Monitor exists in state, but is not available anymore
                self.monitorState[monitor]["state"] = "gone"
                self.monitorState[monitor]["treeItem"].setIcon(0, self.monitorGoneIcon)

        # TODO: Set sheet item state here (blue for active, but no sheet, red for gone, black for all good)
项目:pyree-old    作者:DrLuke    | 项目源码 | 文件源码
def selectNode(self, position, inType:type=None, outType:type=None):
        if self.searchAndCompareModules():
            for nodeName in self.availableNodes:
                if self.availableNodes[nodeName].placeable:
                    returnItem = self.checkOrCreateCategory(self.availableNodes[nodeName].Category, self.ui.treeWidget)
                    newItem = QTreeWidgetItem(1002)  # Type 1002 for modules
                    newItem.setText(0, self.availableNodes[nodeName].name)
                    returnItem.addChild(newItem)
                    newItem.setData(1, Qt.UserRole, nodeName)

        self.exec()

        if len(self.ui.treeWidget.selectedItems()) == 1:
            selectedItem = self.ui.treeWidget.selectedItems()[0]
            selectedItem.setSelected(False)
            if selectedItem.data(1, Qt.UserRole) in self.availableNodes:
                classToSpawn = self.availableNodes[selectedItem.data(1, Qt.UserRole)]
                newNode = classToSpawn()
                newNode.sendMessageCallback = self.sendMessageCallback

                if self.scene is not None:
                    self.scene.undostack.push(AddNodeToSceneCommand(newNode, position, self.scene))
项目:pyree-old    作者:DrLuke    | 项目源码 | 文件源码
def checkOrCreateCategory(self, categories, treeWidget):
        """Recursively add category folders to treeWidget unless they already exist"""
        currentItem = None
        currentCatTree = self.categoryTree
        for category in categories:
            if category in currentCatTree:
                currentItem = currentCatTree[category][0]
                currentCatTree = currentCatTree[category][1]
            else:
                newItem = QTreeWidgetItem(1001)     # Type 1001 for categories
                newItem.setText(0, category)
                if currentItem is None:
                    treeWidget.addTopLevelItem(newItem)
                else:
                    currentItem.addChild(newItem)
                currentItem = newItem
                currentCatTree[category] = [newItem, {}]
                currentCatTree = currentCatTree[category][1]
        return currentItem
项目:pyree-old    作者:DrLuke    | 项目源码 | 文件源码
def __init__(self, parent):
        self.parent = parent

        self.workerAccepted = False     # Whether or not the worker accepted the controller
        self.workerTreeItem = QTreeWidgetItem()

        self.monitorState = {}

        self.inbuf = ""
        self.connection = None

        self.requestJar = {}

        # Refresh monitors every 5 seconds
        self.monitorTimer = QTimer()
        self.monitorTimer.timeout.connect(self.requestMonitors)
        self.monitorTimer.start(5000)

        #
        self.errorIcon = QIcon("resources/icons/exclamation.png")
项目:pyree-old    作者:DrLuke    | 项目源码 | 文件源码
def loadWorkers(self, loadData):
        for workerData in loadData:
            newWorker = Worker(self)
            newconn = Connection(workerData[0], workerData[1], newWorker.messagecallback)
            newWorker.connection = newconn
            if not newconn.valid:
                newWorker.createTreeitem()
                newWorker.connectionLost()

            self.connections[newconn.socket] = (newconn, newWorker)

            for state in workerData[2]:
                newWorker.monitorState[state[0]] = {}
                newWorker.monitorState[state[0]]["state"] = state[1]

                monitorTreeitem = QTreeWidgetItem()
                monitorTreeitem.setText(0, state[0])
                newWorker.workerTreeItem.addChild(monitorTreeitem)
                newWorker.monitorState[state[0]]["treeitem"] = monitorTreeitem

                newWorker.monitorState[state[0]]["sheet"] = newWorker.parent.sheethandler.newMonitorSheet(str(newWorker.connection.ip) + ":" + str(newWorker.connection.port) + " - " + state[0], monitorTreeitem)
                newWorker.monitorState[state[0]]["sheet"].relations = state[2]
项目:Enibar    作者:ENIB    | 项目源码 | 文件源码
def add_product(self, pname, cname, _):
        """ Add product

        :param str pname: Product name
        :param str cname: Category name
        """
        cat_widget = None
        for widget in self.categories:
            if widget.text(0) == cname:
                cat_widget = widget
        if not cat_widget:
            cat_widget = QtWidgets.QTreeWidgetItem(self, [cname])
            self.categories.append(cat_widget)

        pro_widget = QtWidgets.QTreeWidgetItem(cat_widget, [pname])
        self.products.append(pro_widget)
项目:Enibar    作者:ENIB    | 项目源码 | 文件源码
def add_category(self, name, id_):
        """ Add product category to product list.
        This function can't add product to database.

        :param str name: Category name
        :param int id_: Category id
        """
        cat_widget = QtWidgets.QTreeWidgetItem(self, [name])
        self.categories.append(cat_widget)
        for prod in api.products.get(category=id_):
            self.add_product(prod['name'], name, prod['percentage'])


#
# Category
#
项目:gpvdm    作者:roderickmackenzie    | 项目源码 | 文件源码
def make_entry(self,root,text,true_false):
        depth=0
        pointer=root
        for depth in range(0,len(text)):
            found=False
            for i in range(0,pointer.childCount()):
                if pointer.child(i).text(0)==text[depth]:
                    found=True
                    pointer=pointer.child(i)
                    break
            if found==False:
                pointer=QTreeWidgetItem(pointer, [text[depth]])
                pointer.setFlags(pointer.flags() | Qt.ItemIsUserCheckable)
                #if depth==0:
                #   pointer.setIcon(0,QIcon_load("folder"))

                if true_false==True:
                    pointer.setCheckState(0, Qt.Checked ) 
                else:
                    pointer.setCheckState(0, Qt.Unchecked )
项目:unist_bb_downloader    作者:kcm4482    | 项目源码 | 文件源码
def addFileListItem(self, filelist_item, filelist):
        for myfile in filelist:
            if isinstance(myfile, myfunc.FileList):
                _filelist_item = QtWidgets.QTreeWidgetItem(filelist_item)
                _filelist_item.setFlags(_filelist_item.flags() | QtCore.Qt.ItemIsTristate | QtCore.Qt.ItemIsUserCheckable)
                _filelist_item.setText(0, myfile.name)
                size = self.getSizeUnit(myfile.size)
                _filelist_item.setText(1, size)
                _filelist_item.setText(2, myfile.file_path)
                _filelist_item.setCheckState(0, QtCore.Qt.Checked)
                self.addFileListItem(_filelist_item, myfile)
                continue
            file_item = QtWidgets.QTreeWidgetItem(filelist_item)
            file_item.setFlags(file_item.flags() | QtCore.Qt.ItemIsUserCheckable)
            file_item.setText(0, myfile.name)
            size = self.getSizeUnit(myfile.size)
            file_item.setText(1, size)
            file_item.setText(2, myfile.file_path)
            file_item.setCheckState(0, QtCore.Qt.Checked)
项目:universal_tool_template.py    作者:shiningdesign    | 项目源码 | 文件源码
def DataToTree(self, tree, cur_node, data, filter=''):
        node_info = data[0]
        node_info_child = data[1]
        [cur_node.setText(i, node_info[i]) for i in range(len(node_info))]
        target = re.compile(filter, re.IGNORECASE)
        for sub_data in node_info_child:
            if filter == '':
                new_node = QtWidgets.QTreeWidgetItem()
                cur_node.addChild(new_node)
                self.DataToTree(tree, new_node, sub_data)
            else:
                if not target.search(sub_data[0][0]) and not self.DataChildCheck(sub_data[1], filter):
                    pass
                else:
                    new_node = QtWidgets.QTreeWidgetItem()
                    cur_node.addChild(new_node)
                    new_node.setExpanded(1)
                    self.DataToTree(tree, new_node, sub_data, filter)
项目:universal_tool_template.py    作者:shiningdesign    | 项目源码 | 文件源码
def DataToTree_old_2LevelSearch(self, tree, cur_node, data, filter=''):
        node_info = data[0]
        node_info_child = data[1]
        [cur_node.setText(i, node_info[i]) for i in range(len(node_info))]
        target = re.compile(filter, re.IGNORECASE)
        for sub_data in node_info_child:
            if filter == '':
                new_node = QtWidgets.QTreeWidgetItem()
                cur_node.addChild(new_node)
                self.DataToTree(tree, new_node, sub_data)
            else:
                if not target.search(sub_data[0][0]) and len(sub_data[1]) == 0:
                    #print(sub_data[0][0]) print(sub_data[1])
                    pass    
                else:
                    new_node = QtWidgets.QTreeWidgetItem()
                    cur_node.addChild(new_node)
                    new_node.setExpanded(1)
                    self.DataToTree(tree, new_node, sub_data, filter)
项目:universal_tool_template.py    作者:shiningdesign    | 项目源码 | 文件源码
def DataToTree(self, tree, cur_node, data, filter=''):
        node_info = data[0]
        node_info_child = data[1]
        [cur_node.setText(i, node_info[i]) for i in range(len(node_info))]
        target = re.compile(filter, re.IGNORECASE)
        for sub_data in node_info_child:
            if filter == '':
                new_node = QtWidgets.QTreeWidgetItem()
                cur_node.addChild(new_node)
                self.DataToTree(tree, new_node, sub_data)
            else:
                if not target.search(sub_data[0][0]) and not self.DataChildCheck(sub_data[1], filter):
                    pass
                else:
                    new_node = QtWidgets.QTreeWidgetItem()
                    cur_node.addChild(new_node)
                    new_node.setExpanded(1)
                    self.DataToTree(tree, new_node, sub_data, filter)
项目:universal_tool_template.py    作者:shiningdesign    | 项目源码 | 文件源码
def DataToTree_old_2LevelSearch(self, tree, cur_node, data, filter=''):
        node_info = data[0]
        node_info_child = data[1]
        [cur_node.setText(i, node_info[i]) for i in range(len(node_info))]
        target = re.compile(filter, re.IGNORECASE)
        for sub_data in node_info_child:
            if filter == '':
                new_node = QtWidgets.QTreeWidgetItem()
                cur_node.addChild(new_node)
                self.DataToTree(tree, new_node, sub_data)
            else:
                if not target.search(sub_data[0][0]) and len(sub_data[1]) == 0:
                    #print(sub_data[0][0]) print(sub_data[1])
                    pass    
                else:
                    new_node = QtWidgets.QTreeWidgetItem()
                    cur_node.addChild(new_node)
                    new_node.setExpanded(1)
                    self.DataToTree(tree, new_node, sub_data, filter)
项目:universal_tool_template.py    作者:shiningdesign    | 项目源码 | 文件源码
def DataToTree(self, tree, cur_node, data, filter=''):
        node_info = data[0]
        node_info_child = data[1]
        [cur_node.setText(i, node_info[i]) for i in range(len(node_info))]
        target = re.compile(filter, re.IGNORECASE)
        for sub_data in node_info_child:
            if filter == '':
                new_node = QtWidgets.QTreeWidgetItem()
                cur_node.addChild(new_node)
                self.DataToTree(tree, new_node, sub_data)
            else:
                if not target.search(sub_data[0][0]) and not self.DataChildCheck(sub_data[1], filter):
                    pass
                else:
                    new_node = QtWidgets.QTreeWidgetItem()
                    cur_node.addChild(new_node)
                    new_node.setExpanded(1)
                    self.DataToTree(tree, new_node, sub_data, filter)
项目:idasec    作者:RobinDavid    | 项目源码 | 文件源码
def setupUi(self, Master):
        Master.setObjectName("Master")
        Master.resize(718, 477)
        self.verticalLayout = QtWidgets.QVBoxLayout(Master)
        self.verticalLayout.setObjectName("verticalLayout")
        self.splitter = QtWidgets.QSplitter(Master)
        self.splitter.setOrientation(QtCore.Qt.Vertical)
        self.splitter.setObjectName("splitter")
        self.tab_widget = QtWidgets.QTabWidget(self.splitter)
        self.tab_widget.setObjectName("tab_widget")

        self.docker = QtWidgets.QDockWidget(self.splitter)
        self.docker.setObjectName("docker")
        self.docker.setAllowedAreas(QtCore.Qt.BottomDockWidgetArea)

        self.log_widget = QtWidgets.QTreeWidget(self.docker)
        self.log_widget.setHeaderItem(QtWidgets.QTreeWidgetItem(["date", "origin", "type", "message"]))
        self.docker.setWidget(self.log_widget)

        self.verticalLayout.addWidget(self.splitter)
        self.tab_widget.setCurrentIndex(-1)
        QtCore.QMetaObject.connectSlotsByName(Master)
        Master.setWindowTitle("IDASec")
项目:grid-control    作者:akej74    | 项目源码 | 文件源码
def add_gpu_sensors(self):
        """Add selected temperature sensor(s) to the "Selected GPU sensor(s)" three widget."""
        items = [item for item in self.ui.treeWidgetHWMonData.selectedItems()]

        # The new items should have the tree widget itself as parent
        parent = self.ui.treeWidgetSelectedGPUSensors

        for item in items:
            sensor_item = QtWidgets.QTreeWidgetItem(parent)
            sensor_item.setText(0, item.text(0))
            sensor_item.setText(1, item.text(1))
            sensor_item.setForeground(0, QtGui.QBrush(QtCore.Qt.blue))  # Text color blue

        # Deselect all items in the HWMon tree widget after they have been added
        self.ui.treeWidgetHWMonData.clearSelection()
项目:OpenHWControl    作者:kusti8    | 项目源码 | 文件源码
def add_gpu_sensors(self):
        """Add selected temperature sensor(s) to the "Selected GPU sensor(s)" three widget."""
        items = [item for item in self.treeWidgetHWMonData.selectedItems()]

        # The new items should have the tree widget itself as parent
        parent = self.treeWidgetSelectedGPUSensors

        for item in items:
            sensor_item = QtWidgets.QTreeWidgetItem(parent)
            sensor_item.setText(0, item.text(0))
            sensor_item.setText(1, item.text(1))
            sensor_item.setForeground(0, QtGui.QBrush(QtCore.Qt.blue))  # Text color blue

        # Deselect all items in the HWMon tree widget after they have been added
        self.treeWidgetHWMonData.clearSelection()
项目:OpenHWControl    作者:kusti8    | 项目源码 | 文件源码
def populate_tree_linux(treeWidget):
    import psutil
    hardwares = psutil.sensors_temperatures()

    # No sensor data (empty list) indicates OpenHWMon is not running
    if not hardwares:
        return

    # Add hardware nodes and temperature sensors to the three widget
    for key, nodelist in hardwares.items():
        item_list = []
        parent = treeWidget
        item = QtWidgets.QTreeWidgetItem(parent)
        item.setText(0, key)  # First column, name of the node
        item.setText(1, key)  # Second column, node id
        item.setFlags(QtCore.Qt.ItemIsEnabled)  # Make hardware nodes "not selectable" in the UI
        for index, node in enumerate(nodelist):
            parent = item
            itema = QtWidgets.QTreeWidgetItem(parent)
            if not node.label:
                name = key
            else:
                name = node.label
            itema.setText(0, name)  # First column, name of the node
            itema.setText(1, name)  # Second column, node id
            itema.setText(2, str(node.current))  # Third column, temperature value
            itema.setForeground(0, QtGui.QBrush(QtCore.Qt.blue))
            itema.setForeground(2, QtGui.QBrush(QtCore.Qt.blue))
项目:pyree-old    作者:DrLuke    | 项目源码 | 文件源码
def newOtherSheet(self):
        newName = self.sheetWidget.newSheetLineedit.text()
        for sheet in self.sheets:   # Prevent duplicate names
            if newName == sheet.name:
                return
        if len(newName) > 0:
            newTreeitem = QTreeWidgetItem()
            newTreeitem.setText(0, newName)
            self.sheetWidget.sheetTree.addTopLevelItem(newTreeitem)

            self.sheets.append(Sheet(newName, newTreeitem))
            self.itemClickedOther(newTreeitem, -1) # Make new sheet current
            self.sheetWidget.sheetTree.setCurrentItem(newTreeitem)
项目:pyree-old    作者:DrLuke    | 项目源码 | 文件源码
def loadSheets(self, sheetData):
        for sheet in sheetData:
            newTreeitem = QTreeWidgetItem()
            newTreeitem.setText(0, sheet[0])
            self.sheetWidget.sheetTree.addTopLevelItem(newTreeitem)

            newSheet = Sheet(sheet[0], newTreeitem)
            newSheet.relations = sheet[1]
            newSheet.monitorSheet = sheet[2]
            self.sheets.append(newSheet)
            self.itemClickedOther(newTreeitem, -1)  # Make new sheet current
            self.sheetWidget.sheetTree.setCurrentItem(newTreeitem)
项目:Enibar    作者:ENIB    | 项目源码 | 文件源码
def load_list(self, mails):
        """ Load notes and display them in the list

        :param list mails: Preselected mails
        """
        for note in api.notes.get():
            widget = QtWidgets.QTreeWidgetItem(self.mail_list, (
                note['nickname'],
                note['mail'],
                note['firstname'],
                note['lastname']
            ))
            if note['mail'] in mails:
                widget.setSelected(True)
项目:Enibar    作者:ENIB    | 项目源码 | 文件源码
def __init__(self):
        super().__init__()
        uic.loadUi('ui/admin_stats_window.ui', self)
        nb_red, red = api.stats.get_red_sum()
        nb_green, green = api.stats.get_green_sum()
        self.red_label.setText("{:.2f} € ({})".format(red, nb_red))
        self.green_label.setText("{:.2f} € ({})".format(green, nb_green))
        self.total_label.setText("{:.2f} € ({})".format(green + red, nb_red + nb_green))
        self.ecocups_nb_label.setText(str(api.stats.get_ecocups_nb()))
        for note, value in api.stats.get_red_notes():
            QtWidgets.QTreeWidgetItem(self.red_notes, [note, "{:.2f}".format(value)])
        self.show()
项目:Enibar    作者:ENIB    | 项目源码 | 文件源码
def _build_recap(self):
        """ Parse a CSV file and try to build lines from it.
        """
        with open(self.file_path, 'r') as fd:
            reader = csv.DictReader(fd)
            for line in reader:
                mail = line.get('Mail')
                if mail:
                    mail = mail.lower()
                note = api.notes.get(lambda x: x['mail'] == mail)
                if note and not note[0]['hidden']:
                    note = note[0]['nickname']
                    self.notes.append(note)
                else:
                    note = None
                if note:
                    QtWidgets.QTreeWidgetItem(
                        self.recap,
                        (note,
                         mail
                        )
                    )
                else:
                    w = QtWidgets.QTreeWidgetItem(
                        self.recap,
                        ("[{} {}]".format(line["Nom"], line["Prénom"]),
                         mail
                        )
                    )
                    for i in range(2):
                        w.setBackground(i, QtCore.Qt.red)
项目:Enibar    作者:ENIB    | 项目源码 | 文件源码
def add_product(self, cname, pname, price_name, price):
        """ Add product to list

        :param str cname: Category name
        :param str pname: Product name
        :param str price_name: Price name
        :param float price: Price value
        """
        name = "{} ({}) - {}".format(pname, price_name, cname)
        for product in self.products:
            if product['name'] == name:
                product['price'] += price
                product['price'] = product['price']
                product['count'] += 1
                product['widget'].setText(0, str(product['count']))
                product['widget'].setText(2, str(round(product['price'], 2)))
                break
        else:
            product = {
                'name': name,
                'price': price,
                'count': 1,
                'category': cname,
                'product': pname,
                'price_name': price_name,
                'deletable': False if pname == settings.ECOCUP_NAME else True,
            }
            widget = QtWidgets.QTreeWidgetItem(['1', name, str(price)])
            self.addTopLevelItem(widget)
            product['widget'] = widget
            self.products.append(product)
        self.update_total()
项目:Enibar    作者:ENIB    | 项目源码 | 文件源码
def selection_changed(self):
        selected = [obj.text() for obj in self.note_list.selectedItems()]
        to_del = []

        if len(selected) > len(self.selected_notes):  # Something was added
            for note in selected:
                if note not in self.selected_notes:
                    cb = QtWidgets.QComboBox()
                    cb.addItems(["1/4", "1/2"] + list(map(str, range(1, 11))))
                    cb.setCurrentIndex(2)

                    item = QtWidgets.QTreeWidgetItem(self.selected_notes_report, [note, "1"])
                    self.selected_notes_report.setItemWidget(item, 1, cb)
                    item.setFlags(QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled)
                    self.selected_notes[note] = item
        else:
            for note in self.selected_notes:
                if note not in selected:
                    to_del.append(note)

        for note in to_del:
            item = self.selected_notes[note]
            del self.selected_notes[note]
            sip.delete(item)

        self.note_list.search_input.clear()
        self.note_list.search_input.setFocus(True)
项目:Enibar    作者:ENIB    | 项目源码 | 文件源码
def add_product(self, name, category, percentage):
        """ Add product to consumption list. If the products has no null price
            only.

        :param str name: Product name
        :param str category: Category Name
        """
        # Find category widget
        cat_widget = None
        for cat in self.categories:
            if category == cat.text(0):
                cat_widget = cat
        if not cat_widget:
            return

        category = api.categories.get_unique(name=category)
        product = api.products.get_unique(
            category=category['id'],
            name=name
        )
        if not product:
            return

        for price in api.prices.get(product=product['id']):
            if float(price['value']) != 0:
                break
        else:
            return

        prod_widget = QtWidgets.QTreeWidgetItem([name])
        cat_widget.addChild(prod_widget)
        self.products.append(prod_widget)
项目:Sephrasto    作者:Aeolitus    | 项目源码 | 文件源码
def loadVorteile(self):
        self.uiVor.treeWidget.blockSignals(True)
        vortList = [[],[],[],[],[],[],[],[]]
        for el in Wolke.DB.vorteile:
            if Wolke.Char.voraussetzungenPrüfen(Wolke.DB.vorteile[el].voraussetzungen):
                idx = Wolke.DB.vorteile[el].typ
                vortList[idx].append(el)
        for i in range(len(vortList)):
            itm = self.uiVor.treeWidget.topLevelItem(i)
            if type(itm) != QtWidgets.QTreeWidgetItem:
                    continue
            if itm == 0: 
                continue
            for j in range(itm.childCount()):
                chi = itm.child(j)
                if type(chi) != QtWidgets.QTreeWidgetItem:
                    continue
                txt = chi.text(0)
                if txt in Wolke.Char.vorteile or txt == Wolke.Char.minderpakt:    
                    chi.setCheckState(0, QtCore.Qt.Checked)
                else:
                    chi.setCheckState(0, QtCore.Qt.Unchecked) 
                if txt not in vortList[i] and txt != Wolke.Char.minderpakt:
                    chi.setHidden(True)
                    if txt in Wolke.Char.vorteile:
                        chi.setCheckState(0,QtCore.Qt.Unchecked)
                        Wolke.Char.vorteile.remove(txt)
                else:
                    chi.setHidden(False)
                if Wolke.DB.vorteile[el].variable!=0:
                    Wolke.Char.vorteileVariable[el] = self.itemWidgets[el].value()
        self.updateInfo()
        self.uiVor.treeWidget.blockSignals(False)
项目:Sephrasto    作者:Aeolitus    | 项目源码 | 文件源码
def initVorteile(self):
        self.uiVor.treeWidget.blockSignals(True)
        vortList = [[],[],[],[],[],[],[],[]]
        for el in Wolke.DB.vorteile:
            if Wolke.DB.vorteile[el].kosten > 20 and Wolke.DB.vorteile[el].variable == 0:
                continue
            if Wolke.DB.vorteile[el].kosten < 0:
                continue
            if el in Wolke.Char.vorteile:
                continue
            idx = Wolke.DB.vorteile[el].typ
            vortList[idx].append(el)
        for i in range(len(vortList)):
            parent = QtWidgets.QTreeWidgetItem(self.uiVor.treeWidget)
            parent.setText(0, VorteilTypen[i])
            parent.setText(1,"")
            parent.setExpanded(True)
            for el in vortList[i]:
                child = QtWidgets.QTreeWidgetItem(parent)
                child.setText(0, Wolke.DB.vorteile[el].name)
                if Wolke.DB.vorteile[el].variable!=0:
                    child.setText(1, "20 EP")
                else:
                    child.setText(1, str(Wolke.DB.vorteile[el].kosten) + " EP")
        self.updateInfo()
        self.uiVor.treeWidget.blockSignals(False)
项目:hacked_cnc    作者:hackerspace    | 项目源码 | 文件源码
def run_cmd(self, cmd):
        item = QTreeWidgetItem(self.comtree)

        item.setText(0, time.strftime("%Y.%m.%d. %H:%M:%S", time.localtime()))
        item.setText(1, cmd)

        for i in range(3):
            item.setTextAlignment(i, Qt.AlignTop)

        item.setForeground(1, QtGui.QBrush(green))
        item.setForeground(2, QtGui.QBrush(red))

        self.comtree.scrollToItem(item)
        self.conn.cmd(cmd)
        proc_events()
项目:unist_bb_downloader    作者:kcm4482    | 项目源码 | 文件源码
def LoadTreeItems(self):
        self.total_item = QtWidgets.QTreeWidgetItem(self.courseTree)
        self.total_item.setFlags(self.total_item.flags() | QtCore.Qt.ItemIsTristate | QtCore.Qt.ItemIsUserCheckable)
        self.total_item.setText(0, '????')
        self.total_item.setCheckState(0, QtCore.Qt.Unchecked)
        self.total_item.setExpanded(True)
        for course in self.account.course_list:
            item = QtWidgets.QTreeWidgetItem(self.total_item)
            item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
            item.setText(0, course.name)
            item.setCheckState(0, QtCore.Qt.Unchecked)
项目:Mac-Python-3.X    作者:L1nwatch    | 项目源码 | 文件源码
def examineChildElements(self, parentElement, parentItem):
        # Traverse the document.
        element = parentElement.firstChild()
        while not element.isNull():
            item = QTreeWidgetItem()
            item.setText(0, element.tagName())
            parentItem.addChild(item)
            self.examineChildElements(element, item)
            element = element.nextSibling()
项目:functions-plus    作者:ax330d    | 项目源码 | 文件源码
def build_tree(self, function_tree, root):
        '''Build Qt Widget tree.'''

        if not function_tree:
            return

        if isinstance(function_tree, FunctionData):
            flags = int(function_tree.flags)
            addr = function_tree.addr

            self.cols.set_data(addr, flags)

            for index in xrange(0, len(self.cols.names)):
                if index > 0:
                    root.setText(index, self.cols.col(index))
                if flags & idc.FUNC_THUNK:
                    root.setBackground(index, QtGui.QColor("violet"))
                    root.setBackground(index, QtGui.QColor("violet"))
                if flags & idc.FUNC_LIB:
                    root.setBackground(index, QtGui.QColor("cyan"))
                    root.setBackground(index, QtGui.QColor("cyan"))
            return

        for name, tree in sorted(function_tree.iteritems()):
            func_item = QtWidgets.QTreeWidgetItem(root)
            if not isinstance(tree, FunctionData):
                word = 'items'
                tree_keys_len = len(tree.keys())
                if tree_keys_len % 10 == 1:
                    word = 'item'
                name = '{} ({} {})'.format(name, tree_keys_len, word)
            func_item.setText(0, name)
            self.build_tree(tree, func_item)
项目:examples    作者:pyqt    | 项目源码 | 文件源码
def examineChildElements(self, parentElement, parentItem):
        # Traverse the document.
        element = parentElement.firstChild()
        while not element.isNull():
            item = QTreeWidgetItem()
            item.setText(0, element.tagName())
            parentItem.addChild(item)
            self.examineChildElements(element, item)
            element = element.nextSibling()
项目:idasec    作者:RobinDavid    | 项目源码 | 文件源码
def log(self, type, message, origin="IDASec"):
        date = datetime.datetime.now().strftime("%H:%M:%S")
        res = re.match("^(\[[A-Za-z]*\])",message)
        if res:
            type = res.groups()[0]
            message = message[len(type):].lstrip()
        message = message.rstrip()
        self.log_widget.addTopLevelItem(QtWidgets.QTreeWidgetItem([date, origin, type, message]))
        self.log_widget.scrollToBottom()


################################################################################
# Usage as plugin
################################################################################
项目:idasec    作者:RobinDavid    | 项目源码 | 文件源码
def OnCreate(self, _):
        self.setupUi(self)
        self.add_trace_button.clicked.connect(self.load_trace)
        self.disassemble_button.clicked.connect(self.disassemble_from_trace)
        self.colorize_button.clicked.connect(self.colorize_trace)
        self.heatmap_button.clicked.connect(self.heatmap_trace)
        self.dump_button.clicked.connect(self.dump_trace)
        self.refresh_button.clicked.connect(self.refresh_trace_view)
        self.traces_tab.currentChanged.connect(self.trace_switch)
        self.traces_tab.tabCloseRequested.connect(self.unload_trace)
        self.loading_stat.setVisible(False)
        self.progressbar_loading.setVisible(False)
        self.traces_tab.setTabsClosable(True)
        self.reads_view.setHeaderItem(QtWidgets.QTreeWidgetItem(["name", "value"]))
        self.writes_view.setHeaderItem(QtWidgets.QTreeWidgetItem(["name", "value"]))
项目:json-viewer    作者:ashwin    | 项目源码 | 文件源码
def tree_add_row(self, key, val, tree_widget):

        text_list = []

        if isinstance(val, dict) or isinstance(val, list):
            text_list.append(key)
            row_item = QtWidgets.QTreeWidgetItem([key])
            self.recurse_jdata(val, row_item)
        else:
            text_list.append(key)
            text_list.append(str(val))
            row_item = QtWidgets.QTreeWidgetItem([key, str(val)])

        tree_widget.addChild(row_item)
        self.text_to_titem.append(text_list, row_item)
项目:calcam    作者:euratom-software    | 项目源码 | 文件源码
def QTreeWidgetItem(*args):
    if qt_ver == 4:
        for i in range(len(args)):
            if type(args[i]) == str:
                args[i] = self.QStringList(args[i])

    return QTreeWidgetItem_class(*args)
项目:pyqt5-example    作者:guinslym    | 项目源码 | 文件源码
def examineChildElements(self, parentElement, parentItem):
        # Traverse the document.
        element = parentElement.firstChild()
        while not element.isNull():
            item = QTreeWidgetItem()
            item.setText(0, element.tagName())
            parentItem.addChild(item)
            self.examineChildElements(element, item)
            element = element.nextSibling()
项目:StudentsManager    作者:Zaeworks    | 项目源码 | 文件源码
def tableAdd(self, student):
        item = QtWidgets.QTreeWidgetItem(self.studentTable)
        self.tableSet(student, item)
        self.tableList.append(student)
        self.tableIndex[student] = item
项目:Sephrasto    作者:Aeolitus    | 项目源码 | 文件源码
def initVorteile(self):
        self.uiVor.treeWidget.blockSignals(True)
        vortList = [[],[],[],[],[],[],[],[]]
        for el in Wolke.DB.vorteile:
            idx = Wolke.DB.vorteile[el].typ
            vortList[idx].append(el)
        for i in range(len(vortList)):
            parent = QtWidgets.QTreeWidgetItem(self.uiVor.treeWidget)
            parent.setText(0, VorteilTypen[i])
            parent.setText(1,"")
            parent.setExpanded(True)
            for el in vortList[i]:
                child = QtWidgets.QTreeWidgetItem(parent)
                child.setText(0, Wolke.DB.vorteile[el].name)
                if el in Wolke.Char.vorteile:    
                    child.setCheckState(0, QtCore.Qt.Checked)
                else:
                    child.setCheckState(0, QtCore.Qt.Unchecked)
                if Wolke.DB.vorteile[el].variable!=0:
                    spin = QtWidgets.QSpinBox()
                    spin.setMinimum(0)
                    spin.setSuffix(" EP")
                    spin.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
                    spin.setMaximum(9999)
                    if el == Wolke.Char.minderpakt:
                        spin.setValue(20)
                        spin.setReadOnly(True)
                    else:
                        if el in Wolke.Char.vorteileVariable:
                            spin.setValue(Wolke.Char.vorteileVariable[el])
                        else:
                            spin.setValue(Wolke.DB.vorteile[el].kosten)
                    spin.setSingleStep(20)
                    self.itemWidgets[el] = spin
                    spin.valueChanged.connect(lambda state, name=el: self.spinnerChanged(name,state))
                    self.uiVor.treeWidget.setItemWidget(child,1,spin)
                else:
                    child.setText(1, str(Wolke.DB.vorteile[el].kosten) + " EP")
                if Wolke.Char.voraussetzungenPrüfen(Wolke.DB.vorteile[el].voraussetzungen):
                    child.setHidden(False)
                else:
                    child.setHidden(True)
        self.updateInfo()
        self.uiVor.treeWidget.blockSignals(False)
项目:Sephrasto    作者:Aeolitus    | 项目源码 | 文件源码
def __init__(self,waffe=None):
        super().__init__()
        if Wolke.Debug:
            print("Initializing WaffenPicker...")
        self.waffe = None
        if waffe is not None and waffe in Wolke.DB.waffen:
            self.current = waffe
        else:
            self.current = ""
        self.Form = QtWidgets.QDialog()
        self.ui = CharakterWaffen.Ui_Dialog()
        self.ui.setupUi(self.Form)

        self.Form.setWindowFlags(
                QtCore.Qt.Window |
                QtCore.Qt.CustomizeWindowHint |
                QtCore.Qt.WindowTitleHint |
                QtCore.Qt.WindowCloseButtonHint)

        if Wolke.Debug:
            print("Ui is Setup...")
        currSet = self.current != ""
        for kind in Definitionen.Kampftalente:
            parent = QtWidgets.QTreeWidgetItem(self.ui.treeWeapons)
            parent.setText(0,kind)
            parent.setText(1,"")
            parent.setExpanded(True)
            wafs = []
            for waf in Wolke.DB.waffen:
                if Wolke.DB.waffen[waf].fertigkeit == kind:
                    wafs.append(waf)
            wafs.sort()
            for el in wafs:
                if not currSet:
                    self.current = el
                    currSet = True
                child = QtWidgets.QTreeWidgetItem(parent)
                child.setText(0,el)
                child.setText(1,Wolke.DB.waffen[el].talent)  
        self.ui.treeWeapons.sortItems(1,QtCore.Qt.AscendingOrder)
        if Wolke.Debug:
            print("Tree Filled...")
        self.ui.treeWeapons.itemSelectionChanged.connect(self.changeHandler)
        self.ui.treeWeapons.header().setSectionResizeMode(0,1)
        self.updateInfo()
        if Wolke.Debug:
            print("Info Updated...")
        self.Form.setWindowModality(QtCore.Qt.ApplicationModal)
        self.Form.show()
        self.ret = self.Form.exec_()
        if self.ret == QtWidgets.QDialog.Accepted and self.current != '':
            self.waffe = Wolke.DB.waffen[self.current]
        else:
            self.waffe = None
项目:gpvdm    作者:roderickmackenzie    | 项目源码 | 文件源码
def update(self):
        self.tab.clear()

        param_list=[]
        tf_list=[]

        files,true_false=self.from_file()
        param_list.extend(files)
        tf_list.extend(true_false)

        files,true_false=self.scan_dir("snapshots")
        param_list.extend(files)
        tf_list.extend(true_false)

        files,true_false=self.scan_dir("light_dump")
        param_list.extend(files)
        tf_list.extend(true_false)

        files,true_false=self.scan_dir("dynamic")
        param_list.extend(files)
        tf_list.extend(true_false)

        files,true_false=self.scan_dir("solver")
        param_list.extend(files)
        tf_list.extend(true_false)

        files,true_false=self.scan_dir("equilibrium")
        param_list.extend(files)
        tf_list.extend(true_false)

        files,true_false=self.scan_root_dir()
        param_list.extend(files)
        tf_list.extend(true_false)

        root = QTreeWidgetItem(self.tab, [_("Output files")])
        root.setExpanded(True)

        #param_list=scan_items_get_list()
        i=0
        for item in range(0, len(param_list)):
            div_str=param_list[item].replace("\\", "/")
            div_str=div_str.split("/")
            piter=None
            self.make_entry(root,div_str,tf_list[item])
项目:unist_bb_downloader    作者:kcm4482    | 项目源码 | 文件源码
def handleCourseChange(self, item, column):
        if item == self.total_item:
            return
        if item.checkState(column) == QtCore.Qt.Checked:
            l = self.fileTree.findItems(item.text(0), QtCore.Qt.MatchExactly)
            if l == []:
                for _course in self.account.course_list:
                    if _course.name == item.text(0):
                        course = _course
                        break

                course_item = QtWidgets.QTreeWidgetItem(self.fileTree)
                course_item.setFlags(item.flags() | QtCore.Qt.ItemIsTristate | QtCore.Qt.ItemIsUserCheckable)
                course_item.setText(0, course.name)
                size = self.getSizeUnit(course.size)
                course_item.setText(1, size)
                course_item.setText(2, course.file_path)
                course_item.setCheckState(0, QtCore.Qt.Checked)
                course_item.setExpanded(True)
                for menu in course:
                    menu_item = QtWidgets.QTreeWidgetItem(course_item)
                    menu_item.setFlags(menu_item.flags() | QtCore.Qt.ItemIsTristate | QtCore.Qt.ItemIsUserCheckable)
                    menu_item.setText(0, menu.name)
                    size = self.getSizeUnit(menu.size)
                    menu_item.setText(1, size)
                    menu_item.setText(2, menu.file_path)
                    menu_item.setCheckState(0, QtCore.Qt.Checked)
                    for myfile in menu:
                        if isinstance(myfile, myfunc.FileList):
                            filelist_item = QtWidgets.QTreeWidgetItem(menu_item)
                            filelist_item.setFlags(filelist_item.flags() | QtCore.Qt.ItemIsTristate | QtCore.Qt.ItemIsUserCheckable)
                            filelist_item.setText(0, myfile.name)
                            size = self.getSizeUnit(myfile.size)
                            filelist_item.setText(1, size)
                            filelist_item.setText(2, myfile.file_path)
                            filelist_item.setCheckState(0, QtCore.Qt.Checked)
                            self.addFileListItem(filelist_item, myfile)
                            continue
                        file_item = QtWidgets.QTreeWidgetItem(menu_item)
                        file_item.setFlags(file_item.flags() | QtCore.Qt.ItemIsUserCheckable)
                        file_item.setText(0, myfile.name)
                        size = self.getSizeUnit(myfile.size)
                        file_item.setText(1, size)
                        file_item.setText(2, myfile.file_path)
                        file_item.setCheckState(0, QtCore.Qt.Checked)

            else:
                l[0].setCheckState(0, QtCore.Qt.Checked)
        elif item.checkState(column) == QtCore.Qt.Unchecked:
            l = self.fileTree.findItems(item.text(0), QtCore.Qt.MatchExactly)
            if l != []:
                l[0].setCheckState(0, QtCore.Qt.Unchecked)
                item.parent().removeChild(l[0])
项目:idasec    作者:RobinDavid    | 项目源码 | 文件源码
def update_instruction_informations(self, new_item, _):
        index = self.traces_tab.currentIndex()
        try:
            table = self.index_map[index]
            trace = self.core.traces[self.id_map[index]]
            offset = int(table.item(new_item.row(), 0).text())
            inst = trace.instrs[offset]

            # === Gui stuff
            self.reads_view.clear()
            self.writes_view.clear()
            self.additional_infos.clear()
            for r_w, name, value in inst.registers:
                val_s = hex(value)[:-1] if hex(value).endswith('L') else hex(value)
                infos = [name, val_s]
                widget = QtWidgets.QTreeWidgetItem(infos)
                if r_w == "R":
                    self.reads_view.addTopLevelItem(widget)
                else:
                    self.writes_view.addTopLevelItem(widget)
            for r_w, addr, value in inst.memories:
                infos = ["@[%x]" % addr, "".join("{:02x}".format(ord(c)) for c in value)]
                widget = QtWidgets.QTreeWidgetItem(infos)
                if r_w == "R":
                    self.reads_view.addTopLevelItem(widget)
                else:
                    self.writes_view.addTopLevelItem(widget)
            for i in range(self.reads_view.topLevelItemCount()):
                self.reads_view.resizeColumnToContents(i)
            for i in range(self.writes_view.topLevelItemCount()):
                self.writes_view.resizeColumnToContents(i)

            if inst.nextaddr is not None:
                self.additional_infos.setHtml("Next addr:<bold>"+hex(inst.nextaddr)[:-1]+"</bold>")
            if inst.wave is not None:
                self.additional_infos.append("Wave: "+str(inst.wave))
            if inst.syscall is not None:
                self.additional_infos.append("Syscall:"+str(inst.syscall.id))
            if inst.libcall is not None:
                c = inst.libcall
                s = "Libcall:<span style='color:blue;'>"+str(c.func_name)+"</span>"
                s += "<ul><li>at:"+hex(c.func_addr)[:-1]+"</li>"
                s += "<li>traced: <span style='color:" + ("blue" if c.is_traced else "red")+";'>" + \
                     str(c.is_traced)+"</span></li></ul>"
                self.additional_infos.append(s)
            if inst.comment is not None:
                self.additional_infos.append("Comment:"+inst.comment)
        except ValueError:
            pass
        except KeyError:
            pass