def __init__(self):
        super(LessonSelector, self).__init__()
        self.setupUi(self)

        self.lesson = None

        allLessons = defaultdict(list)
        for lesson in lessons:
            allLessons[lesson.group].append(lesson)

        lessonIcon = QIcon(os.path.dirname(__file__) + '/lesson.gif')
        for group, groupLessons in allLessons.iteritems():
            groupItem = QTreeWidgetItem()
            groupItem.setText(0, group)
            for lesson in groupLessons:
                lessonItem = QTreeWidgetItem()
                lessonItem.lesson = lesson
                lessonItem.setText(0, lesson.name)
                lessonItem.setIcon(0, lessonIcon)
                groupItem.addChild(lessonItem)
            self.lessonsTree.addTopLevelItem(groupItem)

        self.lessonsTree.sortItems(0, 0)

        self.lessonsTree.expandAll()

        self.lessonsTree.currentItemChanged.connect(self.currentItemChanged)
        self.lessonsTree.itemDoubleClicked.connect(self.itemDoubleClicked)

        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)

        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
Beispiel #2
0
    def load_ui(self):
        sections = sorted(list(Preferences.configuration.keys()),
            key=lambda item: Preferences.configuration[item]['weight'])
        for section in sections:
            text = Preferences.configuration[section]['text']
            Widget = Preferences.configuration[section]['widget']
            widget = Widget(self)
            area = QScrollArea()
            area.setWidgetResizable(True)
            area.setWidget(widget)
            index = self.stacked.addWidget(area)
            item = QTreeWidgetItem([text])
            item.setData(0, Qt.UserRole, index)
            self.tree.addTopLevelItem(item)

            #Sort Item Children
            subcontent = Preferences.configuration[section].get(
                'subsections', {})
            subsections = sorted(list(subcontent.keys()),
                key=lambda item: subcontent[item]['weight'])
            for sub in subsections:
                text = subcontent[sub]['text']
                Widget = subcontent[sub]['widget']
                widget = Widget(self)
                area = QScrollArea()
                area.setWidgetResizable(True)
                area.setWidget(widget)
                index = self.stacked.addWidget(area)
                subitem = QTreeWidgetItem([text])
                subitem.setData(0, Qt.UserRole, index)
                item.addChild(subitem)

        self.tree.expandAll()
Beispiel #3
0
 def createTree(self):
     objects = list(self.model)
     objects = [object for object in objects
         if self.filter.match(object)]
     objects.sort(key=getIdentifier)
     groups = {}
     for object in objects:
         if isinstance(object, Group):
             key = None
         else:
             key = self.getTreeKey(object)
         if key in groups:
             groups[key].append(object)
         else:
             groups[key] = [object]
     root = []
     for key in sorted(groups.keys()):
         if key:
             label = self.createTreeKeyLabel(key)
         else:
             label = tr('Groups')
         tree = QTreeWidgetItem([label])
         unsetFlag(tree, Qt.ItemIsSelectable)
         for object in groups[key]:
             node = self.createTreeItem(object)
             tree.addChild(node)
         root.append(tree)
     return root
 def __add_themen(self):
     self.ui.TREE_THEMEN.headerItem().setText(0, '')
     #TODO: resize column to contents
     #all of these don't work??
     self.ui.TREE_THEMEN.header().resizeSection(0, 250)
     self.ui.TREE_THEMEN.header().setResizeMode(
         QHeaderView.ResizeToContents)
     self.ui.TREE_THEMEN.header().setStretchLastSection(True)
     themen = self.json_settings.themen()
     for thema_name, thema in themen.iteritems():
         tree_thema = QTreeWidgetItem(self.ui.TREE_THEMEN)
         tree_thema.setText(0, thema_name)
         tree_thema.setData(0, Qt.UserRole, thema)
         tree_thema.setFlags(tree_thema.flags() | Qt.ItemIsUserCheckable)
         if thema_name == 'DKM':
             tree_thema.setCheckState(0, Qt.Checked)
         else:
             tree_thema.setCheckState(0, Qt.Unchecked)
         if not thema.subthemen is None:
             for subthema in thema.subthemen:
                 if VRP_DEBUG is True:
                     QgsMessageLog.logMessage(
                         u'Subthema: {0}'.format(subthema.name),
                         DLG_CAPTION)
                 tree_subthema = QTreeWidgetItem()
                 tree_subthema.setText(0, subthema.name)
                 tree_subthema.setData(0, Qt.UserRole, subthema)
                 tree_subthema.setFlags(tree_subthema.flags()
                                        | Qt.ItemIsUserCheckable)
                 tree_subthema.setCheckState(0, Qt.Unchecked)
                 tree_thema.addChild(tree_subthema)
Beispiel #5
0
 def __init__(self, parent=None):
     """
     Constructor
     """
     QDialog.__init__(self, parent)
     self.setupUi(self)
     self.parent = parent
     self.pxSchedTbl = parent.pxCurSelGaInOsObj
     self.setWindowTitle("Configure Schedule Table <%s>" %
                         (self.pxSchedTbl.xScheduleTableName))
     self.vDisableAllTab()
     self.pxCurSelEp = None
     self.pxCurSelEpSubIndex = -1
     self.pxCurSelTreeItem = None
     #根据table 刷新界面树,初始化
     index = 0
     for ep in self.pxSchedTbl.xSchedTblEpList:
         defaultName = QString('Expiry Point %s(%s)' % (index, ep[0]))
         pxTreeIlem = QTreeWidgetItem(self.trSchedTable,
                                      QStringList(defaultName))
         self.trSchedTable.addTopLevelItem(pxTreeIlem)
         index += 1
         for epsub in ep[1]:
             defaultName = QString(epsub)
             pxTreeIlem2 = QTreeWidgetItem(None, QStringList(defaultName))
             pxTreeIlem.addChild(pxTreeIlem2)
             pxTreeIlem.setExpanded(True)
     #刷新基本控件
     self.cbxSchedTblRepeatable.setChecked(
         self.pxSchedTbl.xSchedTblRepeatable)
     self.cbxSchedTblAutostartable.setChecked(
         self.pxSchedTbl.xSchedTblAutostartable)
     self.cmbxSchedTblAutoStartType.setCurrentIndex(
         self.vDoGetAutostartType())
     self.cmbxSchedTblSyncStrategy.setCurrentIndex(
         self.vDoGetSyncStrategy())
     self.spbxSchedTblAbsRel.setValue(self.pxSchedTbl.xSchedTblAbsRelValue)
     self.spbxSchedTblFinalDelay.setValue(
         self.pxSchedTbl.xSchedTblFinalDelay)
     self.spbxSchedTblMaxAdvance.setValue(
         self.pxSchedTbl.xSchedTblMaxAdvance)
     self.spbxSchedTblMaxRetard.setValue(self.pxSchedTbl.xSchedTblMaxRetard)
     self.spbxSchedTblPrecision.setValue(
         self.pxSchedTbl.xSchedTblExplicitPrecision)
     index = -1
     i = 0
     for cnt in self.parent.pxGaInOSCounterCfgList:
         name = cnt.xCounterName
         self.cmbxSchedTblDrivingCounter.addItem(name)
         if (self.pxSchedTbl.xSchedTblDrivingCounter == name):
             index = i
         i += 1
     #模拟一次点击刷新控件
     self.on_cbxSchedTblAutostartable_clicked(
         self.pxSchedTbl.xSchedTblAutostartable)
     #初始化控件
     self.btnAdd.setText("Add Expiry Point")
     self.btnAdd.setDisabled(False)
     self.btnInsert.setDisabled(True)
     self.btnDelete.setDisabled(True)
Beispiel #6
0
	def updateHolesTable(self):
		self.treeWidget_holes.clear()
		self.treeWidget_holes.setColumnCount(3)
		self.treeWidget_holes.setColumnWidth(0, 50)
		self.treeWidget_holes.setColumnWidth(1, 50)
		self.treeWidget_holes.setColumnWidth(2, 70)
		self.treeWidget_holes.setColumnWidth(3, 70)
		self.treeWidget_holes.setHeaderLabels(["dia", "#", "X", "Y"])

		diaList=list(self.fitHoles.keys())
		diaList.sort()

		for dia in diaList:
			drillItem = QTreeWidgetItem()
			drillItem.setText(0, str(dia))
			drillItem.setText(1, str(len(self.fitHoles[dia])))
			self.treeWidget_holes.addTopLevelItem(drillItem)

			for hole in (self.fitHoles[dia]):
				x, y, ID = hole
				holeItem = QTreeWidgetItem(ID+1000)	# use ID of hole as type
				holeItem.setText(2, "{:3.1f}".format(x))
				holeItem.setText(3, "{:3.1f}".format(y))
				drillItem.addChild(holeItem)

				if hole in self.selectedHoles:
					self.treeWidget_holes.setCurrentItem(holeItem)
					#self.treeWidget_holes.expandItem(drillItem)
					#self.treeWidget_holes.scrollToItem(holeItem)

		if not self.selectedHoles:
			self.treeWidget_holes.setCurrentItem(None)
Beispiel #7
0
    def load_ui(self):
        sections = sorted(
            list(Preferences.configuration.keys()),
            key=lambda item: Preferences.configuration[item]['weight'])
        for section in sections:
            text = Preferences.configuration[section]['text']
            Widget = Preferences.configuration[section]['widget']
            widget = Widget(self)
            area = QScrollArea()
            area.setWidgetResizable(True)
            area.setWidget(widget)
            index = self.stacked.addWidget(area)
            item = QTreeWidgetItem([text])
            item.setData(0, Qt.UserRole, index)
            self.tree.addTopLevelItem(item)

            #Sort Item Children
            subcontent = Preferences.configuration[section].get(
                'subsections', {})
            subsections = sorted(list(subcontent.keys()),
                                 key=lambda item: subcontent[item]['weight'])
            for sub in subsections:
                text = subcontent[sub]['text']
                Widget = subcontent[sub]['widget']
                widget = Widget(self)
                area = QScrollArea()
                area.setWidgetResizable(True)
                area.setWidget(widget)
                index = self.stacked.addWidget(area)
                subitem = QTreeWidgetItem([text])
                subitem.setData(0, Qt.UserRole, index)
                item.addChild(subitem)

        self.tree.expandAll()
Beispiel #8
0
class LoadThings(QUndoCommand):
    def __init__(self, widget, thing):
        super(LoadThings, self).__init__()
        self.widget = widget

        self.createdThing = thing
        self.item = QTreeWidgetItem()
        self.item.setText(0, thing.name)

        typeName = type(thing).__name__
        for i in range(self.widget.ui.treeWidget.topLevelItemCount()):
            group = self.widget.ui.treeWidget.topLevelItem(i)
            if group.text(0) == typeName:
                self.group = group
                break
        else: # group not found
            self.group = QTreeWidgetItem()
            self.group.setText(0, typeName)

    def redo(self):
        if self.widget.ui.treeWidget.indexOfTopLevelItem(self.group) == -1:
            self.widget.ui.treeWidget.addTopLevelItem(self.group)
        self.group.addChild(self.item)
        self.group.setExpanded(True)
        self.widget.ui.treeWidget.setCurrentItem(self.item)

    def undo(self):
        self.group.takeChild(self.group.childCount()-1)
        if self.group.childCount() == 0:
            parentIndex = self.widget.ui.treeWidget.indexOfTopLevelItem(self.group)
            self.widget.ui.treeWidget.takeTopLevelItem(parentIndex)
