Exemplo n.º 1
1
 def setModified(self, item: QTreeWidgetItem, modified: bool):
     f = item.font(0)
     f.setItalic(modified)
     item.setFont(0, f)
     item.setFont(1, f)
     f.setBold(modified)
     item.setFont(2, f)
    def generate_tree_model(self, data_dict):
        """Generate a tree model for specified dictionary

        :param data_dict: A dictionary
        :type data_dict: dict
        :return: list of QTreeWidgetItem
        :rtype list:
        """
        widget_items = []
        font = QFont()
        font.setBold(True)
        for key in data_dict.keys():
            entry = data_dict[key]
            key_item = QTreeWidgetItem()
            key_item.setText(0, str(key))
            key_item.setFont(0, font)
            if isinstance(entry, dict):
                items = self.generate_tree_model(entry)
                key_item.addChildren(items)
            else:
                # value_item = QTreeWidgetItem()
                key_item.setText(1, str(entry))
                key_item.setFlags(key_item.flags() | Qt.ItemIsEditable)
                # key_item.addChild(key_item)
            widget_items.append(key_item)

        return widget_items
Exemplo n.º 3
0
 def _loadCardGroup( self, groupName, records, parent = None ):
     if ( not groupName ):
         groupName = 'None'
     
     cards  = self.cardWidget()
     factory = self.factory()
     
     # create the group item
     group_item = QTreeWidgetItem(parent, [groupName])
     font = group_item.font(0)
     font.setBold(True)
     font.setPointSize(font.pointSize() + 2)
     group_item.setFont(0, font)
     group_item.setFlags(Qt.ItemIsEnabled)
     
     # load sub-groups
     if ( type(records) == dict ):
         for subgroup, records in sorted(records.items()):
             self._loadCardGroup(subgroup, records, group_item)
     else:
         for record in records:
             widget = factory.createCard(cards, record)
             if ( not widget ):
                 continue
             
             widget.adjustSize()
             
             # create the card item
             item = QTreeWidgetItem(group_item)
             item.setSizeHint(0, QSize(0, widget.height()))
             cards.setItemWidget(item, 0, widget)
     
     group_item.setExpanded(True)
Exemplo n.º 4
0
 def _set_root_path_message(self, message):
     self.clear()
     base_item = QTreeWidgetItem([message])
     font = base_item.font(0)
     font.setItalic(True)
     base_item.setFont(0, font)
     self.addTopLevelItem(base_item)
Exemplo n.º 5
0
    def fillTreeWidget(self):
        """ Заполняем tree widget записями, на основе разбиения на категории"""
        self._loadingData = True
        self._ui.twEntries.clear()
        for key in self._categories:
            self._categories[key] = sorted(self._categories[key], key=attrgetter('title'))
            item = DateTreeWidgetItem(self._ui.twEntries)
            font = item.font(0)
            font.setPointSize(11)
            font.setBold(True)
            item.setFont(0, font)
            if settings.showEntryCountInCategory():
                item.setText(0, "{} ({})".format(key, len(self._categories[key])))
            else:
                item.setText(0, key)
            item.setData(0, Qt.UserRole, self._keyForCategory[key])
            for e in self._categories[key]:
                entryItem = QTreeWidgetItem(item)
                font = entryItem.font(0)
                font.setPointSize(12)
                entryItem.setCheckState(0, Qt.Checked if e.interesting else Qt.Unchecked)
                entryItem.setText(0, e.title)
                entryItem.setFont(0, font)
                entryItem.setData(0, Qt.UserRole, e.id)
                self._setToolTipForItem(e, entryItem)

        self._ui.twEntries.sortItems(0, Qt.AscendingOrder)
        self._ui.twEntries.expandAll()
        self._loadingData = False
Exemplo n.º 6
0
    def _loadCardGroup(self, groupName, records, parent=None):
        if (not groupName):
            groupName = 'None'

        cards = self.cardWidget()
        factory = self.factory()

        # create the group item
        group_item = QTreeWidgetItem(parent, [groupName])
        font = group_item.font(0)
        font.setBold(True)
        font.setPointSize(font.pointSize() + 2)
        group_item.setFont(0, font)
        group_item.setFlags(Qt.ItemIsEnabled)

        # load sub-groups
        if (type(records) == dict):
            for subgroup, records in sorted(records.items()):
                self._loadCardGroup(subgroup, records, group_item)
        else:
            for record in records:
                widget = factory.createCard(cards, record)
                if (not widget):
                    continue

                widget.adjustSize()

                # create the card item
                item = QTreeWidgetItem(group_item)
                item.setSizeHint(0, QSize(0, widget.height()))
                cards.setItemWidget(item, 0, widget)

        group_item.setExpanded(True)
Exemplo n.º 7
0
    def generate_tree_model(self, data_dict):
        """Generate a tree model for specified dictionary

        :param data_dict: A dictionary
        :type data_dict: dict
        :return: list of QTreeWidgetItem
        :rtype list:
        """
        widget_items = []
        font = QFont()
        font.setBold(True)
        for key in data_dict.keys():
            entry = data_dict[key]
            key_item = QTreeWidgetItem()
            key_item.setText(0, str(key))
            key_item.setFont(0, font)
            if isinstance(entry, dict):
                items = self.generate_tree_model(entry)
                key_item.addChildren(items)
            else:
                # value_item = QTreeWidgetItem()
                key_item.setText(1, str(entry))
                key_item.setFlags(key_item.flags() | Qt.ItemIsEditable)
                # key_item.addChild(key_item)
            widget_items.append(key_item)

        return widget_items
Exemplo n.º 8
0
 def create_views_node(self, root_node, views):
     children = []
     title_node = QTreeWidgetItem(root_node, 0)
     title_node.setText(0, QApplication.translate("EntityDependencies", "Views"))
     title_node.setFont(0, self.title_font())
     for view in views:
         node = QTreeWidgetItem(title_node, 0)
         node.setText(0, view)
         children.append(node)
     return children
Exemplo n.º 9
0
 def createItem(self, name, description):
     """ Create a new item. """
     item = QTreeWidgetItem(self.treeWidget)
     item.groupName = name
     item.setFont(0, QFont("monospace"))
     item.setText(0, name)
     item.setText(1, description)
     item.setText(2, self.manager.shortcutText(name))
     item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled)
     return item