Beispiel #9
0
 def on_btnParse_clicked(self):
     """
     Slot documentation goes here.
     """
     self.tvResult.clear()
     fName = self.lblPath.text()
     pattern = self.txtReToMatch.displayText()
     parser = Parser.Parser(fName)
     parser.parseLogFile(pattern)
     
     if 0<len(parser.lastError):
         self.lblPath.setText(parser.lastError)
     else:
         for ip_k in parser.parsedRecords.keys():
             item = QTreeWidgetItem(self.tvResult)
             item.setText(0,  ip_k)
             self.tvResult.addTopLevelItem(item)
             for ua_k in parser.parsedRecords[ip_k].keys():
                 item2 = QTreeWidgetItem(item)
                 item2.setText(0,  ua_k)
                 item.addChild(item2)
                 for logEntry in parser.parsedRecords[ip_k][ua_k]:
                     item3 = QTreeWidgetItem(item2)
                     item3.setText(0,  logEntry.urlReq)
                     item3.setText(1,  logEntry.dateTime)
                     item2.addChild(item3)
Beispiel #10
0
    def addRecentAlgorithms(self, updating):
        showRecent = ProcessingConfig.getSetting(
            ProcessingConfig.SHOW_RECENT_ALGORITHMS)
        if showRecent:
            recent = ProcessingLog.getRecentAlgorithms()
            if len(recent) != 0:
                found = False
                if updating:
                    recentItem = self.algorithmTree.topLevelItem(0)
                    treeWidget = recentItem.treeWidget()
                    treeWidget.takeTopLevelItem(
                        treeWidget.indexOfTopLevelItem(recentItem))

                recentItem = QTreeWidgetItem()
                recentItem.setText(0, self.tr('Recently used algorithms'))
                for algname in recent:
                    alg = Processing.getAlgorithm(algname)
                    if alg is not None:
                        algItem = TreeAlgorithmItem(alg)
                        recentItem.addChild(algItem)
                        found = True
                if found:
                    self.algorithmTree.insertTopLevelItem(0, recentItem)
                    recentItem.setExpanded(True)

            self.algorithmTree.setWordWrap(True)
Beispiel #11
0
    def loadPagesList(self, checkable=False):
        self.clear()
        for section in self.user_settings['pagesindex'].sections:
            root = QTreeWidgetItem([section.title])
            root.setData(0, Qt.UserRole, QVariant(QString(section.name)))
            root.setData(0, Qt.DecorationRole, QVariant(QIcon(section.icon)))
            self.addTopLevelItem(root)

            for page_id, page in section.pages:
                if not page:
                    page = self.getPage(page_id)
                if page.title:
                    page_title = page.title
                else:
                    page_title = tr('(No name)')
                item = QTreeWidgetItem([page_title])
                item.setData(0, Qt.UserRole ,QVariant(QString(page_id)))
                if checkable:
                    item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
                    item.setCheckState(0, Qt.Unchecked)
                root.addChild(item)
                if page == self.window.current_page:
                    f = QFont()
                    f.setWeight(QFont.Bold)
                    item.setData(0, Qt.FontRole, QVariant(f))
                    self.setCurrentItem(item)

        self.expandAll()
Beispiel #12
0
    def _add_symbol_to_tree_widget(self, symbol):
        """ Add the given symbol to the tree widget. If this
        is a new category create it, otherwise append it
        to the already existing one.

        """

        # find category
        category = symbol["category"]
        categoryItems = self.availableSymbolsWidget.findItems(
            category, Qt.MatchExactly, 0)

        name = symbol["name"]
        symbolItem = QTreeWidgetItem([name])
        symbolItem.setData(0, Qt.UserRole, name)
        symbolItem.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable
                            | Qt.ItemIsEnabled)

        if categoryItems:
            categoryItems[0].addChild(symbolItem)
        else:
            categoryItem = QTreeWidgetItem(self.availableSymbolsWidget,
                                           [category])
            categoryItem.setFlags(Qt.ItemIsEnabled)
            categoryItem.addChild(symbolItem)

        self.availableSymbolsWidget.resizeColumnToContents(0)
        self.availableSymbolsWidget.sortItems(0, Qt.AscendingOrder)
        self.availableSymbolsWidget.setCurrentItem(symbolItem)
    def fillTree(self):
        self.profilesTree.clear()

        allProfiles = defaultdict(list)
        for v in profiles.values():
            allProfiles[v.group].append(v)

        profileIcon = QIcon(os.path.join(os.path.dirname(__file__), os.pardir,
                                               'icons', 'profile.png'))

        for group, groupProfiles in allProfiles.iteritems():
            groupItem = QTreeWidgetItem()
            groupItem.setText(0, group)
            for profile in groupProfiles:
                profileItem = QTreeWidgetItem()
                profileItem.profile = profile
                profileItem.isCustom = False
                profileItem.setText(0, profile.name)
                profileItem.setIcon(0, profileIcon)
                groupItem.addChild(profileItem)
            self.profilesTree.addTopLevelItem(groupItem)

        groupItem = QTreeWidgetItem()
        groupItem.setText(0, self.tr("User profiles"))
        for profile in customProfiles():
            profileItem = QTreeWidgetItem()
            profileItem.profile = profile
            profileItem.isCustom = True
            profileItem.setText(0, profile.name)
            profileItem.setIcon(0, profileIcon)
            groupItem.addChild(profileItem)
        self.profilesTree.addTopLevelItem(groupItem)

        self.profilesTree.expandAll()
    def addRecentAlgorithms(self, updating):
        showRecent = ProcessingConfig.getSetting(
            ProcessingConfig.SHOW_RECENT_ALGORITHMS)
        if showRecent:
            recent = ProcessingLog.getRecentAlgorithms()
            if len(recent) != 0:
                found = False
                if updating:
                    recentItem = self.algorithmTree.topLevelItem(0)
                    treeWidget = recentItem.treeWidget()
                    treeWidget.takeTopLevelItem(
                        treeWidget.indexOfTopLevelItem(recentItem))

                recentItem = QTreeWidgetItem()
                recentItem.setText(0, self.tr('Recently used algorithms'))
                for algname in recent:
                    alg = Processing.getAlgorithm(algname)
                    if alg is not None:
                        algItem = TreeAlgorithmItem(alg)
                        recentItem.addChild(algItem)
                        found = True
                if found:
                    self.algorithmTree.insertTopLevelItem(0, recentItem)
                    recentItem.setExpanded(True)

            self.algorithmTree.setWordWrap(True)
Beispiel #15
0
    def populateConfigParams(self, dlg):
        """ Populates the dialog with option items and widgets """
        self.items = defaultdict(dict)
        tree = dlg.paramsTreeOL

        configure_export_action = QAction('...', self)
        configure_export_action.triggered.connect(self.configureExporter)

        params = getParams(configure_exporter_action=configure_export_action)
        for group, settings in params.iteritems():
            item = QTreeWidgetItem()
            item.setText(0, group)
            for param, value in settings.iteritems():
                subitem = self.createOptionItem(tree_widget=tree,
                                                parent_item=item,
                                                parameter=param,
                                                default_value=value)
                item.addChild(subitem)
                self.items[group][param] = subitem
            self.paramsTreeOL.addTopLevelItem(item)
            item.sortChildren(0, Qt.AscendingOrder)
        self.paramsTreeOL.expandAll()
        self.paramsTreeOL.resizeColumnToContents(0)
        self.paramsTreeOL.resizeColumnToContents(1)
        self.layer_search_combo.removeItem(1)
 def __add_themen(self):
     self.ui.TREE_THEMEN.headerItem().setText(0, '')
     #TODO: resize column to contents
     #all of these don't work??
     self.ui.TREE_THEMEN.header().resizeSection(0, 250)
     self.ui.TREE_THEMEN.header().setResizeMode(QHeaderView.ResizeToContents);
     self.ui.TREE_THEMEN.header().setStretchLastSection(True);
     themen = self.json_settings.themen()
     for thema_name, thema in themen.iteritems():
         tree_thema = QTreeWidgetItem(self.ui.TREE_THEMEN)
         tree_thema.setText(0, thema_name)
         tree_thema.setData(0, Qt.UserRole, thema)
         tree_thema.setFlags(tree_thema.flags() | Qt.ItemIsUserCheckable)
         if thema_name == 'DKM':
             tree_thema.setCheckState(0, Qt.Checked)
         else:
             tree_thema.setCheckState(0, Qt.Unchecked)
         if not thema.subthemen is None:
             for subthema in thema.subthemen:
                 if VRP_DEBUG is True: QgsMessageLog.logMessage(u'Subthema: {0}'.format(subthema.name), DLG_CAPTION)
                 tree_subthema = QTreeWidgetItem()
                 tree_subthema.setText(0, subthema.name)
                 tree_subthema.setData(0, Qt.UserRole, subthema)
                 tree_subthema.setFlags(tree_subthema.flags() | Qt.ItemIsUserCheckable)
                 tree_subthema.setCheckState(0, Qt.Unchecked)
                 tree_thema.addChild(tree_subthema)
    def _add_symbol_to_tree_widget(self, symbol):
        """ Add the given symbol to the tree widget. If this
        is a new category create it, otherwise append it
        to the already existing one.

        """

        # find category
        category = symbol["category"]
        categoryItems = self.availableSymbolsWidget.findItems(category,
                                                Qt.MatchExactly, 0)

        name = symbol["name"]
        symbolItem = QTreeWidgetItem([name])
        symbolItem.setData(0, Qt.UserRole, name)
        symbolItem.setFlags(Qt.ItemIsSelectable |
                            Qt.ItemIsUserCheckable |
                            Qt.ItemIsEnabled)

        if categoryItems:
            categoryItems[0].addChild(symbolItem)
        else:
            categoryItem = QTreeWidgetItem(self.availableSymbolsWidget,
                                           [category])
            categoryItem.setFlags(Qt.ItemIsEnabled)
            categoryItem.addChild(symbolItem)

        self.availableSymbolsWidget.resizeColumnToContents(0)
        self.availableSymbolsWidget.sortItems(0, Qt.AscendingOrder)
        self.availableSymbolsWidget.setCurrentItem(symbolItem)
Beispiel #18
0
    def buildParentItem(self, dcollection, title, rootresource):
        '''
        Builds tree widget items from a dictionary.
        '''
        rtItem = QTreeWidgetItem()
        rtItem.setText(0, title)
        rtItem.setIcon(0, QIcon(rootresource))

        topLevelItems = []

        for k, v in dcollection.iteritems():
            parentItem = QTreeWidgetItem()

            if isinstance(v, dict):
                parentItem.setText(0, k)

                for kc, vc in v.iteritems():
                    child = QTreeWidgetItem()
                    child.setText(0, self._combine(kc, vc))
                    parentItem.addChild(child)

            else:
                parentItem.setText(0, self._combine(k, v))

            topLevelItems.append(parentItem)

        rtItem.addChildren(topLevelItems)
        rtItem.setExpanded(True)

        return rtItem
Beispiel #19
0
 def createTree(self):
     nodes = self._createTree(list(self.model))
     root = QTreeWidgetItem([tr("Network interfaces")])
     root.setIcon(0, QIcon(":/icons-32/home.png"))
     unsetFlag(root, Qt.ItemIsSelectable)
     for node in nodes:
         root.addChild(node)
     return [root]
Beispiel #20
0
 def __importCSV(self, csvFile):
     self.twMeasurements.clear()
     self.__sourcecsv= InputCSVH5(csvFile, ',')
     self.__sourcecsv.load_csvHeader()
     rootItem= QTreeWidgetItem(self.twMeasurements, [csvFile])
     for value in self.__sourcecsv.measurements:
         childItem = QTreeWidgetItem()
         childItem.setText(0, value)
         rootItem.addChild(childItem)
    def populate(self):
        groups = {}
        count = 0
        provider = Processing.algs[self.providerName]
        algs = provider.values()

        name = 'ACTIVATE_' + self.providerName.upper().replace(' ', '_')
        active = ProcessingConfig.getSetting(name)

        # Add algorithms
        for alg in algs:
            if not alg.showInToolbox:
                continue
            if alg.group in groups:
                groupItem = groups[alg.group]
            else:
                groupItem = QTreeWidgetItem()
                name = alg.i18n_group or alg.group
                if not active:
                    groupItem.setForeground(0, Qt.darkGray)
                groupItem.setText(0, name)
                groupItem.setToolTip(0, name)
                groups[alg.group] = groupItem
            algItem = TreeAlgorithmItem(alg)
            if not active:
                algItem.setForeground(0, Qt.darkGray)
            groupItem.addChild(algItem)
            count += 1

        actions = Processing.actions[self.providerName]
        for action in actions:
            if action.group in groups:
                groupItem = groups[action.group]
            else:
                groupItem = QTreeWidgetItem()
                groupItem.setText(0, action.group)
                groups[action.group] = groupItem
            algItem = TreeActionItem(action)
            groupItem.addChild(algItem)

        text = self.provider.getDescription()

        if not active:
            def activateProvider():
                self.toolbox.activateProvider(self.providerName)
            label = QLabel(text + "&nbsp;&nbsp;&nbsp;&nbsp;<a href='%s'>Activate</a>")
            label.setStyleSheet("QLabel {background-color: white; color: grey;}")
            label.linkActivated.connect(activateProvider)
            self.tree.setItemWidget(self, 0, label)

        else:
            text += QCoreApplication.translate("TreeProviderItem", " [{0} geoalgorithms]").format(count)
        self.setText(0, text)
        self.setToolTip(0, self.text(0))
        for groupItem in groups.values():
            self.addChild(groupItem)
Beispiel #22
0
    def populate(self):
        groups = {}
        count = 0
        provider = Processing.algs[self.providerName]
        algs = provider.values()

        name = 'ACTIVATE_' + self.providerName.upper().replace(' ', '_')
        active = ProcessingConfig.getSetting(name)

        # Add algorithms
        for alg in algs:
            if not alg.showInToolbox:
                continue
            if alg.group in groups:
                groupItem = groups[alg.group]
            else:
                groupItem = QTreeWidgetItem()
                name = alg.i18n_group or alg.group
                if not active:
                    groupItem.setForeground(0, Qt.darkGray)
                groupItem.setText(0, name)
                groupItem.setToolTip(0, name)
                groups[alg.group] = groupItem
            algItem = TreeAlgorithmItem(alg)
            if not active:
                algItem.setForeground(0, Qt.darkGray)
            groupItem.addChild(algItem)
            count += 1

        actions = Processing.actions[self.providerName]
        for action in actions:
            if action.group in groups:
                groupItem = groups[action.group]
            else:
                groupItem = QTreeWidgetItem()
                groupItem.setText(0, action.group)
                groups[action.group] = groupItem
            algItem = TreeActionItem(action)
            groupItem.addChild(algItem)

        text = self.provider.getDescription()

        if not active:
            def activateProvider():
                self.toolbox.activateProvider(self.providerName)
            label = QLabel(text + "&nbsp;&nbsp;&nbsp;&nbsp;<a href='%s'>Activate</a>")
            label.setStyleSheet("QLabel {background-color: white; color: grey;}")
            label.linkActivated.connect(activateProvider)
            self.tree.setItemWidget(self, 0, label)

        else:
            text += QCoreApplication.translate("TreeProviderItem", " [{0} geoalgorithms]").format(count)
        self.setText(0, text)
        self.setToolTip(0, self.text(0))
        for groupItem in groups.values():
            self.addChild(groupItem)
Beispiel #23
0
 def reloadGui(self):
     tree=self.trSchedTable.topLevelItem(0);
     for tbl in self.cfg.table:
         item=QTreeWidgetItem(tree,QStringList('Expiry Point(offset = %s)'%(tbl.offset)));
         tree.addChild(item);
         for action in tbl.actionList:
             item2=QTreeWidgetItem(item,QStringList(action));
             item.addChild(item2);
         item.setExpanded(True)
     tree.setExpanded(True)
Beispiel #24
0
 def reloadTaskGui(self):
     tree=self.trModule.topLevelItem(1);
     for index in range(0, tree.childCount()):
         temp=tree.takeChild(0);
         del temp;
     for obj in self.cfg.taskList:
         item=QTreeWidgetItem(tree,QStringList(obj.name));
         tree.addChild(item);
         for ent in obj.eventList:
             item2=QTreeWidgetItem(item,QStringList(ent.name));
             item.addChild(item2);
Beispiel #25
0
 def reloadGui(self):
     tree = self.trSchedTable.topLevelItem(0)
     for tbl in self.cfg.table:
         item = QTreeWidgetItem(
             tree, QStringList('Expiry Point(offset = %s)' % (tbl.offset)))
         tree.addChild(item)
         for action in tbl.actionList:
             item2 = QTreeWidgetItem(item, QStringList(action))
             item.addChild(item2)
         item.setExpanded(True)
     tree.setExpanded(True)
Beispiel #26
0
 def reloadCtrlGui(self):
     tree=self.trCanCfg.topLevelItem(1);
     for index in range(0, tree.childCount()):
         temp=tree.takeChild(0);
         del temp;
     for obj in self.cfg.CanCtrlList:
         item=QTreeWidgetItem(tree,QStringList(obj.name));
         tree.addChild(item);
         for hoh in obj.hohList:
             item2=QTreeWidgetItem(item,QStringList(hoh.name));
             item.addChild(item2);
Beispiel #27
0
 def reloadTaskGui(self):
     tree = self.trModule.topLevelItem(1)
     for index in range(0, tree.childCount()):
         temp = tree.takeChild(0)
         del temp
     for obj in self.cfg.taskList:
         item = QTreeWidgetItem(tree, QStringList(obj.name))
         tree.addChild(item)
         for ent in obj.eventList:
             item2 = QTreeWidgetItem(item, QStringList(ent.name))
             item.addChild(item2)
Beispiel #28
0
 def fillInputsTree(self):
     icon = QIcon(os.path.join(pluginPath, 'images', 'input.png'))
     parametersItem = QTreeWidgetItem()
     parametersItem.setText(0, self.tr('Parameters'))
     for paramType in ModelerParameterDefinitionDialog.paramTypes:
         paramItem = QTreeWidgetItem()
         paramItem.setText(0, paramType)
         paramItem.setIcon(0, icon)
         paramItem.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled)
         parametersItem.addChild(paramItem)
     self.inputsTree.addTopLevelItem(parametersItem)
     parametersItem.setExpanded(True)
Beispiel #29
0
    def __setupModelData(self):
        dsList = DataSourcesList().data_sources.values()
        groupInfoList = GroupsList().groups
        groupsItems = []
        groups = []
        for ds in dsList:
            if ds.group in groups:
                group_item = groupsItems[groups.index(ds.group)]
            else:
                group_item = QTreeWidgetItem()
                group_item.setData(self.COLUMN_GROUP_DS, Qt.DisplayRole,
                                   ds.group)
                group_item.setData(self.COLUMN_VISIBILITY, Qt.DisplayRole, "")
                group_item.setData(self.COLUMN_SOURCE, Qt.DisplayRole,
                                   ds.category)
                group_item.setCheckState(self.COLUMN_VISIBILITY, Qt.Unchecked)

                groupInfo = groupInfoList.get(ds.group)
                if groupInfo is not None:
                    group_item.setIcon(self.COLUMN_GROUP_DS,
                                       QIcon(groupInfo.icon))
                else:
                    group_item.setData(
                        self.COLUMN_GROUP_DS, Qt.DisplayRole,
                        ds.group + " (%s!)" % self.tr("group not found"))
                group_item.setData(self.COLUMN_GROUP_DS, Qt.UserRole,
                                   groupInfo)

                groups.append(ds.group)
                groupsItems.append(group_item)
                self.rootItem.addChild(group_item)

            ds_item = QTreeWidgetItem()
            ds_item.setData(self.COLUMN_GROUP_DS, Qt.DisplayRole, ds.alias)
            ds_item.setIcon(self.COLUMN_GROUP_DS, QIcon(ds.icon_path))
            ds_item.setData(self.COLUMN_GROUP_DS, Qt.UserRole, ds)
            ds_item.setData(self.COLUMN_VISIBILITY, Qt.DisplayRole, "")
            ds_item.setData(self.COLUMN_SOURCE, Qt.DisplayRole, ds.category)

            ds_check_state = Qt.Checked
            if ds.id in PluginSettings.get_hide_ds_id_list():
                ds_check_state = Qt.Unchecked
            ds_item.setCheckState(self.COLUMN_VISIBILITY, ds_check_state)

            if group_item.childCount() != 0 and group_item.checkState(
                    1) != ds_check_state:
                group_item.setCheckState(self.COLUMN_VISIBILITY,
                                         Qt.PartiallyChecked)
            else:
                group_item.setCheckState(self.COLUMN_VISIBILITY,
                                         ds_check_state)

            group_item.addChild(ds_item)
Beispiel #30
0
    def fill(self):
        self.clear()
        services = self._client.getServices()
        try:
            descrs = self._client.getServiceDescriptions(services)
        except Exception:
            descrs = {}
        self._client.startPoller(self.updateStatus)

        for service, instances in iteritems(services):
            serviceItem = QTreeWidgetItem([service])
            serviceItem.setForeground(1, QBrush(QColor('white')))
            serviceItem.setTextAlignment(1, Qt.AlignCenter)
            serviceItem.setFlags(Qt.ItemIsEnabled)
            serviceItem.setForeground(3, QBrush(QColor('red')))
            self.addTopLevelItem(serviceItem)

            btns = []
            has_empty_instance = None
            for instance in instances:
                if not instance:
                    has_empty_instance = True
                    continue
                instanceItem = QTreeWidgetItem([instance])
                instanceItem.setForeground(1, QBrush(QColor('white')))
                instanceItem.setTextAlignment(1, Qt.AlignCenter)
                instanceItem.setFlags(Qt.ItemIsEnabled)
                instanceItem.setForeground(3, QBrush(QColor('red')))
                if descrs.get((service, instance)):
                    instanceItem.setText(0, descrs[service, instance])
                serviceItem.addChild(instanceItem)

                btn = JobButtons(self._client, service, instance,
                                 instanceItem)
                btns.append(btn)
                self.setItemWidget(instanceItem, 2, btn)
                self._items[service, instance] = instanceItem
            if has_empty_instance:
                btn = JobButtons(self._client, service, '',
                                 serviceItem)
                btn.setMinimumSize(QSize(30, 40))
                self.setItemWidget(serviceItem, 2, btn)
                if descrs.get((service, '')):
                    serviceItem.setText(0, descrs[service, ''])
                self._items[service, ''] = serviceItem
            else:
                # create "virtual" job with buttons that start/stop all
                # instances of the service
                self._virt_items[service] = serviceItem
                multibtn = MultiJobButtons(btns)
                self.setItemWidget(serviceItem, 2, multibtn)

        self.expandAll()