Exemplo n.º 10
0
 def create_entities_node(self, root_node, entities):
     children = []
     title_node = QTreeWidgetItem(root_node, 0)
     title_node.setText(0, QApplication.translate("EntityDependencies", "Entities"))
     title_node.setFont(0, self.title_font())
     for entity in entities:
         node = QTreeWidgetItem(title_node, 0)
         node.setText(0, entity)
         children.append(node)
     return children
Exemplo n.º 11
0
class TaskItem(Base):
    __tablename__ = 'tasks'

    id = Column(Integer, primary_key=True)
    task = Column(String)
    priority = Column(Integer)
    description = Column(String)
    complete = Column(Integer)
    date = Column(Date)

    def __init__(self, task, priority, description, complete, date):
        self.task = task
        self.priority = priority
        self.description = description
        self.complete = complete
        self.date = date
        #self.id = id
        

    def makeWidget(self):
        self.treeWidget = QTreeWidgetItem()
        timeleft = int((self.date - datetime.date.today()).days)
        weekday = self.date.strftime("%A")

        if self.complete:
            sofont = QtGui.QFont()
            font = QtGui.QFont()
            sofont.setStrikeOut(1)
            self.treeWidget.setFont(0, sofont)
    
        self.treeWidget.setData(0, 0, self.task)
        self.treeWidget.setData(1, 0, self.priority)
        self.treeWidget.setData(3, 0, self.id)
        
        if timeleft <2:
            pass
        elif timeleft >1 and timeleft <=7:
            self.treeWidget.setData(2, 0, str(weekday))
        else:
            self.treeWidget.setData(2, 0, str(self.date))

        self.treeWidget.setCheckState(0, self.complete)

        return self.treeWidget

    def timeLeft(self):
        return (self.date - datetime.date.today()).days
    def getCompleted(self):
        return self.complete
    def getWidget(self):
        return self.treeWidget

    def __repr__(self):
        return self.task
Exemplo n.º 12
0
 def create_entities_node(self, root_node, entities):
     children = []
     title_node = QTreeWidgetItem(root_node, 0)
     title_node.setText(
         0, QApplication.translate("EntityDependencies", "Entities"))
     title_node.setFont(0, self.title_font())
     for entity in entities:
         node = QTreeWidgetItem(title_node, 0)
         node.setText(0, entity)
         children.append(node)
     return children
Exemplo n.º 13
0
 def create_views_node(self, root_node, views):
     children = []
     title_node = QTreeWidgetItem(root_node, 0)
     title_node.setText(
         0, QApplication.translate("EntityDependencies", "Views"))
     title_node.setFont(0, self.title_font())
     for view in views:
         node = QTreeWidgetItem(title_node, 0)
         node.setText(0, view)
         children.append(node)
     return children
Exemplo n.º 14
0
    def populate_classified_values(self, unassigned_values, assigned_values,
                                   default_classes):
        """Populate lstUniqueValues and treeClasses.from the parameters.

        :param unassigned_values: List of values that haven't been assigned
            to a class. It will be put in self.lstUniqueValues.
        :type unassigned_values: list

        :param assigned_values: Dictionary with class as the key and list of
            value as the value of the dictionary. It will be put in
            self.treeClasses.
        :type assigned_values: dict

        :param default_classes: Default classes from unit.
        :type default_classes: list
        """
        # Populate the unique values list
        self.lstUniqueValues.clear()
        self.lstUniqueValues.setSelectionMode(
            QAbstractItemView.ExtendedSelection)
        for value in unassigned_values:
            value_as_string = value is not None and unicode(value) or 'NULL'
            list_item = QListWidgetItem(self.lstUniqueValues)
            list_item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable
                               | Qt.ItemIsDragEnabled)
            list_item.setData(Qt.UserRole, value)
            list_item.setText(value_as_string)
            self.lstUniqueValues.addItem(list_item)
        # Populate assigned values tree
        self.treeClasses.clear()
        self.treeClasses.invisibleRootItem().setFlags(Qt.ItemIsEnabled)
        for default_class in default_classes:
            # Create branch for class
            tree_branch = QTreeWidgetItem(self.treeClasses)
            tree_branch.setFlags(Qt.ItemIsDropEnabled | Qt.ItemIsEnabled)
            tree_branch.setExpanded(True)
            tree_branch.setFont(0, bold_font)
            if 'name' in default_class:
                default_class_name = default_class['name']
            else:
                default_class_name = default_class['key']
            tree_branch.setText(0, default_class_name)
            tree_branch.setData(0, Qt.UserRole, default_class['key'])
            if 'description' in default_class:
                tree_branch.setToolTip(0, default_class['description'])
            # Assign known values
            for value in assigned_values[default_class['key']]:
                string_value = value is not None and unicode(value) or 'NULL'
                tree_leaf = QTreeWidgetItem(tree_branch)
                tree_leaf.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable
                                   | Qt.ItemIsDragEnabled)
                tree_leaf.setData(0, Qt.UserRole, value)
                tree_leaf.setText(0, string_value)
Exemplo n.º 15
0
    def addApplet(self, app):
        assert isinstance(
            app, Applet), "Applets must inherit from Applet base class."
        assert app.base_initialized, "Applets must call Applet.__init__ upon construction."

        assert issubclass(
            type(app.gui), AppletGuiInterface
        ), "Applet GUIs must conform to the Applet GUI interface."

        self._applets.append(app)
        applet_index = len(self._applets) - 1
        self.appletStack.addWidget(app.gui.centralWidget())

        # Viewer controls are optional. If the applet didn't provide one, create an empty widget for him.
        if app.gui.viewerControlWidget() is None:
            self.viewerControlStack.addWidget(QWidget(parent=self))
        else:
            self.viewerControlStack.addWidget(app.gui.viewerControlWidget())

        # Add rows to the applet bar model
        rootItem = self.appletBar.invisibleRootItem()

        # Add all of the applet bar's items to the toolbox widget
        for controlName, controlGuiItem in app.gui.appletDrawers():
            appletNameItem = QTreeWidgetItem(self.appletBar,
                                             QtCore.QStringList(controlName))
            appletNameItem.setFont(0, QFont("Ubuntu", 14))
            drawerItem = QTreeWidgetItem(appletNameItem)
            drawerItem.setSizeHint(0, controlGuiItem.frameSize())
            #            drawerItem.setBackground( 0, QBrush( QColor(224, 224, 224) ) )
            #            drawerItem.setForeground( 0, QBrush( QColor(0,0,0) ) )
            self.appletBar.setItemWidget(drawerItem, 0, controlGuiItem)

            # Since each applet can contribute more than one applet bar item,
            #  we need to keep track of which applet this item is associated with
            self.appletBarMapping[rootItem.childCount() - 1] = applet_index

        # Set up handling of GUI commands from this applet
        app.guiControlSignal.connect(
            bind(self.handleAppletGuiControlSignal, applet_index))
        self._disableCounts.append(0)
        self._controlCmds.append([])

        # Set up handling of progress updates from this applet
        self.progressDisplayManager.addApplet(applet_index, app)

        # Set up handling of shell requests from this applet
        app.shellRequestSignal.connect(
            partial(self.handleShellRequest, applet_index))

        self.projectManager.addApplet(app)

        return applet_index
Exemplo n.º 16
0
    def show_termins_in_list(self, page):
        self.currentPage = page
        # фильтрация списка терминов
        search_word = self.searchLineEdit.text()
        if search_word.strip() != '':
            search_str = search_word
        else:
            search_str = ''

        # показ уже обработанных терминов
        if self.showLinkedCheck.isChecked():
            show_linked = 1
        else:
            show_linked = 0

        query = QSqlQuery(self.local_cn)
        LIMIT = int(self.terminsPerPageComboBos.currentText())
        OFFSET = (page - 1) * LIMIT
        query.prepare(show_termins_in_list_query)
        query.bindValue(':search_str', search_str + '%')
        query.bindValue(':linked', show_linked)
        query.bindValue(':limit', LIMIT.__str__())
        query.bindValue(':offset', OFFSET.__str__())
        if query.exec_():
            self.root.takeChildren()
            i = 1
            f = QFont()
            f.setBold(True)
            while query.next():
                c = QTreeWidgetItem()
                c.setText(0, query.value(0))  # Заглавное слово
                c.setData(1, 0, query.value(1))  # uuid
                c.setData(2, 0, i)  # номерок
                if query.value(2) == 1:
                    c.setFont(0, f)
                self.root.addChild(c)
                i += 1

            pages = 1
            query.prepare(show_termins_in_list_count_query)
            query.bindValue(':search_str', search_str + '%')
            query.bindValue(':linked', show_linked)
            if query.exec_() and query.next():
                try:
                    pages = math.ceil(query.value(0) / LIMIT)
                except:
                    pages = 1

            self.draw_paginator(pages, page)
        else:
            print(query.lastError().text())
            print("not exec")
        self.terminsTreeWidget.scrollToTop()
Exemplo n.º 17
0
    def createSeparatorItem(self):
        """
        Creates a new separator item.
        
        :return     <QTreeWidgetItem>
        """
        item = QTreeWidgetItem(['                                    '])
        font = item.font(0)
        font.setStrikeOut(True)
        item.setFont(0, font)
        item.setData(0, Qt.UserRole, qt.wrapVariant('separator'))
        flags = item.flags()
        flags ^= Qt.ItemIsDropEnabled
        item.setFlags(flags)

        return item
Exemplo n.º 18
0
 def createSeparatorItem( self ):
     """
     Creates a new separator item.
     
     :return     <QTreeWidgetItem>
     """
     item = QTreeWidgetItem(['                                    '])
     font = item.font(0)
     font.setStrikeOut(True)
     item.setFont(0, font)
     item.setData(0, Qt.UserRole, qt.wrapVariant('separator'))
     flags = item.flags()
     flags ^= Qt.ItemIsDropEnabled
     item.setFlags(flags)
     
     return item
Exemplo n.º 19
0
    def addApplet( self, app ):
        assert isinstance( app, Applet ), "Applets must inherit from Applet base class."
        assert app.base_initialized, "Applets must call Applet.__init__ upon construction."

        assert issubclass( type(app.gui), AppletGuiInterface ), "Applet GUIs must conform to the Applet GUI interface."
        
        self._applets.append(app)
        applet_index = len(self._applets) - 1
        self.appletStack.addWidget( app.gui.centralWidget() )
        
        # Viewer controls are optional. If the applet didn't provide one, create an empty widget for him.
        if app.gui.viewerControlWidget() is None:
            self.viewerControlStack.addWidget( QWidget(parent=self) )
        else:
            self.viewerControlStack.addWidget( app.gui.viewerControlWidget() )

        # Add rows to the applet bar model
        rootItem = self.appletBar.invisibleRootItem()

        # Add all of the applet bar's items to the toolbox widget
        for controlName, controlGuiItem in app.gui.appletDrawers():
            appletNameItem = QTreeWidgetItem( self.appletBar, QtCore.QStringList( controlName ) )
            appletNameItem.setFont( 0, QFont("Ubuntu", 14) )
            drawerItem = QTreeWidgetItem(appletNameItem)
            drawerItem.setSizeHint( 0, controlGuiItem.frameSize() )
#            drawerItem.setBackground( 0, QBrush( QColor(224, 224, 224) ) )
#            drawerItem.setForeground( 0, QBrush( QColor(0,0,0) ) )
            self.appletBar.setItemWidget( drawerItem, 0, controlGuiItem )

            # Since each applet can contribute more than one applet bar item,
            #  we need to keep track of which applet this item is associated with
            self.appletBarMapping[rootItem.childCount()-1] = applet_index

        # Set up handling of GUI commands from this applet
        app.guiControlSignal.connect( bind(self.handleAppletGuiControlSignal, applet_index) )
        self._disableCounts.append(0)
        self._controlCmds.append( [] )

        # Set up handling of progress updates from this applet
        self.progressDisplayManager.addApplet(applet_index, app)
        
        # Set up handling of shell requests from this applet
        app.shellRequestSignal.connect( partial(self.handleShellRequest, applet_index) )

        self.projectManager.addApplet(app)
                
        return applet_index