Beispiel #31
0
 def fillInputsTree(self):
     icon = QIcon(os.path.join(pluginPath, 'images', 'input.png'))
     parametersItem = QTreeWidgetItem()
     parametersItem.setText(0, self.tr('Parameters'))
     for paramType in ModelerParameterDefinitionDialog.paramTypes:
         paramItem = QTreeWidgetItem()
         paramItem.setText(0, paramType)
         paramItem.setIcon(0, icon)
         paramItem.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled)
         parametersItem.addChild(paramItem)
     self.inputsTree.addTopLevelItem(parametersItem)
     parametersItem.setExpanded(True)
Beispiel #32
0
 def __init__(self, parent = None):
     """
     Constructor
     """
     QDialog.__init__(self, parent)
     self.setupUi(self);
     self.parent=parent;
     self.pxSchedTbl=parent.pxCurSelGaInOsObj;
     self.setWindowTitle("Configure Schedule Table <%s>"%(self.pxSchedTbl.xScheduleTableName));
     self.vDisableAllTab();
     self.pxCurSelEp=None;
     self.pxCurSelEpSubIndex=-1;
     self.pxCurSelTreeItem=None;
     #根据table 刷新界面树,初始化
     index=0;
     for ep in self.pxSchedTbl.xSchedTblEpList:
         defaultName=QString('Expiry Point %s(%s)'%(index, ep[0]));
         pxTreeIlem=QTreeWidgetItem(self.trSchedTable,QStringList(defaultName));
         self.trSchedTable.addTopLevelItem(pxTreeIlem);
         index+=1;
         for epsub in ep[1]:
             defaultName=QString(epsub);
             pxTreeIlem2=QTreeWidgetItem(None,QStringList(defaultName));
             pxTreeIlem.addChild(pxTreeIlem2);
             pxTreeIlem.setExpanded(True);
     #刷新基本控件
     self.cbxSchedTblRepeatable.setChecked(self.pxSchedTbl.xSchedTblRepeatable);
     self.cbxSchedTblAutostartable.setChecked(self.pxSchedTbl.xSchedTblAutostartable);
     self.cmbxSchedTblAutoStartType.setCurrentIndex(self.vDoGetAutostartType());
     self.cmbxSchedTblSyncStrategy.setCurrentIndex(self.vDoGetSyncStrategy());
     self.spbxSchedTblAbsRel.setValue(self.pxSchedTbl.xSchedTblAbsRelValue);
     self.spbxSchedTblFinalDelay.setValue(self.pxSchedTbl.xSchedTblFinalDelay);
     self.spbxSchedTblMaxAdvance.setValue(self.pxSchedTbl.xSchedTblMaxAdvance);
     self.spbxSchedTblMaxRetard.setValue(self.pxSchedTbl.xSchedTblMaxRetard);
     self.spbxSchedTblPrecision.setValue(self.pxSchedTbl.xSchedTblExplicitPrecision);
     index=-1;
     i=0;
     for cnt in self.parent.pxGaInOSCounterCfgList:
         name=cnt.xCounterName;
         self.cmbxSchedTblDrivingCounter.addItem(name);
         if(self.pxSchedTbl.xSchedTblDrivingCounter==name):
             index=i;
         i+=1;
     #模拟一次点击刷新控件
     self.on_cbxSchedTblAutostartable_clicked(self.pxSchedTbl.xSchedTblAutostartable);
     #初始化控件
     self.btnAdd.setText("Add Expiry Point");
     self.btnAdd.setDisabled(False);
     self.btnInsert.setDisabled(True);
     self.btnDelete.setDisabled(True);
Beispiel #33
0
 def reloadTreeGui(self):
     tree=self.trCanIfCfg.topLevelItem(0);
     for index in range(0, tree.childCount()):
         temp=tree.takeChild(0);
         del temp;
     for obj in self.cfg.channelList:
         item=QTreeWidgetItem(tree,QStringList(obj.name));
         tree.addChild(item);
         for hoh in obj.hthList+obj.hrhList:
             item2=QTreeWidgetItem(item,QStringList(hoh.name));
             item.addChild(item2);
             for pdu in hoh.pduList:
                 item3=QTreeWidgetItem(item2,QStringList(pdu.name));
                 item2.addChild(item3);
 def reloadTreeGui(self):
     tree=self.trCanIfCfg.topLevelItem(0);
     for index in range(0, tree.childCount()):
         temp=tree.takeChild(0);
         del temp;
     for obj in self.cfg.channelList:
         item=QTreeWidgetItem(tree,QStringList(obj.name));
         tree.addChild(item);
         for hoh in obj.hthList+obj.hrhList:
             item2=QTreeWidgetItem(item,QStringList(hoh.name));
             item.addChild(item2);
             for pdu in hoh.pduList:
                 item3=QTreeWidgetItem(item2,QStringList(pdu.name));
                 item2.addChild(item3);
Beispiel #35
0
    def readModels(self):

        info_list = self.controller.initFieldDialog()
        self.modelsList.clear()

        for info in info_list:

            item = QTreeWidgetItem()
            item.setText(0, info.groupName)
            self.modelsList.addTopLevelItem(item)

            for model in info.modelNames:

                child = QTreeWidgetItem()
                child.setText(0, model)
                item.addChild(child)
Beispiel #36
0
    def fillAlgorithmTreeUsingProviders(self):
        self.algorithmTree.clear()
        text = unicode(self.searchBox.text())
        allAlgs = ModelerUtils.allAlgs
        for providerName in allAlgs.keys():
            name = 'ACTIVATE_' + providerName.upper().replace(' ', '_')
            if not ProcessingConfig.getSetting(name):
                continue
            groups = {}
            provider = allAlgs[providerName]
            algs = provider.values()

            # Add algorithms
            for alg in algs:
                if not alg.showInModeler or alg.allowOnlyOpenedLayers:
                    continue
                if alg.commandLineName() == self.alg.commandLineName():
                    continue
                if text == '' or text.lower() in alg.name.lower():
                    if alg.group in groups:
                        groupItem = groups[alg.group]
                    else:
                        groupItem = QTreeWidgetItem()
                        name = alg.i18n_group or alg.group
                        groupItem.setText(0, name)
                        groupItem.setToolTip(0, name)
                        groups[alg.group] = groupItem
                    algItem = TreeAlgorithmItem(alg)
                    groupItem.addChild(algItem)

            if len(groups) > 0:
                providerItem = QTreeWidgetItem()
                providerItem.setText(0,
                                     ModelerUtils.providers[providerName].getDescription())
                providerItem.setToolTip(0,
                                        ModelerUtils.providers[providerName].getDescription())
                providerItem.setIcon(0,
                                     ModelerUtils.providers[providerName].getIcon())
                for groupItem in groups.values():
                    providerItem.addChild(groupItem)
                self.algorithmTree.addTopLevelItem(providerItem)
                providerItem.setExpanded(text != '')
                for groupItem in groups.values():
                    if text != '':
                        groupItem.setExpanded(True)

        self.algorithmTree.sortItems(0, Qt.AscendingOrder)
 def __load_Measurements(self, dbh5file):
     ''' load signals from the h5 database '''
     self.__measdb= StreamH5CIM('./db/measurements', str(dbh5file))
     self.__measdb.open(str(dbh5file), mode= 'r')
     # TODO select model, root group h5
     self.twMeasVariable.clear()
     rootItem= QTreeWidgetItem(self.twMeasVariable, [self.__measdb.modelName])
     arbolMedidas= self.__measdb.select_treeMeasurements(self.__measdb.modelName)
     for psres in arbolMedidas:
         itemParent= QTreeWidgetItem()
         itemParent.setText(0,unicode(psres))
         for psmeas in arbolMedidas[psres]:
             childItem = QTreeWidgetItem()
             childItem.setText(0, unicode(psmeas))
             itemParent.addChild(childItem)
         rootItem.addChild(itemParent)
     self.twMeasVariable.itemSelectionChanged.connect(self.__twMeasVariable_onSelectionChanged)
Beispiel #38
0
    def fill(self):
        self.clear()
        services = self._client.getServices()
        try:
            descrs = self._client.getServiceDescriptions(services)
        except Exception:
            descrs = {}
        self._client.startPoller(self.updateStatus)

        for service, instances in iteritems(services):
            serviceItem = QTreeWidgetItem([service])
            serviceItem.setForeground(1, QBrush(QColor('white')))
            serviceItem.setTextAlignment(1, Qt.AlignCenter)
            serviceItem.setFlags(Qt.ItemIsEnabled)
            serviceItem.setForeground(3, QBrush(QColor('red')))
            self.addTopLevelItem(serviceItem)

            if not instances:
                self._items[service] = serviceItem
                btn = JobButtons(self._client, service, None, serviceItem)
                self.setItemWidget(serviceItem, 2, btn)
                if descrs.get(service):
                    serviceItem.setText(0, descrs[service])
            else:
                self._items[service] = (serviceItem, {})
                btns = []
                for instance in instances:
                    instanceItem = QTreeWidgetItem([instance])
                    instanceItem.setForeground(1, QBrush(QColor('white')))
                    instanceItem.setTextAlignment(1, Qt.AlignCenter)
                    instanceItem.setFlags(Qt.ItemIsEnabled)
                    instanceItem.setForeground(3, QBrush(QColor('red')))
                    if descrs.get((service, instance)):
                        instanceItem.setText(0, descrs[service, instance])
                    serviceItem.addChild(instanceItem)

                    btn = JobButtons(self._client, service, instance,
                                     instanceItem)
                    btns.append(btn)
                    self.setItemWidget(instanceItem, 2, btn)
                    self._items[service][1][instance] = instanceItem
                multibtn = MultiJobButtons(btns)
                self.setItemWidget(serviceItem, 2, multibtn)

        self.expandAll()
Beispiel #39
0
 def populateModelTree(self):
     logger.log('Loading model tree')
     self.modelTreeWidget.clear()
     for model in self.modelDict.keys():
         logger.log('Adding model: ' + model)
         modelItem = QTreeWidgetItem(self.modelTreeWidget)
         modelItem.setText(0, model)
         if self.modelDict[model].hasModel():
             modelItem.addChild(QTreeWidgetItem(QStringList('Model')))
         if self.modelDict[model].hasModelMaterial():
             modelItem.addChild(QTreeWidgetItem(QStringList('Mat: ' + self.modelDict[model]._modelMaterial)))
         if self.modelDict[model].hasModelPath():
             modelItem.addChild(QTreeWidgetItem(QStringList('model_path')))
         if self.modelDict[model].hasSupportPath():
             modelItem.addChild(QTreeWidgetItem(QStringList('support_path')))
         if self.modelDict[model].hasBasePath():
             modelItem.addChild(QTreeWidgetItem(QStringList('base_path')))
     self.modelTreeWidget.expandAll()
Beispiel #40
0
    def buildParentItem(self,dcollection,title,rootresource):
        '''
        Builds tree widget items from a dictionary.
        '''
        rtItem = QTreeWidgetItem()
        rtItem.setText(0,title)
        rtItem.setIcon(0,QIcon(rootresource))
            
        topLevelItems = []
            
        for k,v in dcollection.iteritems():
            parentItem = QTreeWidgetItem()
                
            if isinstance(v,dict):                                                
                parentItem.setText(0,k)
                    
                for kc,vc in v.iteritems():
                    child = QTreeWidgetItem()
                    child.setText(0,self._combine(kc, vc))
                    parentItem.addChild(child)
                
            else:
                parentItem.setText(0,self._combine(k, v))                
                    
            topLevelItems.append(parentItem)
                
        rtItem.addChildren(topLevelItems)
        rtItem.setExpanded(True)
        
        return rtItem

        
        
        
        
        
        
        
        
        
        
        
        
Beispiel #41
0
    def addIndex(self, index):
        indexTree = self.applicationWindow.mainWindow.indexes

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

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

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

        indexTree.addTopLevelItem(indexItem)
Beispiel #42
0
	def addIndex(self, index):
		indexTree = self.applicationWindow.mainWindow.indexes

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

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

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

		indexTree.addTopLevelItem(indexItem)
Beispiel #43
0
 def setDocuments(self, documents):
     """Display the specified documents in the list."""
     # clear the treewidget
     for d in self.tree.invisibleRootItem().takeChildren():
         for i in d.takeChildren():
             i.doc = None
     # group the documents by directory
     dirs = {}
     for d in documents:
         path = d.url().toLocalFile()
         if path:
             dirname, filename = os.path.split(path)
             dirs.setdefault(dirname, []).append((filename, d))
     for dirname in sorted(dirs, key=util.naturalsort):
         diritem = QTreeWidgetItem()
         diritem.setText(0, util.homify(dirname))
         self.tree.addTopLevelItem(diritem)
         diritem.setExpanded(True)
         diritem.setFlags(Qt.ItemIsEnabled)
         diritem.setIcon(0, icons.get('folder-open'))
         for filename, document in sorted(
                 dirs[dirname], key=lambda item: util.naturalsort(item[0])):
             fileitem = QTreeWidgetItem()
             diritem.addChild(fileitem)
             if documentwatcher.DocumentWatcher.instance(
                     document).isdeleted():
                 itemtext = _("[deleted]")
                 icon = "dialog-error"
             else:
                 itemtext = _("[modified]")
                 icon = "document-edit"
             fileitem.setIcon(0, icons.get(icon))
             fileitem.setText(0, filename)
             fileitem.setText(1, itemtext)
             fileitem.doc = document
     # select the item if there is only one
     if len(dirs) == 1 and len(list(dirs.values())[0]) == 1:
         fileitem.setSelected(True)
     self.tree.resizeColumnToContents(0)
     self.tree.resizeColumnToContents(1)
     self.updateButtons()
Beispiel #44
0
 def setDocuments(self, documents):
     """Display the specified documents in the list."""
     # clear the treewidget
     for d in self.tree.invisibleRootItem().takeChildren():
         for i in d.takeChildren():
             i.doc = None
     # group the documents by directory
     dirs = {}
     for d in documents:
         path = d.url().toLocalFile()
         if path:
             dirname, filename = os.path.split(path)
             dirs.setdefault(dirname, []).append((filename, d))
     for dirname in sorted(dirs, key=util.naturalsort):
         diritem = QTreeWidgetItem()
         diritem.setText(0, util.homify(dirname))
         self.tree.addTopLevelItem(diritem)
         diritem.setExpanded(True)
         diritem.setFlags(Qt.ItemIsEnabled)
         diritem.setIcon(0, icons.get('folder-open'))
         for filename, document in sorted(dirs[dirname],
                                           key=lambda item: util.naturalsort(item[0])):
             fileitem = QTreeWidgetItem()
             diritem.addChild(fileitem)
             if documentwatcher.DocumentWatcher.instance(document).isdeleted():
                 itemtext = _("[deleted]") 
                 icon = "dialog-error"
             else:
                 itemtext = _("[modified]")
                 icon = "document-edit"
             fileitem.setIcon(0, icons.get(icon))
             fileitem.setText(0, filename)
             fileitem.setText(1, itemtext)
             fileitem.doc = document
     # select the item if there is only one
     if len(dirs) == 1 and len(list(dirs.values())[0]) == 1:
         fileitem.setSelected(True)
     self.tree.resizeColumnToContents(0)
     self.tree.resizeColumnToContents(1)
     self.updateButtons()
Beispiel #45
0
    def populate(self):
        groups = {}
        count = 0
        provider = Processing.algs[self.providerName]
        algs = provider.values()

        # Add algorithms
        for alg in algs:
            if not alg.showInToolbox:
                continue
            if alg.group in groups:
                groupItem = groups[alg.group]
            else:
                groupItem = QTreeWidgetItem()
                name = alg.i18n_group if alg.i18n_group else "[" + alg.group + "]"
                groupItem.setText(0, name)
                groupItem.setToolTip(0, name)
                groups[alg.group] = groupItem
            algItem = TreeAlgorithmItem(alg)
            groupItem.addChild(algItem)
            count += 1

        actions = Processing.actions[self.providerName]
        for action in actions:
            if action.group in groups:
                groupItem = groups[action.group]
            else:
                groupItem = QTreeWidgetItem()
                groupItem.setText(0, action.group)
                groups[action.group] = groupItem
            algItem = TreeActionItem(action)
            groupItem.addChild(algItem)

        self.setText(
            0,
            self.provider.getDescription() + QCoreApplication.translate(
                "TreeProviderItem", " [{0} geoalgorithms]").format(count))
        self.setToolTip(0, self.text(0))
        for groupItem in groups.values():
            self.addChild(groupItem)
Beispiel #46
0
    def populate(self):
        groups = {}
        count = 0
        provider = Processing.algs[self.providerName]
        algs = provider.values()

        # Add algorithms
        for alg in algs:
            if not alg.showInToolbox:
                continue
            if alg.group in groups:
                groupItem = groups[alg.group]
            else:
                groupItem = QTreeWidgetItem()
                groupItem.setText(0, alg.group)
                groupItem.setToolTip(0, alg.group)
                groups[alg.group] = groupItem
            algItem = TreeAlgorithmItem(alg)
            groupItem.addChild(algItem)
            count += 1

        actions = Processing.actions[self.providerName]
        for action in actions:
            if action.group in groups:
                groupItem = groups[action.group]
            else:
                groupItem = QTreeWidgetItem()
                groupItem.setText(0, action.group)
                groups[action.group] = groupItem
            algItem = TreeActionItem(action)
            groupItem.addChild(algItem)

        self.setText(
            0,
            self.provider.getDescription()
            + QCoreApplication.translate("TreeProviderItem", " [{0} geoalgorithms]").format(count),
        )
        self.setToolTip(0, self.text(0))
        for groupItem in groups.values():
            self.addChild(groupItem)
Beispiel #47
0
 def populateSource(self):
     items = {}
     for stat in self.stat.getStatKeys():
         source = stat[0]
         function = "%s (%s)" % (stat[2], stat[1])
         if source in ("", "profile") or source.startswith("<"):
             continue
         # Create the function child
         child = QTreeWidgetItem([function])
         # Store it in stat hash array
         self.stat.setStatLink(child, stat, TAB_SOURCE)
         if source in items:
             father = items[source]
         else:
             # Create the father
             father = QTreeWidgetItem([source])
             items[source] = father
         father.addChild(child)
     self.sourceTreeWidget.setSortingEnabled(False)
     for value in list(items.values()):
         self.sourceTreeWidget.addTopLevelItem(value)
     self.sourceTreeWidget.setSortingEnabled(True)
 def setPlugins( self, plugins ):
     """
     Loads the plugins for the inputed dialog.
     
     :param      plugins | [<XWizardPlugin>, ..]
     """
     langs = {}
     icons = {}
     
     for plugin in plugins:
         wlang = plugin.wizardType()
         wgrp  = plugin.wizardGroup()
         
         langs.setdefault(wlang, {})
         langs[wlang].setdefault(wgrp, [])
         
         langs[wlang][wgrp].append( plugin )
         
         icons.setdefault(wgrp, plugin.groupIcon(wgrp))
     
     self._plugins = langs
     
     self.uiPluginTREE.clear()
     for wlang in sorted(langs.keys()):
         langitem = QTreeWidgetItem([wlang])
         langitem.setSizeHint(0, QSize(0, 26))
         
         for wgrp in sorted(langs[wlang].keys()):
             grpitem = QTreeWidgetItem([wgrp])
             grpitem.setIcon(0, QIcon(icons[wgrp]))
             grpitem.setSizeHint(0, QSize(0, 26))
             langitem.addChild(grpitem)
         
         folder = QIcon(projexui.resources.find('img/folder_32.png'))
         langitem.setIcon(0, folder)
         
         self.uiPluginTREE.addTopLevelItem(langitem)
         langitem.setExpanded(True)
Beispiel #49
0
    def __init__(self, report):
        super(ReportDialog, self).__init__()
        self.setupUi(self)

        self.actionSaveAll.setIcon(
            QgsApplication.getThemeIcon('/mActionFileSave.svg'))
        self.actionSaveSelected.setIcon(
            QgsApplication.getThemeIcon('/mActionFileSaveAs.svg'))
        self.actionOpenTracker.setIcon(
            QgsApplication.getThemeIcon('/mActionHelpAPI.png'))

        self.actionSaveAll.triggered.connect(lambda: self.saveResults(True))
        self.actionSaveSelected.triggered.connect(
            lambda: self.saveResults(False))

        self.resultsTree.clear()

        results = report.results

        allResults = defaultdict(list)
        for result in results:
            test = result.test
            allResults[test.group].append(result)

        for group, groupResults in allResults.iteritems():
            groupItem = QTreeWidgetItem()
            groupItem.setText(0, group)
            for result in groupResults:
                resultItem = QTreeWidgetItem()
                resultItem.result = result
                resultItem.setText(0, result.test.name)
                resultItem.setForeground(0, self.resultColor[result.status])
                groupItem.addChild(resultItem)
            self.resultsTree.addTopLevelItem(groupItem)

        self.resultsTree.expandAll()
        self.resultsTree.itemClicked.connect(self.itemClicked)
        self.resultsTree.customContextMenuRequested.connect(self.showPopupMenu)
Beispiel #50
0
    def populate(self):
        groups = {}
        count = 0
        provider = Processing.algs[self.providerName]
        algs = provider.values()

        # Add algorithms
        for alg in algs:
            if not alg.showInToolbox:
                continue
            if alg.group in groups:
                groupItem = groups[alg.group]
            else:
                groupItem = QTreeWidgetItem()
                groupItem.setText(0, alg.group)
                groupItem.setToolTip(0, alg.group)
                groups[alg.group] = groupItem
            algItem = TreeAlgorithmItem(alg)
            groupItem.addChild(algItem)
            count += 1

        actions = Processing.actions[self.providerName]
        for action in actions:
            if action.group in groups:
                groupItem = groups[action.group]
            else:
                groupItem = QTreeWidgetItem()
                groupItem.setText(0, action.group)
                groups[action.group] = groupItem
            algItem = TreeActionItem(action)
            groupItem.addChild(algItem)

        self.setText(0, self.provider.getDescription()
                    + ' [' + str(count) + ' geoalgorithms]')
        self.setToolTip(0, self.text(0))
        for groupItem in groups.values():
            self.addChild(groupItem)
Beispiel #51
0
 def reloadTreeGui1(self):
     """加载IPDU"""
     tree=self.trComCfg.topLevelItem(1);
     for index in range(0, tree.childCount()):
         temp=tree.takeChild(0);
         del temp;
     for Ipdu in self.cfg.IPduList:
         item=QTreeWidgetItem(tree,QStringList(Ipdu.name));
         tree.addChild(item);
         for sig in Ipdu.signalList:
             item2=QTreeWidgetItem(item,QStringList(sig.name));
             item.addChild(item2);
         for sig in Ipdu.signalGroupList:
             item2=QTreeWidgetItem(item,QStringList(sig.name));
             item.addChild(item2);
             for grpsig in sig.groupSignalList:
                 item3=QTreeWidgetItem(item2,QStringList(grpsig.name));
                 item2.addChild(item3); 