Exemplo n.º 20
0
    def __init__(self, parent=None):
        super(XFontPickerWidget, self).__init__(parent)

        # load the user interface
        projexui.loadUi(__file__, self)

        # define custom properties
        database = QFontDatabase()
        for family in sorted(database.families()):
            item = QTreeWidgetItem(self.uiFontTREE, [family])
            item.setFont(0, QFont(family))

        # set default properties

        # create connections
        self.uiSizeSPN.valueChanged.connect(self.setPointSize)
        self.uiFontTREE.itemDoubleClicked.connect(self.accepted)
Exemplo n.º 21
0
 def __init__( self, parent = None ):
     super(XFontPickerWidget, self).__init__( parent )
     
     # load the user interface
     projexui.loadUi(__file__, self)
     
     # define custom properties
     database = QFontDatabase()
     for family in sorted(database.families()):
         item = QTreeWidgetItem(self.uiFontTREE, [family])
         item.setFont(0, QFont(family))
     
     # set default properties
     
     # create connections
     self.uiSizeSPN.valueChanged.connect(self.setPointSize)
     self.uiFontTREE.itemDoubleClicked.connect(self.accepted)
Exemplo n.º 22
0
 def createTreeItem(self, object):
     icon = object.getIcon()
     label = object.formatID()
     tree = QTreeWidgetItem([label])
     tree.setData(0, Qt.UserRole, QVariant(object['id']))
     tooltip = object.getToolTip()
     if tooltip:
         tree.setToolTip(0, tooltip)
     if icon:
         tree.setIcon(0, QIcon(icon))
     font = tree.font(0)
     if object['editable']:
         font.setBold(True)
     if not object['references']:
         font.setItalic(True)
     tree.setFont(0, font)
     if not object['editable']:
         unsetFlag(tree, Qt.ItemIsEditable)
     return tree
 def __createEntry(self, description, entryText, entryVersion):
     """
     Private method to generate a program entry.
     
     @param description descriptive text (string or QString)
     @param entryText text to show (string or QString)
     @param entryVersion version string to show (string or QString).
     """
     itm = QTreeWidgetItem(self.programsList, QStringList(description))
     font = itm.font(0)
     font.setBold(True)
     itm.setFont(0, font)
     
     if len(entryVersion):
         itm2 = QTreeWidgetItem(itm, QStringList() << entryText << entryVersion)
         itm.setExpanded(True)
     else:
         itm.setText(1, self.trUtf8("(not found)"))
     QApplication.processEvents()
     self.programsList.header().resizeSections(QHeaderView.ResizeToContents)
     self.programsList.header().setStretchLastSection(True)
Exemplo n.º 24
0
    def _populate_reporting_tab(self):
        """Populate trees about layers."""
        self.tree.clear()
        self.add_layer.setEnabled(False)
        self.remove_layer.setEnabled(False)
        self.move_up.setEnabled(False)
        self.move_down.setEnabled(False)
        self.tree.setColumnCount(1)
        self.tree.setRootIsDecorated(False)
        self.tree.setHeaderHidden(True)

        analysis_branch = QTreeWidgetItem(self.tree.invisibleRootItem(),
                                          [FROM_ANALYSIS['name']])
        analysis_branch.setFont(0, bold_font)
        analysis_branch.setExpanded(True)
        analysis_branch.setFlags(Qt.ItemIsEnabled)

        if self._multi_exposure_if:
            expected = self._multi_exposure_if.output_layers_expected()
            for group, layers in expected.iteritems():
                group_branch = QTreeWidgetItem(analysis_branch, [group])
                group_branch.setFont(0, bold_font)
                group_branch.setExpanded(True)
                group_branch.setFlags(Qt.ItemIsEnabled)

                for layer in layers:
                    layer = definition(layer)
                    if layer.get('allowed_geometries', None):
                        item = QTreeWidgetItem(group_branch,
                                               [layer.get('name')])
                        item.setData(0, LAYER_ORIGIN_ROLE,
                                     FROM_ANALYSIS['key'])
                        item.setData(0, LAYER_PARENT_ANALYSIS_ROLE, group)
                        item.setData(0, LAYER_PURPOSE_KEY_OR_ID_ROLE,
                                     layer['key'])
                        item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)

        canvas_branch = QTreeWidgetItem(self.tree.invisibleRootItem(),
                                        [FROM_CANVAS['name']])
        canvas_branch.setFont(0, bold_font)
        canvas_branch.setExpanded(True)
        canvas_branch.setFlags(Qt.ItemIsEnabled)

        # List layers from the canvas
        loaded_layers = QgsMapLayerRegistry.instance().mapLayers().values()
        canvas_layers = self.iface.mapCanvas().layers()
        flag = setting('visibleLayersOnlyFlag', expected_type=bool)
        for loaded_layer in loaded_layers:
            if flag and loaded_layer not in canvas_layers:
                continue

            title = loaded_layer.name()
            item = QTreeWidgetItem(canvas_branch, [title])
            item.setData(0, LAYER_ORIGIN_ROLE, FROM_CANVAS['key'])
            item.setData(0, LAYER_PURPOSE_KEY_OR_ID_ROLE, loaded_layer.id())
            item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)

        self.tree.resizeColumnToContents(0)
Exemplo n.º 25
0
    def display(self):
        '''
        Initialize top-level items
        '''
        if len(self.items) == 0:
            return

        self.tree.clear()

        #If there is only one item then set it as the root item
        if len(self.items) == 1:
            rootItem = self.items[0]

            #Set root font
            rtFont = rootItem.font(0)
            rtFont.setBold(True)
            rootItem.setFont(0, rtFont)

            #Add the tree item to the tree widget
            self.tree.addTopLevelItem(rootItem)
            rootItem.setExpanded(True)

        else:
            rootItem = QTreeWidgetItem(self.tree)
            rootItem.setText(0, self.title)
            rootItem.setIcon(0, QIcon(self.rootResource))

            #Set root font
            rtFont = rootItem.font(0)
            rtFont.setBold(True)
            rootItem.setFont(0, rtFont)

            rootItem.addChildren(self.items)
            rootItem.setExpanded(True)

        #Force the horizontal scrollbar to show
        self.tree.header().setResizeMode(QHeaderView.ResizeToContents)