Beispiel #52
0
class MainDialog(QDialog, Ui_MainDialog):

    """The main dialog of QGIS2Web plugin."""
    items = {}

    def __init__(self, iface):
        QDialog.__init__(self)
        self.setupUi(self)
        self.iface = iface

        self.previewUrl = None
        self.layer_search_combo = None
        self.exporter_combo = None

        self.feedback = FeedbackDialog(self)
        self.feedback.setModal(True)

        stgs = QSettings()

        self.restoreGeometry(stgs.value("qgis2web/MainDialogGeometry",
                                        QByteArray(), type=QByteArray))

        if stgs.value("qgis2web/previewOnStartup", Qt.Checked) == Qt.Checked:
            self.previewOnStartup.setCheckState(Qt.Checked)
        else:
            self.previewOnStartup.setCheckState(Qt.Unchecked)
        if (stgs.value("qgis2web/closeFeedbackOnSuccess", Qt.Checked) ==
                Qt.Checked):
            self.closeFeedbackOnSuccess.setCheckState(Qt.Checked)
        else:
            self.closeFeedbackOnSuccess.setCheckState(Qt.Unchecked)
        self.previewFeatureLimit.setText(
            stgs.value("qgis2web/previewFeatureLimit", "1000"))

        self.paramsTreeOL.setSelectionMode(QAbstractItemView.SingleSelection)
        self.preview = None
        if webkit_available:
            widget = QWebView()
            self.preview = widget
            webview = self.preview.page()
            webview.setNetworkAccessManager(QgsNetworkAccessManager.instance())
            self.preview.settings().setAttribute(
                QWebSettings.DeveloperExtrasEnabled, True)
        else:
            widget = QTextBrowser()
            widget.setText(self.tr('Preview is not available since QtWebKit '
                                   'dependency is missing on your system'))
        self.right_layout.insertWidget(0, widget)
        self.populateConfigParams(self)
        self.populate_layers_and_groups(self)
        self.populateLayerSearch()
        self.populateBasemaps()

        writer = WRITER_REGISTRY.createWriterFromProject()
        self.setStateToWriter(writer)

        self.exporter = EXPORTER_REGISTRY.createFromProject()
        self.exporter_combo.setCurrentIndex(
            self.exporter_combo.findText(self.exporter.name()))
        self.exporter_combo.currentIndexChanged.connect(
            self.exporterTypeChanged)

        self.toggleOptions()
        if webkit_available:
            if self.previewOnStartup.checkState() == Qt.Checked:
                self.autoUpdatePreview()
            self.buttonPreview.clicked.connect(self.previewMap)
        else:
            self.buttonPreview.setDisabled(True)
        self.layersTree.model().dataChanged.connect(self.populateLayerSearch)
        self.ol3.clicked.connect(self.changeFormat)
        self.leaflet.clicked.connect(self.changeFormat)
        self.buttonExport.clicked.connect(self.saveMap)
        readme = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                              "README.md")
        helpText = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                "helpFile.md")
        lines = open(readme, 'r').readlines()
        with open(helpText, 'w') as helpFile:
            for ct, line in enumerate(lines):
                if ct > 4:
                    helpFile.write(line)
            helpFile.close()
        self.helpField.setSource(QUrl.fromLocalFile(helpText))
        if webkit_available:
            self.devConsole = QWebInspector(self.verticalLayoutWidget_2)
            self.devConsole.setFixedHeight(0)
            self.devConsole.setObjectName("devConsole")
            self.devConsole.setPage(self.preview.page())
            self.right_layout.insertWidget(1, self.devConsole)
        self.filter = devToggleFilter()
        self.installEventFilter(self.filter)
        self.setModal(False)

    def changeFormat(self):
        self.autoUpdatePreview()
        self.toggleOptions()

    def exporterTypeChanged(self):
        new_exporter_name = self.exporter_combo.currentText()
        try:
            self.exporter = [
                e for e in EXPORTER_REGISTRY.getExporters()
                if e.name() == new_exporter_name][0]()
        except:
            pass

    def currentMapFormat(self):
        """
        Returns the currently selected map writer type
        """
        return self.getWriterFactory().type()

    def getWriterFactory(self):
        """
        Returns a factory to create the currently selected map writer
        """
        if self.mapFormat.checkedButton() == self.ol3:
            return OpenLayersWriter
        elif self.mapFormat.checkedButton() == self.leaflet:
            return LeafletWriter

    def createWriter(self):
        """
        Creates a writer object reflecting the current settings
        in the dialog
        """
        writer = self.getWriterFactory()()
        (writer.layers, writer.groups, writer.popup,
         writer.visible, writer.json,
         writer.cluster) = self.getLayersAndGroups()
        writer.params = self.getParameters()
        return writer

    def showErrorMessage(self, error):
        """
        Shows an error message in the preview window
        """
        html = "<html>"
        html += "<head></head>"
        html += "<style>body {font-family: sans-serif;}</style>"
        html += "<body><h1>Error</h1>"
        html += "<p>qgis2web produced an error:</p><code>"
        html += error
        html += "</code></body></html>"
        if self.preview:
            self.preview.setHtml(html)

    def showFeedbackMessage(self, title, message):
        """
        Shows a feedback message in the preview window
        """
        html = "<html>"
        html += "<head></head>"
        html += "<style>body {font-family: sans-serif;}</style>"
        html += "<body><h1>{}</h1>".format(title)
        html += "<p>{}</p>".format(message)
        html += "</body></html>"
        if self.preview:
            self.preview.setHtml(html)

    def toggleOptions(self):
        currentWriter = self.getWriterFactory()
        for param, value in specificParams.iteritems():
            treeParam = self.paramsTreeOL.findItems(param,
                                                    (Qt.MatchExactly |
                                                     Qt.MatchRecursive))[0]
            if currentWriter == OpenLayersWriter:
                if value == "OL3":
                    treeParam.setDisabled(False)
                else:
                    treeParam.setDisabled(True)
            else:
                if value == "OL3":
                    treeParam.setDisabled(True)
                else:
                    treeParam.setDisabled(False)
        for option, value in specificOptions.iteritems():
            treeOptions = self.layersTree.findItems(option,
                                                    (Qt.MatchExactly |
                                                     Qt.MatchRecursive))
            for treeOption in treeOptions:
                if currentWriter == OpenLayersWriter:
                    if value == "OL3":
                        treeOption.setDisabled(False)
                    else:
                        treeOption.setDisabled(True)
                else:
                    if value == "OL3":
                        treeOption.setDisabled(True)
                    else:
                        treeOption.setDisabled(False)

    def createPreview(self):
        writer = self.createWriter()
        return writer.write(self.iface,
                            dest_folder=utils.tempFolder()).index_file

    def shouldAutoPreview(self):
        """
        Returns a tuple, with a bool for whether the preview should
        automatically be generated, and a string for explanations
        as to why the preview cannot be automatically generated
        """
        writer = self.createWriter()
        total_features = 0
        for layer in writer.layers:
            if isinstance(layer, QgsVectorLayer):
                total_features += layer.featureCount()

        if total_features > int(self.previewFeatureLimit.text()):
            # Too many features => too slow!
            return (False, self.tr('<p>A large number of features are '
                                   'present in the map. Generating the '
                                   'preview may take some time.</p>'
                                   '<p>Click Update Preview to generate the '
                                   'preview anyway.</p>'))

        return (True, None)

    def autoUpdatePreview(self):
        """
        Triggered when a preview will be automatically generated, i.e.
        not as a result of the user manually clicking the
        Update Preview button.
        """
        (auto_preview, message) = self.shouldAutoPreview()
        if not auto_preview:
            self.showFeedbackMessage(self.tr('Preview Map'), message)
        else:
            self.previewMap()

    def previewMap(self):
        try:
            preview_file = self.createPreview()
            self.loadPreviewFile(preview_file)
        except Exception as e:
            self.showErrorMessage(
                traceback.format_exc().replace("\n", "<br />"))
            QgsMessageLog.logMessage(traceback.format_exc(), "qgis2web",
                                     level=QgsMessageLog.CRITICAL)

    def saveMap(self):
        writer = self.createWriter()
        write_folder = self.exporter.exportDirectory()
        if not write_folder:
            return

        self.feedback.reset()
        self.feedback.show()
        results = writer.write(self.iface,
                               dest_folder=write_folder,
                               feedback=self.feedback)
        self.feedback.showFeedback('Success')
        if self.closeFeedbackOnSuccess.checkState() == Qt.Checked:
            self.feedback.close()
        result = self.exporter.postProcess(results, feedback=self.feedback)
        if result and (not os.environ.get('CI') and
                       not os.environ.get('TRAVIS')):
            webbrowser.open_new_tab(self.exporter.destinationUrl())

    def populate_layers_and_groups(self, dlg):
        """Populate layers on QGIS into our layers and group tree view."""
        root_node = QgsProject.instance().layerTreeRoot()
        tree_groups = []
        tree_layers = root_node.findLayers()
        self.layers_item = QTreeWidgetItem()
        self.layers_item.setText(0, "Layers and Groups")
        self.layersTree.setColumnCount(3)

        for tree_layer in tree_layers:
            layer = tree_layer.layer()
            if layer.type() != QgsMapLayer.PluginLayer:
                try:
                    if layer.type() == QgsMapLayer.VectorLayer:
                        testDump = layer.rendererV2().dump()
                    layer_parent = tree_layer.parent()
                    if layer_parent.parent() is None:
                        item = TreeLayerItem(self.iface, layer,
                                             self.layersTree, dlg)
                        self.layers_item.addChild(item)
                    else:
                        if layer_parent not in tree_groups:
                            tree_groups.append(layer_parent)
                except:
                    QgsMessageLog.logMessage(traceback.format_exc(),
                                             "qgis2web",
                                             level=QgsMessageLog.CRITICAL)

        for tree_group in tree_groups:
            group_name = tree_group.name()
            group_layers = [
                tree_layer.layer() for tree_layer in tree_group.findLayers()]
            item = TreeGroupItem(group_name, group_layers, self.layersTree)
            self.layers_item.addChild(item)

        self.layersTree.addTopLevelItem(self.layers_item)
        self.layersTree.expandAll()
        self.layersTree.resizeColumnToContents(0)
        self.layersTree.resizeColumnToContents(1)
        for i in xrange(self.layers_item.childCount()):
            item = self.layers_item.child(i)
            if item.checkState(0) != Qt.Checked:
                item.setExpanded(False)

    def populateLayerSearch(self):
        self.layer_search_combo.clear()
        self.layer_search_combo.addItem("None")
        (layers, groups, popup, visible,
         json, cluster) = self.getLayersAndGroups()
        for count, layer in enumerate(layers):
            if layer.type() == layer.VectorLayer:
                options = []
                fields = layer.pendingFields()
                for f in fields:
                    fieldIndex = fields.indexFromName(unicode(f.name()))
                    try:
                        formCnf = layer.editFormConfig()
                        editorWidget = formCnf.widgetType(fieldIndex)
                    except:
                        editorWidget = layer.editorWidgetV2(fieldIndex)
                    if editorWidget == QgsVectorLayer.Hidden \
                            or editorWidget == 'Hidden':
                        continue
                    options.append(unicode(f.name()))
                for option in options:
                    displayStr = unicode(layer.name() + ": " + option)
                    self.layer_search_combo.insertItem(0, displayStr)
                    sln = utils.safeName(layer.name())
                    self.layer_search_combo.setItemData(
                        self.layer_search_combo.findText(displayStr),
                        sln + unicode(count))

    def configureExporter(self):
        self.exporter.configure()

    def populateConfigParams(self, dlg):
        """ Populates the dialog with option items and widgets """
        self.items = defaultdict(dict)
        tree = dlg.paramsTreeOL

        configure_export_action = QAction('...', self)
        configure_export_action.triggered.connect(self.configureExporter)

        params = getParams(configure_exporter_action=configure_export_action)
        for group, settings in params.iteritems():
            item = QTreeWidgetItem()
            item.setText(0, group)
            for param, value in settings.iteritems():
                subitem = self.createOptionItem(tree_widget=tree,
                                                parent_item=item,
                                                parameter=param,
                                                default_value=value)
                item.addChild(subitem)
                self.items[group][param] = subitem
            self.paramsTreeOL.addTopLevelItem(item)
            item.sortChildren(0, Qt.AscendingOrder)
        self.paramsTreeOL.expandAll()
        self.paramsTreeOL.resizeColumnToContents(0)
        self.paramsTreeOL.resizeColumnToContents(1)
        self.layer_search_combo.removeItem(1)

    def createOptionItem(self, tree_widget, parent_item,
                         parameter, default_value):
        """create the tree item corresponding to an option parameter"""
        action = None
        if isinstance(default_value, dict):
            action = default_value['action']
            default_value = default_value['option']

        subitem = TreeSettingItem(parent_item, tree_widget,
                                  parameter, default_value, action)
        if parameter == 'Layer search':
            self.layer_search_combo = subitem.combo
        elif parameter == 'Exporter':
            self.exporter_combo = subitem.combo

        return subitem

    def setStateToWriter(self, writer):
        """
        Sets the dialog state to match the specified writer
        """
        self.selectMapFormat(writer)
        self.setStateToParams(writer.params)
        self.setStateForBasemaps(writer.params["Appearance"]["Base layer"])

    def setStateToParams(self, params):
        """
        Sets the dialog state to match the specified parameters
        """
        for group, settings in self.items.iteritems():
            for param, item in settings.iteritems():
                value = params[group][param]
                item.setValue(value)

    def setStateForBasemaps(self, basemaps):
        """
        Sets the dialog state to match the specified basemaps
        """
        for i in range(self.basemaps.count()):
            self.basemaps.item(i).setSelected(False)

        for basemap in basemaps:
            try:
                self.basemaps.findItems(basemap,
                                        (Qt.MatchExactly))[0].setSelected(True)
            except:
                pass

    def populateBasemaps(self):
        """
        Adds entries for all known basemaps to the dialog
        """
        multiSelect = QAbstractItemView.ExtendedSelection
        self.basemaps.setSelectionMode(multiSelect)
        attrFields = []
        for i in range(len(baselayers)):
            for key in baselayers[i]:
                attrFields.append(key)
        self.basemaps.addItems(attrFields)

    def selectMapFormat(self, writer):
        """
        Updates dialog state to match the specified writer format
        """
        self.ol3.setChecked(isinstance(writer, OpenLayersWriter))
        self.leaflet.setChecked(isinstance(writer, LeafletWriter))

    def loadPreviewFile(self, file):
        """
        Loads a web based preview from a local file path
        """
        self.previewUrl = QUrl.fromLocalFile(file)
        if self.preview:
            self.preview.settings().clearMemoryCaches()
            self.preview.setUrl(self.previewUrl)

    def getParameters(self):
        parameters = defaultdict(dict)
        for group, settings in self.items.iteritems():
            for param, item in settings.iteritems():
                parameters[group][param] = item.value()
                if param == "Layer search":
                    parameters["Appearance"]["Search layer"] = (
                        self.layer_search_combo.itemData(
                            self.layer_search_combo.currentIndex()))
        basemaps = [i.text() for i in self.basemaps.selectedItems()]
        parameters["Appearance"]["Base layer"] = basemaps
        return parameters

    def saveParameters(self):
        """
        Saves current dialog state to project
        """
        WRITER_REGISTRY.saveWriterToProject(self.createWriter())
        EXPORTER_REGISTRY.writeToProject(self.exporter)

    def getLayersAndGroups(self):
        layers = []
        groups = {}
        popup = []
        visible = []
        json = []
        cluster = []
        for i in xrange(self.layers_item.childCount()):
            item = self.layers_item.child(i)
            if isinstance(item, TreeLayerItem):
                if item.checkState(0) == Qt.Checked:
                    layers.append(item.layer)
                    popup.append(item.popup)
                    visible.append(item.visible)
                    json.append(item.json)
                    cluster.append(item.cluster)
            else:
                group = item.name
                groupLayers = []
                if item.checkState(0) != Qt.Checked:
                    continue
                for layer in item.layers:
                    groupLayers.append(layer)
                    layers.append(layer)
                    popup.append(utils.NO_POPUP)
                    if item.visible:
                        visible.append(True)
                    else:
                        visible.append(False)
                    if hasattr(item, "json") and item.json:
                        json.append(True)
                    else:
                        json.append(False)
                    if hasattr(item, "cluster") and item.cluster:
                        cluster.append(True)
                    else:
                        cluster.append(False)
                groups[group] = groupLayers[::-1]

        return (layers[::-1],
                groups,
                popup[::-1],
                visible[::-1],
                json[::-1],
                cluster[::-1])

    def closeEvent(self, event):
        self.saveParameters()
        (layers, groups, popup, visible,
         json, cluster) = self.getLayersAndGroups()
        for layer, pop, vis in zip(layers, popup, visible):
            attrDict = {}
            for attr in pop:
                attrDict['attr'] = pop[attr]
                layer.setCustomProperty("qgis2web/popup/" + attr, pop[attr])
                layer.setCustomProperty("qgis2web/Visible", vis)

        QSettings().setValue(
            "qgis2web/MainDialogGeometry", self.saveGeometry())

        QSettings().setValue("qgis2web/previewOnStartup",
                             self.previewOnStartup.checkState())
        QSettings().setValue("qgis2web/closeFeedbackOnSuccess",
                             self.closeFeedbackOnSuccess.checkState())
        QSettings().setValue("qgis2web/previewFeatureLimit",
                             self.previewFeatureLimit.text())
        event.accept()