Exemplo n.º 26
0
 def display(self):
     '''
     Initialize top-level items
     '''
     if len(self.items) == 0:
         return
 
     self.tree.clear()
     
     #If there is only one item then set it as the root item
     if len(self.items) == 1:
         rootItem = self.items[0]
         
         #Set root font
         rtFont = rootItem.font(0)
         rtFont.setBold(True)
         rootItem.setFont(0,rtFont)
         
         #Add the tree item to the tree widget
         self.tree.addTopLevelItem(rootItem)
         rootItem.setExpanded(True)
         
     else:
         rootItem = QTreeWidgetItem(self.tree)
         rootItem.setText(0,self.title)
         rootItem.setIcon(0,QIcon(self.rootResource))
         
         #Set root font
         rtFont = rootItem.font(0)
         rtFont.setBold(True)
         rootItem.setFont(0,rtFont)
         
         rootItem.addChildren(self.items)
         rootItem.setExpanded(True)
     
     #Force the horizontal scrollbar to show
     self.tree.header().setResizeMode(QHeaderView.ResizeToContents)
Exemplo n.º 27
0
def updatePacketDetails(treeWidget, packet):
	"""
	This function fills QTreeWidget with packet detailed information.
	"""
	#first remove all content
	fontBold = QFont()
	fontBold.setBold(True)
	
	treeWidget.clear()
	
	t = QTreeWidgetItem(treeWidget)
	t.setText(0, 'Reception time')
	t.setText(1, '%s:%s:%s.%s' % tuple(packet.time))
	
	if packet.isInvalid:
			return
	
	trInfo =  QTreeWidgetItem(treeWidget)
	trInfo.setText(0, 'Transmission info')
	trInfo.setText(1, 'CRC passed: %s,  LQI: %s,  RSSI: %s' % (packet.CRCOk, packet.LQI, packet.RSSI))
	
	PHY =  QTreeWidgetItem(treeWidget)
	PHY.setText(0, 'PHY fields')
	PHY.setFont(0, fontBold)

	frameLength = QTreeWidgetItem(PHY)
	frameLength.setText(0, 'Frame length')
	frameLength.setText(1, '%i' % len(packet.load))
	
	MAC =  QTreeWidgetItem(treeWidget)
	MAC.setText(0, 'MAC fields')
	MAC.setFont(0, fontBold)
	
	frameControl = QTreeWidgetItem(MAC)
	frameControl.setText(0, 'Frame control')
	frameControl.setText(1, packet.frameControl)
	
	frameType = QTreeWidgetItem(frameControl)
	frameType.setText(0, 'Frame Type')
	frameType.setText(1, packet.frameType)
	
	securityEnabled = QTreeWidgetItem(frameControl)
	securityEnabled.setText(0, 'Security enabled')
	securityEnabled.setText(1, packet.securityEnabled)
	
	framePending = QTreeWidgetItem(frameControl)
	framePending.setText(0, 'Frame pending')
	framePending.setText(1, packet.framePending)
	
	ackRequest = QTreeWidgetItem(frameControl)
	ackRequest.setText(0, 'Ack. request')
	ackRequest.setText(1, packet.ackRequest)
	
	intraPAN = QTreeWidgetItem(frameControl)
	intraPAN.setText(0, 'Intra-PAN')
	intraPAN.setText(1, packet.intraPAN)
	
	dstAddrMode = QTreeWidgetItem(frameControl)
	dstAddrMode.setText(0, 'Dest. addressing mode')
	dstAddrMode.setText(1, packet.dstAddrMode)
	
	srcAddrMode = QTreeWidgetItem(frameControl)
	srcAddrMode.setText(0, 'Source addressing mode')
	srcAddrMode.setText(1, packet.srcAddrMode)
	
	seqNumber = QTreeWidgetItem(MAC)
	seqNumber.setText(0, 'Sequence number')
	seqNumber.setText(1, packet.seqNumber)
	
	if hasattr(packet, 'dstPANID'):
		dstPANID = QTreeWidgetItem(MAC)
		dstPANID.setText(0, 'Destination PAN-ID')
		dstPANID.setText(1, packet.dstPANID)
	
	if hasattr(packet, 'dstAddr'):
		dstAddr = QTreeWidgetItem(MAC)
		dstAddr.setText(0, 'Destination address')
		dstAddr.setText(1, packet.dstAddr)
	
	if hasattr(packet, 'srcPANID'):
		srcPANID = QTreeWidgetItem(MAC)
		srcPANID.setText(0, 'Source PAN-ID')
		srcPANID.setText(1, packet.srcPANID)
		
	if hasattr(packet, 'srcAddr'):
		srcAddr = QTreeWidgetItem(MAC)
		srcAddr.setText(0, 'Source address')
		srcAddr.setText(1, packet.srcAddr)
		
	if hasattr(packet, 'payload'):
		payload = QTreeWidgetItem(MAC)
		payload.setText(0, 'Payload')
		payload.setText(1, packet.payload)
	
	if hasattr(packet, 'commandType'):
		commandType = QTreeWidgetItem(MAC)
		commandType.setText(0, 'Command type')
		commandType.setText(1, packet.commandType)
	
	if hasattr(packet, 'commandPayload'):
		commandPayload = QTreeWidgetItem(MAC)
		commandPayload.setText(0, 'Command payload')
		commandPayload.setText(1, packet.commandPayload)
	
	if hasattr(packet, 'superFrameSpec'):
		superFrameSpec = QTreeWidgetItem(MAC)
		superFrameSpec.setText(0, 'Superframe specification')
		superFrameSpec.setText(1, packet.superFrameSpec)
	
		beaconOrder = QTreeWidgetItem(superFrameSpec)
		beaconOrder.setText(0, 'Beacon order')
		beaconOrder.setText(1, packet.beaconOrder)
	
		superFrameOrder = QTreeWidgetItem(superFrameSpec)
		superFrameOrder.setText(0, 'Superframe order')
		superFrameOrder.setText(1, packet.superFrameOrder)
	
		finalCAPSlot = QTreeWidgetItem(superFrameSpec)
		finalCAPSlot.setText(0, 'finalCAPSlot')
		finalCAPSlot.setText(1, packet.finalCAPSlot)
	
		battLifeExt = QTreeWidgetItem(superFrameSpec)
		battLifeExt.setText(0, 'Batt. life extension')
		battLifeExt.setText(1, packet.battLifeExt)
	
		PANCoord = QTreeWidgetItem(superFrameSpec)
		PANCoord.setText(0, 'PAN Coordinator')
		PANCoord.setText(1, packet.PANCoord)
	
		assocPermit = QTreeWidgetItem(superFrameSpec)
		assocPermit.setText(0, 'Association permit')
		assocPermit.setText(1, packet.assocPermit)
	
	if hasattr(packet, 'GTS'):
		GTS = QTreeWidgetItem(MAC)
		GTS.setText(0, 'GTS specification')
		GTS.setText(1, packet.GTS)
	
		GTSDescrCount = QTreeWidgetItem(GTS)
		GTSDescrCount.setText(0, 'GTS descriptor count')
		GTSDescrCount.setText(1, packet.GTSDescrCount)
		
		GTSPermit = QTreeWidgetItem(GTS)
		GTSPermit.setText(0, 'GTS permit')
		GTSPermit.setText(1, packet.GTSPermit)
		
		if int(packet.GTSDescrCount, 16) > 0:
			GTSDirections = QTreeWidgetItem(GTS)
			GTSDirections.setText(0, 'GTS directions')
			GTSDirections.setText(1, packet.GTSDirections)
		
			GTSDescriptors = QTreeWidgetItem(GTS)
			GTSDescriptors.setText(0, 'GTS descriptors list')
			descriptors = []
			for i in xrange(int(packet.GTSDescrCount, 16)):
				descriptor = [QTreeWidgetItem(GTSDescriptors)] * 3
				descriptor[0].setText(0, 'Device short address')
				descriptor[0].setText(1, packet.GTSDescriptors[i].deviceShortAddr)
				descriptor[1].setText(0, 'GTS starting slot')
				descriptor[1].setText(1, packet.GTSDescriptors[i].GTSStartingSlot)
				descriptor[2].setText(0, 'GTS length')
				descriptor[3].setText(1, packet.GTSDescriptors[i].GTSLength)
				descriptors.append(descriptor)
		
		if int(packet.numShortAddrPnd, 16) > 0 or int(packet.numShortAddrPnd, 16) > 0:
			pendingAddr = QTreeWidgetItem(MAC)
			pendingAddr.setText(0, 'Pending addresses list')
			pndShort = []
			pndLong = []
			for i in xrange(int(packet.numShortAddrPnd, 16)):
				pndShort.append(QTreeWidgetItem(pendingAddr))
				pndShort[i].setText(0, 'Pending short addr. #%i' % i)
				pndShort[i].setText(1, packet.shortAddrPndList[i])
			for i in xrange(int(packet.numLongAddrPnd, 16)):
				pndLong.append(QTreeWidgetItem(pendingAddr))
				pndLong[i].setText(0, 'Pending long addr. #%i' % i)
				pndLong[i].setText(1, packet.longAddrPndList[i])
			
	if hasattr(packet, 'bcnPayload'):
		bcnPayload = QTreeWidgetItem(MAC)
		bcnPayload.setText(0, 'Beacon payload')
		bcnPayload.setText(1, packet.bcnPayload)
 def __createProgramEntry(self, description, exe,
                          versionCommand = "", versionStartsWith = "", 
                          versionPosition = 0, version = "",
                          versionCleanup = None, versionRe = None):
     """
     Private method to generate a program entry.
     
     @param description descriptive text (string or QString)
     @param exe name of the executable program (string)
     @param versionCommand command line switch to get the version info (string)
         if this is empty, the given version will be shown.
     @param versionStartsWith start of line identifying version info (string)
     @param versionPosition index of part containing the version info (integer)
     @keyparam version version string to show (string)
     @keyparam versionCleanup tuple of two integers giving string positions
         start and stop for the version string (tuple of integers)
     @keyparam versionRe regexp to determine the line identifying version 
         info (string). Takes precedence over versionStartsWith.
     @return version string of detected or given version (string)
     """
     itm = QTreeWidgetItem(self.programsList, QStringList(description))
     font = itm.font(0)
     font.setBold(True)
     itm.setFont(0, font)
     if not exe:
         itm.setText(1, self.trUtf8("(not configured)"))
     else:
         if os.path.isabs(exe):
             if not Utilities.isExecutable(exe):
                 exe = ""
         else:
             exe = Utilities.getExecutablePath(exe)
         if exe:
             if versionCommand and \
                (versionStartsWith != "" or \
                 (versionRe is not None and versionRe != "")) and \
                versionPosition:
                 proc = QProcess()
                 proc.setProcessChannelMode(QProcess.MergedChannels)
                 proc.start(exe, QStringList(versionCommand))
                 finished = proc.waitForFinished(10000)
                 if finished:
                     output = \
                         unicode(proc.readAllStandardOutput(), 
                                 str(Preferences.getSystem("IOEncoding")), 
                                 'replace')
                     if versionRe is None:
                         versionRe = "^%s" % re.escape(versionStartsWith)
                     versionRe = re.compile(versionRe, re.UNICODE)
                     for line in output.splitlines():
                         if versionRe.search(line):
                             try:
                                 version = line.split()[versionPosition]
                                 if versionCleanup:
                                     version = \
                                         version[versionCleanup[0]:versionCleanup[1]]
                                 break
                             except IndexError:
                                 version = self.trUtf8("(unknown)")
                 else:
                     version = self.trUtf8("(not executable)")
             itm2 = QTreeWidgetItem(itm, QStringList() << exe << version)
             itm.setExpanded(True)
         else:
             itm.setText(1, self.trUtf8("(not found)"))
     QApplication.processEvents()
     self.programsList.header().resizeSections(QHeaderView.ResizeToContents)
     self.programsList.header().setStretchLastSection(True)
     return version