Beispiel #53
0
    def fillTreeUsingCategories(self):
        providersToExclude = ['model', 'script']
        self.algorithmTree.clear()
        text = unicode(self.searchBox.text())
        groups = {}
        for providerName in Processing.algs.keys():
            provider = Processing.algs[providerName]
            name = 'ACTIVATE_' + providerName.upper().replace(' ', '_')
            if not ProcessingConfig.getSetting(name):
                continue
            if providerName in providersToExclude or \
                    len(ModelerUtils.providers[providerName].actions) != 0:
                continue
            algs = provider.values()

            # add algorithms

            for alg in algs:
                if not alg.showInToolbox:
                    continue
                altgroup, altsubgroup = AlgorithmClassification.getClassification(alg)
                if altgroup is None:
                    continue
                algName = AlgorithmClassification.getDisplayName(alg)
                if text == '' or text.lower() in algName.lower():
                    if altgroup not in groups:
                        groups[altgroup] = {}
                    group = groups[altgroup]
                    if altsubgroup not in group:
                        groups[altgroup][altsubgroup] = []
                    subgroup = groups[altgroup][altsubgroup]
                    subgroup.append(alg)

        if len(groups) > 0:
            mainItem = QTreeWidgetItem()
            mainItem.setText(0, 'Geoalgorithms')
            mainItem.setIcon(0, GeoAlgorithm.getDefaultIcon())
            mainItem.setToolTip(0, mainItem.text(0))
            for (groupname, group) in groups.items():
                groupItem = QTreeWidgetItem()
                groupItem.setText(0, groupname)
                groupItem.setIcon(0, GeoAlgorithm.getDefaultIcon())
                groupItem.setToolTip(0, groupItem.text(0))
                mainItem.addChild(groupItem)
                for (subgroupname, subgroup) in group.items():
                    subgroupItem = QTreeWidgetItem()
                    subgroupItem.setText(0, subgroupname)
                    subgroupItem.setIcon(0, GeoAlgorithm.getDefaultIcon())
                    subgroupItem.setToolTip(0, subgroupItem.text(0))
                    groupItem.addChild(subgroupItem)
                    for alg in subgroup:
                        algItem = TreeAlgorithmItem(alg)
                        subgroupItem.addChild(algItem)

            self.algorithmTree.addTopLevelItem(mainItem)

        for providerName in Processing.algs.keys():
            if providerName not in providersToExclude:
                continue
            name = 'ACTIVATE_' + providerName.upper().replace(' ', '_')
            if not ProcessingConfig.getSetting(name):
                continue
            providerItem = TreeProviderItem(providerName)
            self.algorithmTree.addTopLevelItem(providerItem)
Beispiel #54
0
class SelectLinkForReplace(ui, QDialog):

    def __init__(self, word, onlyClassified):
        super().__init__()
        self.setupUi(self)
        self.local_cn = get_local_connection()
        self.word = word
        print(word)
        self.onlyClassified = onlyClassified
        
        self.filterEdit.setText(self.word)
        self.root = QTreeWidgetItem(self.treeWidget, ['description'])
        self.treeWidget.setRootIndex(self.treeWidget.indexFromItem(self.root))

        self.treeWidget.itemSelectionChanged.connect(self.tree_item_clicked)

        self.AcceptBtn.clicked.connect(self.ok_click)
        self.cancelBtn.clicked.connect(self.cancel_click)

        self.filterEdit.textChanged.connect(self.fill_fields)

        self.selected_uuid = None
        self.name = None

        self.fill_fields()
        self.status = False

    def ok_click(self):
        if self.selected_uuid is not None:
            self.status = True
            self.close()

    def cancel_click(self):
        self.close()

    def fill_fields(self):

        search_word = self.filterEdit.text()
        if search_word.strip() != '':
            search_str = stem_str(search_word)
        else:
            search_str = ''

        query = QSqlQuery(self.local_cn)
        LIMIT = 100
        OFFSET = 0
        query.prepare(show_termins_in_link_selector_query)
        query.bindValue(':search_str', search_str + '%')
        query.bindValue(':linked', 1)
        query.bindValue(':limit', LIMIT.__str__())
        query.bindValue(':offset', OFFSET.__str__())
        if query.exec_():
            self.root.takeChildren()
            while query.next():
                c = QTreeWidgetItem()
                c.setText(0, query.value(0))  # Заглавное слово
                c.setData(1, 0, query.value(1))  # uuid
                self.root.addChild(c)
        else:
            print(query.lastError().text())
            print("not exec")
        self.treeWidget.scrollToTop()

    def tree_item_clicked(self):
        if self.treeWidget.currentItem() is not None:
            self.textEdit.clear()
            self.selected_uuid = self.treeWidget.currentItem().text(1)
            self.name = self.treeWidget.currentItem().text(0)
            if TerminDBUtils.checkTerminExists(self.selected_uuid, self.onlyClassified):
                self.textEdit.insertHtml(TerminDBUtils.getDefinition(self.selected_uuid, self.onlyClassified))
                self.textEdit.setText(self.textEdit.toHtml().replace(" </span>", "</span> "))
            else:
                msg = QMessageBox()
                msg.setIcon(QMessageBox.Warning)
                msg.setText('Запрашиваемый термин не найден в удалённой БД. Возможно он был удален или Вы подключились '
                            'к другой БД. Пожалуйста, обновите список терминов.')
                msg.setWindowTitle('Термин не найден')
                btnyes = msg.addButton("Ок", QMessageBox.YesRole)
                msg.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
                msg.exec_()
                if msg.clickedButton() == btnyes:
                    msg.close()
Beispiel #55
0
class DeviceDialog(QDialog, Ui_DeviceDialog):
    """
        Function and Event handling class for the Ui_DeviceDialog.
    """
    qtcb_enumerate = pyqtSignal(str, str, 'char', type((0, )), type((0, )),
                                int, int)
    qtcb_connected = pyqtSignal(int)

    def __init__(self, parent):
        QDialog.__init__(self, parent, get_modeless_dialog_flags())

        self._logger_window = parent

        self.qtcb_enumerate.connect(self.cb_enumerate)
        self.qtcb_connected.connect(self.cb_connected)

        self.host = None
        self.port = None
        self.secret = None

        self.ipcon = IPConnection()
        self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED,
                                     self.qtcb_connected.emit)
        self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE,
                                     self.qtcb_enumerate.emit)

        self.setupUi(self)

        self.btn_add_device.clicked.connect(self.btn_add_device_clicked)
        self.btn_refresh.clicked.connect(self.btn_refresh_clicked)
        self.btn_close.clicked.connect(self.btn_close_clicked)
        self.tree_widget.itemActivated.connect(self.add_item)

        self.connected_uids = []
        self.available_item = QTreeWidgetItem(['No devices available'])
        self.supported_item = QTreeWidgetItem(['Supported devices'])

        self.tree_widget.addTopLevelItem(self.available_item)
        self.tree_widget.addTopLevelItem(self.supported_item)

        for device_name in device_specs:
            self.supported_item.addChild(QTreeWidgetItem([device_name]))

        self.supported_item.sortChildren(0, Qt.AscendingOrder)
        self.supported_item.setExpanded(True)

    def cb_connected(self, connect_reason):
        self.tree_widget.clearSelection()
        self.available_item.takeChildren()
        self.available_item.setExpanded(True)
        self.available_item.setText(
            0, 'No devices available at {0}:{1}'.format(self.host, self.port))

        self.connected_uids = []

        if self.secret != None:
            self.ipcon.set_auto_reconnect(
                False)  # don't auto-reconnect on authentication error

            try:
                self.ipcon.authenticate(self.secret)
            except:
                try:
                    self.ipcon.disconnect()
                except:
                    pass

                if connect_reason == IPConnection.CONNECT_REASON_AUTO_RECONNECT:
                    extra = ' after auto-reconnect'
                else:
                    extra = ''

                self.available_item.setText(0,
                                            'Could not authenticate' + extra)
                return

            self.ipcon.set_auto_reconnect(True)

        try:
            self.ipcon.enumerate()
        except:
            pass

    def cb_enumerate(self, uid, connected_uid, position, hardware_version,
                     firmware_version, device_identifier, enumeration_type):
        if enumeration_type in [IPConnection.ENUMERATION_TYPE_AVAILABLE,
                                IPConnection.ENUMERATION_TYPE_CONNECTED] and \
           uid not in self.connected_uids:
            try:
                display_name = device_factory.get_device_display_name(
                    device_identifier)
            except KeyError:
                return  # unknown device identifier

            if display_name in device_specs:
                self.connected_uids.append(uid)
                self.available_item.addChild(
                    QTreeWidgetItem(['{0} [{1}]'.format(display_name, uid)]))
                self.available_item.setText(
                    0, 'Devices available at {0}:{1}'.format(
                        self.host, self.port))
                self.available_item.sortChildren(0, Qt.AscendingOrder)
        else:
            if uid in self.connected_uids:
                self.connected_uids.remove(uid)

            for i in range(self.available_item.childCount()):
                child = self.available_item.child(i)

                if '[{0}]'.format(uid) in child.text(0):
                    self.available_item.takeChild(i)
                    break

            if self.available_item.childCount() == 0:
                self.available_item.setText(
                    0, 'No devices available at {0}:{1}'.format(
                        self.host, self.port))

    def btn_add_device_clicked(self):
        for item in self.tree_widget.selectedItems():
            if item == self.available_item or item == self.supported_item:
                continue

            self._logger_window.add_device_to_tree(
                self.create_device_config(item.text(0)))

    def btn_refresh_clicked(self):
        try:
            self.ipcon.disconnect()
        except:
            pass

        self.tree_widget.clearSelection()
        self.available_item.takeChildren()
        self.available_item.setExpanded(True)

        self.connected_uids = []
        self.host = self._logger_window.combo_host.currentText()
        self.port = self._logger_window.spin_port.value()

        if self._logger_window.check_authentication.isChecked():
            try:
                self.secret = self._logger_window.edit_secret.text().encode(
                    'ascii')
            except:
                self.secret = None
        else:
            self.secret = None

        try:
            self.ipcon.connect(self.host, self.port)
            self.available_item.setText(
                0,
                'No devices available at {0}:{1}'.format(self.host, self.port))
        except:
            self.available_item.setText(
                0, 'Could not connect to {0}:{1}'.format(self.host, self.port))

    def btn_close_clicked(self):
        self.close()

    def add_item(self, item):
        if item == self.available_item or item == self.supported_item:
            return

        self._logger_window.add_device_to_tree(
            self.create_device_config(item.text(0)))

    def create_device_config(self, item_text):
        name, uid = Utilities.parse_device_name(item_text)  # FIXME
        device_spec = device_specs[name]

        if uid == None:  # FIXME
            uid = ''

        device = {
            'host': 'default',
            'name': name,
            'uid': uid,
            'values': {},
            'options': {}
        }

        for value_spec in device_spec['values']:
            device['values'][value_spec['name']] = {'interval': 0}

            if value_spec['subvalues'] != None:
                device['values'][value_spec['name']]['subvalues'] = {}

                for subvalue_name in value_spec['subvalues']:
                    device['values'][
                        value_spec['name']]['subvalues'][subvalue_name] = True

        if device_spec['options'] != None:
            for option_spec in device_spec['options']:
                device['options'][option_spec['name']] = {
                    'value': option_spec['default']
                }

        return device
Beispiel #56
0
    def populate_filter_tree(self):
        """ Populates the filter tree widget from the filter data. Called
        automatically from other methods when necessary.
        """
        self.filterTreeWidget.clear()

        for name, manager in sorted(self.filter_managers.items()):
            top = QTreeWidgetItem(self.filterTreeWidget)
            top.setText(0, name)
            top.setFlags(Qt.ItemIsEnabled | Qt.ItemIsDropEnabled)
            top.setData(1, Qt.UserRole, self.FilterTreeRoleTop)
            top.setTextColor(0, Qt.gray)
            top.setChildIndicatorPolicy(QTreeWidgetItem.ShowIndicator)
            self.filterTreeWidget.addTopLevelItem(top)
            if manager.list_items():
                top.setExpanded(True)

            for i in manager.list_items():
                if isinstance(i[1], manager.FilterGroup):
                    group = QTreeWidgetItem(top)
                    group.setText(0, i[0])
                    group.setData(1, Qt.UserRole, self.FilterTreeRoleGroup)
                    group.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable
                                   | Qt.ItemIsDropEnabled
                                   | Qt.ItemIsDragEnabled)
                    group.setChildIndicatorPolicy(
                        QTreeWidgetItem.ShowIndicator)
                    if i[1].list_items():
                        group.setExpanded(True)
                    top.addChild(group)

                    for f in i[1].list_items():
                        item = QTreeWidgetItem(group)
                        item.setText(0, f[0])
                        if f[1].active:
                            item.setData(0, CheckableItemDelegate.CheckedRole,
                                         True)
                        else:
                            item.setData(0, CheckableItemDelegate.CheckedRole,
                                         False)
                        if i[1].exclusive:
                            item.setData(0,
                                         CheckableItemDelegate.CheckTypeRole,
                                         CheckableItemDelegate.RadioCheckType)
                        else:
                            item.setData(
                                0, CheckableItemDelegate.CheckTypeRole,
                                CheckableItemDelegate.CheckBoxCheckType)
                        item.setData(1, Qt.UserRole, self.FilterTreeRoleFilter)
                        item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable
                                      | Qt.ItemIsDragEnabled)
                        group.addChild(item)
                else:
                    item = QTreeWidgetItem(top)
                    item.setText(0, i[0])
                    if i[1].active:
                        item.setData(0, CheckableItemDelegate.CheckedRole,
                                     True)
                    else:
                        item.setData(0, CheckableItemDelegate.CheckedRole,
                                     False)
                    item.setData(0, CheckableItemDelegate.CheckTypeRole,
                                 CheckableItemDelegate.CheckBoxCheckType)
                    item.setData(1, Qt.UserRole, self.FilterTreeRoleFilter)
                    item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable
                                  | Qt.ItemIsDragEnabled)
                    top.addChild(item)
Beispiel #57
0
    def addOverlaysToTreeWidget(self, overlayDict, forbiddenOverlays,
                                preSelectedOverlays, singleOverlaySelection):
        self.singleOverlaySelection = singleOverlaySelection
        testItem = QTreeWidgetItem("a")
        for keys in overlayDict.keys():
            if overlayDict[keys] in forbiddenOverlays:
                continue
            else:
                boolStat = False
                split = keys.split("/")
            for i in range(len(split)):
                if len(split) == 1:
                    newItemsChild = OverlayTreeWidgetItem(
                        overlayDict[keys], keys)
                    self.addTopLevelItem(newItemsChild)
                    boolStat = False
                    if overlayDict[keys] in preSelectedOverlays:
                        newItemsChild.setCheckState(0, Qt.Checked)
                    else:
                        newItemsChild.setCheckState(0, Qt.Unchecked)

                elif i + 1 == len(split) and len(split) > 1:
                    newItemsChild = OverlayTreeWidgetItem(
                        overlayDict[keys], keys)
                    testItem.addChild(newItemsChild)
                    if overlayDict[keys] in preSelectedOverlays:
                        newItemsChild.setCheckState(0, Qt.Checked)
                    else:
                        newItemsChild.setCheckState(0, Qt.Unchecked)

                elif self.topLevelItemCount() == 0 and i + 1 < len(split):
                    newItem = QTreeWidgetItem([split[i]])
                    self.addTopLevelItem(newItem)
                    testItem = newItem
                    boolStat = True

                elif self.topLevelItemCount() != 0 and i + 1 < len(split):
                    if boolStat == False:
                        for n in range(self.topLevelItemCount()):
                            if self.topLevelItem(n).text(0) == split[i]:
                                testItem = self.topLevelItem(n)
                                boolStat = True
                                break
                            elif n + 1 == self.topLevelItemCount():
                                newItem = QTreeWidgetItem([split[i]])
                                self.addTopLevelItem(newItem)
                                testItem = newItem
                                boolStat = True

                    elif testItem.childCount() == 0:
                        newItem = QTreeWidgetItem([split[i]])
                        testItem.addChild(newItem)
                        testItem = newItem
                        boolStat = True
                    else:
                        for x in range(testItem.childCount()):
                            if testItem.child(x).text(0) == split[i]:
                                testItem = testItem.child(x)
                                boolStat = True
                                break
                            elif x + 1 == testItem.childCount():
                                newItem = QTreeWidgetItem([split[i]])
                                testItem.addChild(newItem)
                                testItem = newItem
                                boolStat = True
Beispiel #58
0
    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()