Exemplo n.º 29
0
class ProfileWidget(QTreeWidget, object):
    """Profile Widget."""
    def __init__(self, data=None):
        """Constructor."""
        super(ProfileWidget, self).__init__()

        # Attributes
        self.widget_items = []
        # Set data
        if data:
            self.data = data
        # Set header
        self.header_tree_widget = QTreeWidgetItem(
            [tr('Classification'),
             tr('Affected'),
             tr('Displacement Rate')])
        header_font = QFont()
        header_font.setBold(True)
        header_font.setPointSize(14)
        self.header_tree_widget.setFont(0, header_font)
        self.header_tree_widget.setFont(1, header_font)
        self.header_tree_widget.setFont(2, header_font)
        self.setHeaderItem(self.header_tree_widget)
        self.header().setResizeMode(0, QHeaderView.Stretch)
        self.header().setResizeMode(1, QHeaderView.Fixed)
        self.header().setResizeMode(2, QHeaderView.ResizeToContents)
        self.header().setMovable(False)

    @property
    def data(self):
        """Get the data from the current state of widgets.

        :returns: Profile data in dictionary.
        :rtype: dict
        """
        if len(self.widget_items) == 0:
            return
        data = {}
        for hazard_item in self.widget_items:
            hazard = hazard_item.data(0, Qt.UserRole)
            data[hazard] = {}
            classification_items = [
                hazard_item.child(i) for i in range(hazard_item.childCount())
            ]
            for classification_item in classification_items:
                classification = classification_item.data(0, Qt.UserRole)
                data[hazard][classification] = OrderedDict()
                class_items = [
                    classification_item.child(i)
                    for i in range(classification_item.childCount())
                ]
                for the_class_item in class_items:
                    the_class = the_class_item.data(0, Qt.UserRole)
                    affected_check_box = self.itemWidget(the_class_item, 1)
                    displacement_rate_spin_box = self.itemWidget(
                        the_class_item, 2)
                    data[hazard][classification][the_class] = {
                        'affected': affected_check_box.isChecked(),
                        'displacement_rate':
                        displacement_rate_spin_box.value()
                    }
        return data

    @data.setter
    def data(self, profile_data):
        """Set data for the widget.

        :param profile_data: profile data.
        :type profile_data: dict

        It will replace the previous data.
        """
        default_profile = generate_default_profile()
        self.clear()
        for hazard in sorted(default_profile.keys()):
            classifications = default_profile[hazard]
            hazard_widget_item = QTreeWidgetItem()
            hazard_widget_item.setData(0, Qt.UserRole, hazard)
            hazard_widget_item.setText(0, get_name(hazard))
            for classification in sorted(classifications.keys()):
                # Filter out classification that doesn't support population.
                # TODO(IS): This is not the best place to put the filtering.
                # It's more suitable in the generate_default_profile method
                # in safe/definitions/utilities.
                classification_definition = definition(classification)
                supported_exposures = classification_definition.get(
                    'exposures', [])
                # Empty list means support all exposure
                if supported_exposures != []:
                    if exposure_population not in supported_exposures:
                        continue
                classes = classifications[classification]
                classification_widget_item = QTreeWidgetItem()
                classification_widget_item.setData(0, Qt.UserRole,
                                                   classification)
                classification_widget_item.setText(0, get_name(classification))
                hazard_widget_item.addChild(classification_widget_item)
                for the_class, the_value in classes.items():
                    the_class_widget_item = QTreeWidgetItem()
                    the_class_widget_item.setData(0, Qt.UserRole, the_class)
                    the_class_widget_item.setText(
                        0, get_class_name(the_class, classification))
                    classification_widget_item.addChild(the_class_widget_item)
                    # Adding widget must be happened after addChild
                    affected_check_box = QCheckBox(self)
                    # Set from profile_data if exist, else get default
                    profile_value = profile_data.get(hazard, {}).get(
                        classification, {}).get(the_class, the_value)

                    affected_check_box.setChecked(profile_value['affected'])
                    self.setItemWidget(the_class_widget_item, 1,
                                       affected_check_box)
                    displacement_rate_spinbox = PercentageSpinBox(self)
                    displacement_rate_spinbox.setValue(
                        profile_value['displacement_rate'])
                    displacement_rate_spinbox.setEnabled(
                        profile_value['affected'])
                    self.setItemWidget(the_class_widget_item, 2,
                                       displacement_rate_spinbox)
                    # Behaviour when the check box is checked
                    # noinspection PyUnresolvedReferences
                    affected_check_box.stateChanged.connect(
                        displacement_rate_spinbox.setEnabled)
            if hazard_widget_item.childCount() > 0:
                self.widget_items.append(hazard_widget_item)

        self.addTopLevelItems(self.widget_items)

        self.expandAll()

    def clear(self):
        """Clear method to clear the widget items and the tree widget."""
        super(ProfileWidget, self).clear()
        self.widget_items = []
Exemplo n.º 30
0
class LegendItem( QTreeWidgetItem ):
    """ Provide a widget to show and manage the properties of one single layer """
    def __init__( self, parent, canvasLayer ):
        QTreeWidgetItem.__init__( self )
        self.legend = parent
        self.canvasLayer = canvasLayer
        self.canvasLayer.layer().setLayerName( self.legend.normalizeLayerName( unicode( self.canvasLayer.layer().name() ) ) )
        self.setText( 0, self.canvasLayer.layer().name() )
        self.isVect = ( self.canvasLayer.layer().type() == 0 ) # 0: Vector, 1: Raster
        self.layerId = self.canvasLayer.layer().getLayerID()

        if self.isVect:
            geom = self.canvasLayer.layer().dataProvider().geometryType()

        self.setCheckState( 0, Qt.Checked )

        pm = QPixmap( 20, 20 )
        icon = QIcon()

        if self.isVect:
            if geom == 1 or geom == 4 or geom == 8 or geom == 11: # Point
                icon.addPixmap( QPixmap( resources_prefix + "mIconPointLayer.png" ), QIcon.Normal, QIcon.On)
            elif geom == 2 or geom == 5 or geom == 9 or geom == 12: # Polyline
                icon.addPixmap( QPixmap( resources_prefix + "mIconLineLayer.png"), QIcon.Normal, QIcon.On)
            elif geom == 3 or geom == 6 or geom == 10 or geom == 13: # Polygon
                icon.addPixmap( QPixmap( resources_prefix + "mIconPolygonLayer.png"), QIcon.Normal, QIcon.On)
            else: # Not a valid WKT Geometry
                geom = self.canvasLayer.layer().geometryType() # QGis Geometry
                if geom == 0: # Point
                    icon.addPixmap( QPixmap( resources_prefix + "mIconPointLayer.png" ), QIcon.Normal, QIcon.On)
                elif geom == 1: # Line
                    icon.addPixmap( QPixmap( resources_prefix + "mIconLineLayer.png"), QIcon.Normal, QIcon.On)
                elif geom == 2: # Polygon
                    icon.addPixmap( QPixmap( resources_prefix + "mIconPolygonLayer.png"), QIcon.Normal, QIcon.On)
                else:
                    raise RuntimeError, 'Unknown geometry: ' + str( geom )

            self.vectorLayerSymbology( self.canvasLayer.layer() )
        else:
            self.canvasLayer.layer().thumbnailAsPixmap( pm )
            icon.addPixmap( pm )
            self.child = QTreeWidgetItem( self )
            iconChild = QIcon()
            iconChild.addPixmap( self.canvasLayer.layer().legendAsPixmap().scaled( 15, 15, Qt.KeepAspectRatio ) )
            self.child.setSizeHint ( 0, QSize( 15, 15 ) )
            self.child.setIcon( 0, iconChild )

        self.setIcon( 0, icon )

        self.setToolTip( 0, self.canvasLayer.layer().publicSource() )
        layerFont = QFont()
        layerFont.setBold( True )
        self.setFont( 0, layerFont )

    def nextSibling( self ):
        """ Return the next layer item """
        return self.legend.nextSibling( self )

    def storeAppearanceSettings( self ):
        """ Store the appearance of the layer item """
        self.__itemIsExpanded = self.isExpanded()

    def restoreAppearanceSettings( self ):
        """ Restore the appearance of the layer item """
        self.setExpanded( self.__itemIsExpanded )

    def vectorLayerSymbology( self, layer ):
        itemList = [] # Simbology List

        # Add the new items
        lw = ''
        uv = ''
        label = ''
        renderer = layer.renderer()
        sym = renderer.symbols()

        for it in sym:
            img = QImage()
            if it.type() == QGis.Point:
                img = it.getPointSymbolAsImage( 4 ) # 4: A convenience scale
            elif it.type() == QGis.Line:
                img = it.getLineSymbolAsImage()
            else: #polygon
                img = it.getPolygonSymbolAsImage()

            values = ''
            lw = it.lowerValue()
            if not lw.isEmpty():
                values += lw

            uv = it.upperValue()
            if not uv.isEmpty():
                values += " - "
                values += uv

            label = it.label()
            if not label.isEmpty():
                values += " "
                values += label

            pix = QPixmap( 20, 20 )
            pix = QPixmap().fromImage( img )
            itemList.append( [ values, pix ] )

        self.changeSymbologySettings( layer, itemList )

    def changeSymbologySettings( self, theMapLayer, itemList ):
        if not theMapLayer:
            return

        # Remove previous symbology items
        self.takeChildren()

        # Add the name of classification field as the first symbology item
        renderer = theMapLayer.renderer()
        if renderer.name() == "Graduated Symbol" or \
            renderer.name() == "Unique Value":
            fields = theMapLayer.pendingFields()
            self.child = QTreeWidgetItem( self )
            self.child.setText( 0, fields[ renderer.classificationAttributes()[ 0 ] ].name() )
            childFont = QFont()
            childFont.setItalic( True )
            self.child.setFont( 0, childFont )

        # Add the new symbology items
        for i in range( len( itemList ) ):
            self.child = QTreeWidgetItem( self )
            self.child.setText( 0, unicode( itemList[ i ][ 0 ] ) )
            iconChild = QIcon()
            iconChild.addPixmap( itemList[ i ][ 1 ] )
            self.child.setIcon( 0, iconChild )

            childFont = QFont()
            childFont.setPointSize( 9 )
            self.child.setFont( 0, childFont )
    def populate_classified_values(
            unassigned_values, assigned_values, default_classes,
            list_unique_values, tree_mapping_widget):
        """Populate lstUniqueValues and treeClasses.from the parameters.

        :param unassigned_values: List of values that haven't been assigned
            to a class. It will be put in list_unique_values.
        :type unassigned_values: list

        :param assigned_values: Dictionary with class as the key and list of
            value as the value of the dictionary. It will be put in
            tree_mapping_widget.
        :type assigned_values: dict

        :param default_classes: Default classes from unit.
        :type default_classes: list

        :param list_unique_values: List Widget for unique values
        :type list_unique_values: QListWidget

        :param tree_mapping_widget: Tree Widget for classifying.
        :type tree_mapping_widget: QTreeWidget
        """
        # Populate the unique values list
        list_unique_values.clear()
        list_unique_values.setSelectionMode(
            QAbstractItemView.ExtendedSelection)
        for value in unassigned_values:
            value_as_string = value is not None and unicode(value) or 'NULL'
            list_item = QListWidgetItem(list_unique_values)
            list_item.setFlags(
                Qt.ItemIsEnabled |
                Qt.ItemIsSelectable |
                Qt.ItemIsDragEnabled)
            list_item.setData(Qt.UserRole, value)
            list_item.setText(value_as_string)
            list_unique_values.addItem(list_item)
        # Populate assigned values tree
        tree_mapping_widget.clear()
        bold_font = QFont()
        bold_font.setItalic(True)
        bold_font.setBold(True)
        bold_font.setWeight(75)
        tree_mapping_widget.invisibleRootItem().setFlags(
            Qt.ItemIsEnabled)
        for default_class in default_classes:
            # Create branch for class
            tree_branch = QTreeWidgetItem(tree_mapping_widget)
            tree_branch.setFlags(
                Qt.ItemIsDropEnabled | Qt.ItemIsEnabled)
            tree_branch.setExpanded(True)
            tree_branch.setFont(0, bold_font)
            if 'name' in default_class:
                default_class_name = default_class['name']
            else:
                default_class_name = default_class['key']
            tree_branch.setText(0, default_class_name)
            tree_branch.setData(0, Qt.UserRole, default_class['key'])
            if 'description' in default_class:
                tree_branch.setToolTip(0, default_class['description'])
            # Assign known values
            for value in assigned_values[default_class['key']]:
                string_value = value is not None and unicode(value) or 'NULL'
                tree_leaf = QTreeWidgetItem(tree_branch)
                tree_leaf.setFlags(
                    Qt.ItemIsEnabled |
                    Qt.ItemIsSelectable |
                    Qt.ItemIsDragEnabled)
                tree_leaf.setData(0, Qt.UserRole, value)
                tree_leaf.setText(0, string_value)