Ejemplo n.º 1
0
class ResultsDialog(BASE, WIDGET):

    def __init__(self):
        super(ResultsDialog, self).__init__(None)
        self.setupUi(self)

        self.keyIcon = QIcon()
        self.keyIcon.addPixmap(self.style().standardPixmap(QStyle.SP_FileIcon))

        self.tree.itemClicked.connect(self.changeResult)

        self.fillTree()

        if self.lastUrl:
            self.webView.load(self.lastUrl)

    def fillTree(self):
        elements = ProcessingResults.getResults()
        if len(elements) == 0:
            self.lastUrl = None
            return
        for element in elements:
            item = TreeResultItem(element)
            item.setIcon(0, self.keyIcon)
            self.tree.addTopLevelItem(item)
        self.lastUrl = QUrl(elements[-1].filename)

    def changeResult(self):
        item = self.tree.currentItem()
        if isinstance(item, TreeResultItem):
            url = QUrl(item.filename)
            self.webView.load(url)
Ejemplo n.º 2
0
class ResultsDialog(BASE, WIDGET):
    def __init__(self):
        super(ResultsDialog, self).__init__(None)
        self.setupUi(self)

        self.keyIcon = QIcon()
        self.keyIcon.addPixmap(self.style().standardPixmap(QStyle.SP_FileIcon))

        self.tree.currentItemChanged.connect(self.changeResult)

        self.fillTree()

        if self.lastUrl:
            self.txtResults.setHtml(self.loadResults(self.lastUrl))

    def fillTree(self):
        elements = ProcessingResults.getResults()
        if len(elements) == 0:
            self.lastUrl = None
            return
        for element in elements:
            item = TreeResultItem(element)
            item.setIcon(0, self.keyIcon)
            self.tree.addTopLevelItem(item)
        self.lastUrl = elements[-1].filename

    def changeResult(self):
        item = self.tree.currentItem()
        if isinstance(item, TreeResultItem):
            self.txtResults.setHtml(self.loadResults(item.filename))

    def loadResults(self, fileName):
        with codecs.open(fileName, encoding='utf-8') as f:
            content = f.read()
        return content
Ejemplo n.º 3
0
    def initGui(self):
        # Create Graphical User Interface
        icon = QIcon()
        icon.addPixmap(QPixmap(os.path.dirname(__file__) + "/icon.png"),
                       QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        self.setWindowModality(Qt.WindowModal)
        self.setWindowFlags(Qt.Window
                            | Qt.WindowSystemMenuHint
                            | Qt.WindowMinimizeButtonHint
                            | Qt.WindowMaximizeButtonHint
                            | Qt.WindowCloseButtonHint)

        self.resize(520, 520)

        self.label = QLabel(self)
        self.label.setGeometry(QRect(10, 20, 500, 20))
        font = QFont()
        font.setPointSize(14)
        font.setUnderline(True)
        self.label.setFont(font)
        self.label.setAlignment(Qt.AlignCenter)
        self.label_2 = QLabel(self)
        self.label_2.setGeometry(QRect(10, 70, 500, 16))
        self.label_3 = QLabel(self)
        self.label_3.setGeometry(QRect(10, 90, 500, 16))
        self.label_4 = QLabel(self)
        self.label_4.setGeometry(QRect(10, 110, 500, 16))
        self.pushButton = QPushButton(self)
        self.pushButton.setGeometry(QRect(50, 150, 121, 24))
        self.comboBox = QComboBox(self)
        self.comboBox.setGeometry(QRect(240, 150, 121, 24))
        self.comboBox.addItem("Paso Malla 25m")
        self.comboBox.addItem("Paso Malla 200m")
        self.comboBox.addItem("Paso Malla 500m")
        self.comboBox.addItem("Paso Malla 1.000m")
        self.bt_view_map = QPushButton(self)
        self.bt_view_map.setGeometry(QRect(370, 150, 121, 24))
        self.profile_jpg = QLabel(self)
        self.profile_jpg.setGeometry(QRect(20, 200, 480, 180))

        self.message_box = QTextEdit(self)
        self.message_box.setGeometry(QRect(10, 400, 500, 111))
        self.label.setText("KML / GPX TO 3D")
        self.label_2.setText(
            "Convert a GPX file without elevation, in a GPX and KML with elevation. It's only for Spain."
        )
        self.label_3.setText(
            "Convierte un GPX sin elevación, en un GPX y KML con elevación.")
        self.label_4.setText(
            "Es solo para España ya que utiliza el servicio WCS del Instituto Geografico Nacional"
        )
        self.pushButton.setText("File / Fichero")
        self.bt_view_map.setText("Map / Mapa")

        self.pushButton.clicked.connect(self.select_file)
        self.bt_view_map.clicked.connect(
            lambda: see_map(self.Output_KML_File).exec_())
Ejemplo n.º 4
0
    def _createDocNameItem(self, docName):
        """
        Create a template document standard item.
        """
        # Set icon
        icon = QIcon()
        icon.addPixmap(GuiUtils.get_icon_pixmap("document.png"), QIcon.Normal,
                       QIcon.Off)

        dnItem = QStandardItem(icon, docName)

        return dnItem
Ejemplo n.º 5
0
    def _createNewUserMapping(self, username):
        '''
        Adds a new user to the list of user mappings
        '''
        # Set icon
        icon = QIcon()
        icon.addPixmap(GuiUtils.get_icon_pixmap("user.png"), QIcon.Normal, QIcon.Off)

        userItem = QStandardItem(icon, username)
        userItem.setCheckable(True)
        userItem.setCheckState(Qt.Unchecked)

        return userItem
Ejemplo n.º 6
0
    def _createNewRoleItem(self, rolename):
        '''
        Creates a custom role item for use in a QStandardItemModel
        '''
        # Set icon
        icon = QIcon()
        icon.addPixmap(GuiUtils.get_icon_pixmap("roles.png"), QIcon.Normal,
                       QIcon.Off)

        roleItem = QStandardItem(icon, rolename)
        roleItem.setCheckable(True)
        roleItem.setCheckState(Qt.Unchecked)

        return roleItem
Ejemplo n.º 7
0
    def addBtnDel(self, createButton):
        if createButton is False:
            self.row.addSpacing(33)
            return
        self.delBtn = QPushButton(self.widget)
        self.delBtn.setMaximumSize(QSize(27, 27))
        icon = QIcon()
        icon.addPixmap(QPixmap(PoleRow.ICON_DEL_ROW), QIcon.Normal, QIcon.Off)
        self.delBtn.setIcon(icon)
        self.delBtn.setIconSize(QSize(16, 16))
        self.delBtn.setToolTip(self.tr('Loescht die Stuetze'))
        self.delBtn.setAutoDefault(False)
        self.row.addWidget(self.delBtn)

        self.delBtn.clicked.connect(lambda x: self.parent.onRowDel(self.index))
Ejemplo n.º 8
0
    def addBtnPlus(self, createButton):
        if createButton is False:
            self.row.addSpacing(33)
            return
        self.addBtn = QPushButton(self.widget)
        self.addBtn.setMaximumSize(QSize(27, 27))
        icon = QIcon()
        icon.addPixmap(QPixmap(PoleRow.ICON_ADD_ROW), QIcon.Normal, QIcon.Off)
        self.addBtn.setIcon(icon)
        self.addBtn.setIconSize(QSize(16, 16))
        self.addBtn.setToolTip(
            self.tr('Fuegt eine neue Stuetze nach dieser hinzu'))
        self.addBtn.setAutoDefault(False)
        self.row.addWidget(self.addBtn)

        self.addBtn.clicked.connect(lambda x: self.parent.onRowAdd(self.index))
Ejemplo n.º 9
0
    def setupUi(self, PostNAS_SearchDialogBase):
        PostNAS_SearchDialogBase.setObjectName(
            _fromUtf8("PostNAS_SearchDialogBase"))
        PostNAS_SearchDialogBase.resize(501, 337)
        self.gridLayout = QGridLayout(PostNAS_SearchDialogBase)
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
        self.treeWidget = QTreeWidget(PostNAS_SearchDialogBase)
        self.treeWidget.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.treeWidget.setHeaderHidden(True)
        self.treeWidget.setObjectName(_fromUtf8("treeWidget"))
        self.treeWidget.headerItem().setText(0, _fromUtf8("1"))
        self.gridLayout.addWidget(self.treeWidget, 1, 0, 1, 3)
        self.lineEdit = QLineEdit(PostNAS_SearchDialogBase)
        self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
        self.gridLayout.addWidget(self.lineEdit, 0, 0, 1, 3)
        self.showButton = QToolButton(PostNAS_SearchDialogBase)
        self.showButton.setEnabled(False)
        icon = QtGui.QIcon()
        icon.addPixmap(
            QPixmap(_fromUtf8(":/plugins/PostNAS_Search/search_16x16.png")),
            QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.showButton.setIcon(icon)
        self.showButton.setObjectName(_fromUtf8("showButton"))
        self.gridLayout.addWidget(self.showButton, 2, 2, 1, 1)
        self.resetButton = QToolButton(PostNAS_SearchDialogBase)
        self.resetButton.setEnabled(False)
        icon1 = QIcon()
        icon1.addPixmap(
            QtGui.QPixmap(
                _fromUtf8(":/plugins/PostNAS_Search/marker-delete.png")),
            QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.resetButton.setIcon(icon1)
        self.resetButton.setObjectName(_fromUtf8("resetButton"))
        self.gridLayout.addWidget(self.resetButton, 2, 1, 1, 1)

        self.retranslateUi(PostNAS_SearchDialogBase)
        QtCore.QMetaObject.connectSlotsByName(PostNAS_SearchDialogBase)
Ejemplo n.º 10
0
    def __init__(self, canvas, pare=None):
        """[summary]
        Arguments:
            canvas {[QgsMapCanvas]} -- [El canvas que es vol gestionar]


        """
        self.pare = pare
        self.canvas = canvas
        QWidget.__init__(self)

        # Leemos un fichero serializado para cargar sus ubicaciones en data
        try:
            with open(fic_guardar_arbre, 'rb') as fga:
                data = pickle.load(fga)
                fga.close()
        except:
            data = []

        # Instanciamos ARBOL ************************************************************+*****
        self.arbre = QTreeView()

        # Ponemos menu contextual l arbol
        self.arbre.setContextMenuPolicy(Qt.ActionsContextMenu)
        self.actEsborrar = QAction("Esborrar branca", self)
        self.actEsborrar.setStatusTip("Esborrar")
        self.actEsborrar.triggered.connect(self.esborrarNode)
        self.arbre.addAction(self.actEsborrar)

        self.actExpand = QAction("Expandeix/Contreu Tot", self)
        self.actExpand.setStatusTip("Expand")
        self.actExpand.triggered.connect(self.expand_all)
        self.arbre.addAction(self.actExpand)

        self.actClear = QAction("Esborrar arbre", self)
        self.actClear.setStatusTip("Clear")
        self.actClear.triggered.connect(self.clear_all)
        self.arbre.addAction(self.actClear)

        # Permitimos arrastre de ramas en arbol
        self.arbre.setDragDropMode(
            QAbstractItemView.InternalMove)  #  4atencion  internal
        # Amaguem (o no) les capçaleres. False és que no s'amaguen.
        # self.arbre.setHeaderHidden(True)  #aqui
        # self.arbre.setColumnWidth(0,8000)
        # self.arbre.setHorizontalScrollBarPolicy(1)

        self.arbre.clicked.connect(self._clickArbre)

        # Fem visible l'arbre
        self.arbre.show()

        # Instanciamos MODELO *********************************************************************
        self.model = StandardItemModel_mio(data, ubicacions=self)

        # asignamos al arbol el modelo
        self.arbre.setModel(self.model)

        #Amaguem totes les columnes menys la primera
        for i in range(self.model.columnCount()):
            if i != 0:
                self.arbre.setColumnHidden(
                    i, False
                )  # atencion, si oculto columnas no puedo ver coordenadas de los hijos

        # Connectem el click de l'arbre a la funció _clickArbre

        # no_se
        self.selectionModel = self.arbre.selectionModel()

        # Cal un invisibleRootItem  qu eés la arrel del arbre d'on penjen els elements de la base.
        self.arrelModel = self.model.invisibleRootItem()

        # Definim els labels del arbre.
        self.labels = ['Ubicació', 'xMin', 'yMin', 'xMax', 'yMax', 'Projecte']
        # En funció  d'aquests labels s'estableix el numero de columnes que tindrà el model (i l'arbre)
        self.model.setColumnCount(len(self.labels))
        # Coloquem els labels com a headers del model (i l'arbre)
        self.model.setHorizontalHeaderLabels(self.labels)

        # ELEMENTOS GRAFICOS DE LA CLASE
        # Definim un lineEdit, li afegim un tooltip i el connectem a una funció quan es premi Return
        self.leUbicacions = QLineEdit()
        self.leUbicacions.setToolTip(
            'Escriu el nom de la ubicació i prem Return')
        self.leUbicacions.returnPressed.connect(self._novaUbicacio)

        #Definimos un boton para guardar las ubicaciones
        icon = QIcon()
        fichero = './imatges/guardar.png'
        icon.addPixmap(QPixmap(fichero))
        # icon.addPixmap(QPixmap("D:/projectes_py/qVista/imatges/guardar.png"))

        # self.boton_1 = QPushButton(icon,'')
        # self.boton_1.setToolTip("Desar ubicacions")
        # self.boton_1.setMaximumSize(QSize(20,20))
        # self.boton_1.show()
        # self.boton_1.clicked.connect(self.model.exportData)

        self.lblubicacio = QLabel('Ubicació:')

        # Creamos un caja de diseño vertical que s'aplica al widget QvUbicacions
        self.layVUbicacions = QVBoxLayout(self)
        # Creamos una caja de diseño horizontal
        self.layHUbicacions = QHBoxLayout()
        # incluimos en la caja horizontal el line edit y el boton (entran de izquierda a derecha)
        self.layHUbicacions.addWidget(self.lblubicacio)
        self.layHUbicacions.addWidget(self.leUbicacions)
        # self.layHUbicacions.addWidget(self.boton_1)  # y colocacion en contenidor horizontal

        # incluimos en caja vertical el la caja horizontal y el arbol  (entran desde abajo)
        self.layVUbicacions.addLayout(self.layHUbicacions)
        self.layVUbicacions.addWidget(self.arbre)

        # Podriem afegir un frame (fBotonera), sobre el que carregar botons
        # self.layUbicacions.addWidget(self.fBotonera)

        # PARA QUE HAGA CASO HA DE PONERSE ESTAS LINEAS POST .SETMODEL
        self.arbre.setHeaderHidden(True)  #aqui
        self.arbre.setColumnWidth(0, 8000)
        self.arbre.setHorizontalScrollBarPolicy(1)
Ejemplo n.º 11
0
class ConfigDialog(BASE, WIDGET):
    def __init__(self, toolbox):
        super(ConfigDialog, self).__init__(None)
        self.setupUi(self)

        self.toolbox = toolbox
        self.groupIcon = QIcon()
        self.groupIcon.addPixmap(
            self.style().standardPixmap(QStyle.SP_DirClosedIcon), QIcon.Normal,
            QIcon.Off)
        self.groupIcon.addPixmap(
            self.style().standardPixmap(QStyle.SP_DirOpenIcon), QIcon.Normal,
            QIcon.On)

        if hasattr(self.searchBox, 'setPlaceholderText'):
            self.searchBox.setPlaceholderText(self.tr('Search...'))

        self.model = QStandardItemModel()
        self.tree.setModel(self.model)

        self.delegate = SettingDelegate()
        self.tree.setItemDelegateForColumn(1, self.delegate)

        self.searchBox.textChanged.connect(self.textChanged)

        self.fillTree()

        self.tree.expanded.connect(self.adjustColumns)

    def textChanged(self):
        text = unicode(self.searchBox.text().lower())
        self._filterItem(self.model.invisibleRootItem(), text)
        if text:
            self.tree.expandAll()
        else:
            self.tree.collapseAll()

    def _filterItem(self, item, text):
        if item.hasChildren():
            show = False
            for i in xrange(item.rowCount()):
                child = item.child(i)
                showChild = self._filterItem(child, text)
                show = (showChild or show)
            self.tree.setRowHidden(item.row(), item.index().parent(), not show)
            return show

        elif isinstance(item, QStandardItem):
            hide = bool(text) and (text not in item.text().lower())
            self.tree.setRowHidden(item.row(), item.index().parent(), hide)
            return not hide

    def fillTree(self):
        self.fillTreeUsingProviders()

    def fillTreeUsingProviders(self):
        self.items = {}
        self.model.clear()
        self.model.setHorizontalHeaderLabels(
            [self.tr('Setting'), self.tr('Value')])

        settings = ProcessingConfig.getSettings()

        rootItem = self.model.invisibleRootItem()
        """
        Filter 'General', 'Models' and 'Scripts' items
        """
        priorityKeys = [
            self.tr('General'),
            self.tr('Models'),
            self.tr('Scripts')
        ]
        for group in priorityKeys:
            groupItem = QStandardItem(group)
            icon = ProcessingConfig.getGroupIcon(group)
            groupItem.setIcon(icon)
            groupItem.setEditable(False)
            emptyItem = QStandardItem()
            emptyItem.setEditable(False)

            rootItem.insertRow(0, [groupItem, emptyItem])
            # add menu item only if it has any search matches
            for setting in settings[group]:
                if setting.hidden or setting.name.startswith("MENU_"):
                    continue

                labelItem = QStandardItem(setting.description)
                labelItem.setIcon(icon)
                labelItem.setEditable(False)
                self.items[setting] = SettingItem(setting)
                groupItem.insertRow(0, [labelItem, self.items[setting]])
        """
        Filter 'Providers' items
        """
        providersItem = QStandardItem(self.tr('Providers'))
        icon = QIcon(os.path.join(pluginPath, 'images', 'alg.png'))
        providersItem.setIcon(icon)
        providersItem.setEditable(False)
        emptyItem = QStandardItem()
        emptyItem.setEditable(False)

        rootItem.insertRow(0, [providersItem, emptyItem])
        for group in settings.keys():
            if group in priorityKeys or group == menusSettingsGroup:
                continue

            groupItem = QStandardItem(group)
            icon = ProcessingConfig.getGroupIcon(group)
            groupItem.setIcon(icon)
            groupItem.setEditable(False)

            for setting in settings[group]:
                if setting.hidden:
                    continue

                labelItem = QStandardItem(setting.description)
                labelItem.setIcon(icon)
                labelItem.setEditable(False)
                self.items[setting] = SettingItem(setting)
                groupItem.insertRow(0, [labelItem, self.items[setting]])

            emptyItem = QStandardItem()
            emptyItem.setEditable(False)
            providersItem.appendRow([groupItem, emptyItem])
        """
        Filter 'Menus' items
        """
        menusItem = QStandardItem(self.tr('Menus (requires restart)'))
        icon = QIcon(os.path.join(pluginPath, 'images', 'menu.png'))
        menusItem.setIcon(icon)
        menusItem.setEditable(False)
        emptyItem = QStandardItem()
        emptyItem.setEditable(False)

        rootItem.insertRow(0, [menusItem, emptyItem])

        providers = Processing.providers
        for provider in providers:
            providerDescription = provider.getDescription()
            groupItem = QStandardItem(providerDescription)
            icon = provider.getIcon()
            groupItem.setIcon(icon)
            groupItem.setEditable(False)

            for alg in provider.algs:
                algItem = QStandardItem(alg.i18n_name or alg.name)
                algItem.setIcon(icon)
                algItem.setEditable(False)
                try:
                    settingMenu = ProcessingConfig.settings[
                        "MENU_" + alg.commandLineName()]
                    settingButton = ProcessingConfig.settings[
                        "BUTTON_" + alg.commandLineName()]
                    settingIcon = ProcessingConfig.settings[
                        "ICON_" + alg.commandLineName()]
                except:
                    continue
                self.items[settingMenu] = SettingItem(settingMenu)
                self.items[settingButton] = SettingItem(settingButton)
                self.items[settingIcon] = SettingItem(settingIcon)
                menuLabelItem = QStandardItem("Menu path")
                menuLabelItem.setEditable(False)
                buttonLabelItem = QStandardItem("Add button in toolbar")
                buttonLabelItem.setEditable(False)
                iconLabelItem = QStandardItem("Icon")
                iconLabelItem.setEditable(False)
                emptyItem = QStandardItem()
                emptyItem.setEditable(False)
                algItem.insertRow(0, [menuLabelItem, self.items[settingMenu]])
                algItem.insertRow(0,
                                  [buttonLabelItem, self.items[settingButton]])
                algItem.insertRow(0, [iconLabelItem, self.items[settingIcon]])
                groupItem.insertRow(0, [algItem, emptyItem])

            emptyItem = QStandardItem()
            emptyItem.setEditable(False)

            menusItem.appendRow([groupItem, emptyItem])

        self.tree.sortByColumn(0, Qt.AscendingOrder)
        self.adjustColumns()

    def accept(self):
        for setting in self.items.keys():
            if isinstance(setting.value, bool):
                setting.setValue(
                    self.items[setting].checkState() == Qt.Checked)
            else:
                try:
                    setting.setValue(unicode(self.items[setting].text()))
                except ValueError as e:
                    QMessageBox.warning(
                        self, self.tr('Wrong value'),
                        self.tr('Wrong value for parameter "%s":\n\n%s' %
                                (setting.description, unicode(e))))
                    return
            setting.save()
        Processing.updateAlgsList()
        settingsWatcher.settingsChanged.emit()
        updateMenus()

        QDialog.accept(self)

    def adjustColumns(self):
        self.tree.resizeColumnToContents(0)
        self.tree.resizeColumnToContents(1)
Ejemplo n.º 12
0
class AdjustmentDialogThresholds(QObject):

    COLOR_ERROR = QColor(224, 103, 103)
    COLOR_ATTENTION = QColor(237, 148, 76)
    COLOR_NEUTRAL = QColor(255, 255, 255)
    COLOR = {1: COLOR_NEUTRAL, 2: COLOR_ATTENTION, 3: COLOR_ERROR}

    sig_clickedRow = pyqtSignal(int)

    def __init__(self, parent, datasetSize):
        """
        :type parent: gui.adjustmentDialog.AdjustmentDialog
        """
        super().__init__()
        self.parent = parent
        self.tbl = self.parent.tableThresholds
        self.model = QStandardItemModel(datasetSize[0], datasetSize[1],
                                        self.tbl)
        self.initState = True
        self.thresholdExeeded = False
        self.tbl.setModel(self.model)
        self.tbl.resizeColumnsToContents()
        self.tbl.resizeRowsToContents()
        # Icons
        self.iconOk = QIcon()
        self.iconOk.addPixmap(
            QPixmap(":/plugins/SeilaplanPlugin/gui/icons/icon_green.png"),
            QIcon.Normal, QIcon.Off)
        self.iconErr = QIcon()
        self.iconErr.addPixmap(
            QPixmap(
                ":/plugins/SeilaplanPlugin/gui/icons/icon_exclamation.png"),
            QIcon.Normal, QIcon.Off)

        self.tbl.clicked.connect(self.onClick)

    def populate(self, header, dataset, valueColumn):
        self.model.setHorizontalHeaderLabels(header)
        self.tbl.hideColumn(5)

        # Insert data into cells
        for i, rowData in enumerate(dataset):
            for j, cellData in enumerate(rowData):
                if j == 0:
                    # Create clickable info button in first column
                    btnWidget = self.createInfoBtn(cellData)
                    self.tbl.setIndexWidget(self.model.index(i, j), btnWidget)
                    continue
                if j == 5 and isinstance(cellData, dict):
                    loclen = len(cellData['loc'])
                    if loclen > 0:
                        # Set background color for cells where threshold is
                        #  exceeded
                        color = self.COLOR[max(cellData['color'] or [1])]
                        self.colorBackground(i, valueColumn, color)
                    cellData = loclen
                item = QStandardItem(cellData)
                self.model.setItem(i, j, item)
                self.model.setData(self.model.index(i, j), cellData)

        # Adjust column widths
        self.tbl.resizeColumnsToContents()
        for idx in range(2, self.model.columnCount()):
            currSize = self.tbl.sizeHintForColumn(idx)
            self.tbl.setColumnWidth(idx, max(currSize, 100))
        self.tbl.setFocusPolicy(Qt.NoFocus)
        self.updateTabIcon()

    def updateData(self, row, col, newVal):
        # Update background color of new values
        if col == 5 and isinstance(newVal, dict):
            locLen = len(newVal['loc'])
            color = self.COLOR[max(newVal['color'] or [1])]
            self.colorBackground(row, 4, color)
            newVal = locLen
        # Update value itself
        self.model.setData(self.model.index(row, col), newVal)
        self.updateTabIcon()

        # Remove the background color from initially calculated
        # cable line data
        if self.initState:
            self.initState = False
            for row in range(self.model.rowCount()):
                self.colorBackground(row, 3, self.COLOR_NEUTRAL)

    def colorBackground(self, row, col, color):
        self.model.setData(self.model.index(row, col), QBrush(color),
                           Qt.BackgroundRole)

    def updateTabIcon(self):
        """ Updates icon of QTabWidget with an exclamation mark or check
        mark depending on presents of exceeded thresholds."""
        thresholdExceeded = False
        for i in range(0, self.model.rowCount()):
            if i == 2:
                # Dont check thresholds for 'Sattelkraft'
                continue
            data = self.model.data(self.model.index(i, 5))
            if data and data > 0:
                thresholdExceeded = True
                break
        if thresholdExceeded:
            self.parent.tabWidget.setTabIcon(2, self.iconErr)
        else:
            self.parent.tabWidget.setTabIcon(2, self.iconOk)

    def onClick(self, item):
        # Row is already selected
        if self.parent.selectedThdRow == item.row():
            # Deselect
            self.tbl.clearSelection()
        # Emit select signal
        self.sig_clickedRow.emit(item.row())

    def createInfoBtn(self, cellData):
        button = QPushButton('?')
        button.setMaximumSize(QSize(22, 22))
        # Fill info text into message box
        button.clicked.connect(
            lambda: QMessageBox.information(self.parent, cellData[
                'title'], cellData['message'], QMessageBox.Ok))
        cellWidget = QWidget()
        # Add layout to center button in cell
        layout = QHBoxLayout(cellWidget)
        layout.addWidget(button, 0, Qt.AlignCenter)
        layout.setAlignment(Qt.AlignCenter)
        cellWidget.setLayout(layout)
        return cellWidget
Ejemplo n.º 13
0
    def initGui(self):
        icon = QIcon()
        icon.addPixmap(
            QPixmap(
                "C:/Roberto/Visual_Studio_Code/GisBike/programa/IMG/Qgis.png"),
            QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        self.setWindowModality(Qt.WindowModal)
        self.setWindowFlags(Qt.Window
                            | Qt.WindowSystemMenuHint
                            | Qt.WindowMinimizeButtonHint
                            | Qt.WindowMaximizeButtonHint
                            | Qt.WindowCloseButtonHint)

        self.resize(1200, 600)

        self.verticalLayout_2 = QVBoxLayout(self)
        self.splitter = QSplitter(self)
        self.splitter.setOrientation(Qt.Horizontal)

        self.actionZoomIn = QPushButton("Zoom in", self.splitter)
        self.actionZoomOut = QPushButton("Zoom out", self.splitter)
        self.actionPan = QPushButton("Pan", self.splitter)
        self.actionFile = QPushButton("File", self.splitter)

        self.project = QgsProject.instance()
        self.project.read('C:/Users/Fcc/Desktop/QGis/pruebas2.qgz')
        self.root = QgsProject.instance().layerTreeRoot()
        self.bridge = QgsLayerTreeMapCanvasBridge(self.root, self.canvas)

        self.bridge.setCanvasLayers()
        self.bridge.setAutoSetupOnFirstLayer(True)

        #https://gis.stackexchange.com/questions/141516/adding-legend-to-canvas-in-standalone-pyqgis-application
        self.model = QgsLayerTreeModel(self.root)
        self.model.setFlag(QgsLayerTreeModel.AllowNodeReorder)
        self.model.setFlag(QgsLayerTreeModel.AllowNodeRename)
        self.model.setFlag(QgsLayerTreeModel.AllowNodeChangeVisibility)
        self.model.setFlag(QgsLayerTreeModel.ShowLegend)
        self.view = QgsLayerTreeView(self.splitter)
        self.view.setModel(self.model)
        self.view.setFixedWidth(150)
        #self.view.resize(150,600)

        self.widget = QWidget(self.splitter)
        self.verticalLayout = QVBoxLayout(self.widget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.addWidget(self.actionZoomIn)
        self.horizontalLayout.addWidget(self.actionZoomOut)
        self.horizontalLayout.addWidget(self.actionPan)
        self.horizontalLayout.addWidget(self.actionFile)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.verticalLayout.addWidget(self.canvas)
        self.verticalLayout_2.addWidget(self.splitter)

        self.actionZoomIn.clicked.connect(self.zoomIn)
        self.actionZoomOut.clicked.connect(self.zoomOut)
        self.actionPan.clicked.connect(self.pan)
        self.actionFile.clicked.connect(self.file)

        # create the map tools
        self.toolPan = QgsMapToolPan(self.canvas)
        self.toolZoomIn = QgsMapToolZoom(self.canvas, False)  # false = in
        self.toolZoomOut = QgsMapToolZoom(self.canvas, True)  # true = out
Ejemplo n.º 14
0
    def __init__(self, iface, data):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'datosinmueble_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        self.data = data
        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&datosinmueble')
        #Init canvas
        self.canvas = self.iface.mapCanvas()
        #Init click tool
        self.clickTool = QgsMapToolEmitPoint(self.canvas)
        self.dockwidget = datosinmuebleDialog(parent=iface.mainWindow())
        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.first_start = None

        # Declaramos los botones y sus acciones
        self.dockwidget.btCerrar_2.clicked.connect(self.closePlugin)
        #Setamos todos los campos de texto
        #Seteamos todos los campos de texto
        self.predioDetalle = self.data['datosPredio']
        self.dockwidget.leReg.setText(self.predioDetalle['cveRegion'])
        self.dockwidget.leManz.setText(self.predioDetalle['cveManzana'])
        self.dockwidget.leLote.setText(self.predioDetalle['lote'])
        self.dockwidget.leCondo.setText("")
        self.dockwidget.leNombreColonia.setText(self.predioDetalle['dv'])
        self.dockwidget.leNombreColonia_2.setText(
            self.predioDetalle['denominacionPredio'])
        self.dockwidget.leNombreColonia_3.setText(
            self.predioDetalle['claseCuenta'])
        self.dockwidget.leNombreColonia_4.setText(
            self.predioDetalle['marcaFiscal'])
        self.dockwidget.leNombreColonia_5.setText(
            self.predioDetalle['docCuenta'])
        try:
            self.dockwidget.leNombreColonia_6.setText(
                self.predioDetalle['calles'][0]['calle'])
        except Exception:
            print("No tiene calles")
        self.dockwidget.leNombreColonia_7.setText(self.predioDetalle['numero'])
        self.dockwidget.leNombreColonia_8.setText(
            self.predioDetalle['colonia'])
        self.dockwidget.leNombreColonia_9.setText(self.predioDetalle['cp'])
        self.dockwidget.leNombreColonia_10.setText(
            self.predioDetalle['cveManzana'])
        self.dockwidget.leNombreColonia_11.setText(
            self.predioDetalle['delegacion'])
        self.dockwidget.leNombreColonia_12.setText(
            str(self.predioDetalle['superTerreno']))
        self.dockwidget.leNombreColonia_13.setText(
            str(self.predioDetalle['superConstruccion']))
        self.dockwidget.leNombreColonia_14.setText(self.predioDetalle['giro'])
        self.dockwidget.leNombreColonia_15.setText("")

        # --- Cargamos las construcciones a la lista
        self.construcciones = self.predioDetalle['construcciones']
        self.dockwidget.twListaVias_3.clearContents()
        self.dockwidget.twListaVias_3.setRowCount(len(self.construcciones))
        for row in range(len(self.construcciones)):
            self.dockwidget.twListaVias_3.setItem(
                row, 0,
                QtWidgets.QTableWidgetItem(str(
                    self.construcciones[row]['id'])))
            self.dockwidget.twListaVias_3.setItem(
                row, 3,
                QtWidgets.QTableWidgetItem(self.construcciones[row]['clase']))
            self.dockwidget.twListaVias_3.setItem(
                row, 4,
                QtWidgets.QTableWidgetItem(
                    self.construcciones[row]['descClase']))
            self.dockwidget.twListaVias_3.setItem(
                row, 5,
                QtWidgets.QTableWidgetItem(
                    str(self.construcciones[row]['nivel'])))
            self.dockwidget.twListaVias_3.setItem(
                row, 8,
                QtWidgets.QTableWidgetItem(
                    str(self.construcciones[row]['anio'])))
            self.dockwidget.twListaVias_3.setItem(
                row, 10,
                QtWidgets.QTableWidgetItem(
                    str(self.construcciones[row]['superficie'])))

        # --- Cargamos la lista de propietarios
        self.propietarios = self.predioDetalle['propietarios']
        self.dockwidget.twListaVias_5.clearContents()
        self.dockwidget.twListaVias_5.setRowCount(len(self.propietarios))
        for row in range(len(self.propietarios)):
            self.dockwidget.twListaVias_5.setItem(
                row, 0,
                QtWidgets.QTableWidgetItem(str(
                    self.propietarios[row]['curp'])))
            self.dockwidget.twListaVias_5.setItem(
                row, 1,
                QtWidgets.QTableWidgetItem(self.propietarios[row]['nombre']))
            self.dockwidget.twListaVias_5.setItem(
                row, 2,
                QtWidgets.QTableWidgetItem(self.propietarios[row]['curp']))
            self.dockwidget.twListaVias_5.setItem(
                row, 3,
                QtWidgets.QTableWidgetItem(str(self.propietarios[row]['ife'])))
            self.dockwidget.twListaVias_5.setItem(
                row, 4,
                QtWidgets.QTableWidgetItem(str(
                    self.propietarios[row]['otro'])))
            self.dockwidget.twListaVias_5.setItem(
                row, 5,
                QtWidgets.QTableWidgetItem(
                    str(self.propietarios[row]['derecho'])))
            self.dockwidget.twListaVias_5.setItem(
                row, 6,
                QtWidgets.QTableWidgetItem(
                    str(self.propietarios[row]['porcentaje'])))
            self.dockwidget.twListaVias_5.setItem(
                row, 7,
                QtWidgets.QTableWidgetItem(
                    str(self.propietarios[row]['titulo'])))

        # -- Cargamos la lista de instalaciones especiales
        self.instalacionesEspeciales = self.predioDetalle[
            'instalacionesEspeciales']
        self.dockwidget.twListaVias_4.clearContents()
        self.dockwidget.twListaVias_4.setRowCount(
            len(self.instalacionesEspeciales))
        for row in range(len(self.instalacionesEspeciales)):
            self.dockwidget.twListaVias_4.setItem(
                row, 0,
                QtWidgets.QTableWidgetItem(
                    str(self.instalacionesEspeciales[row]['descripcion'])))

        #Hacemos la parte de las fotos
        self.dockwidget.listWidget.setViewMode(QListView.IconMode)
        self.dockwidget.listWidget.setIconSize(QtCore.QSize(
            180, 180))  #set icon size
        self.dockwidget.listWidget.setGridSize(QtCore.QSize(
            220, 220))  #set icon grid display
        # self.selectionModel(self.selectedIndexes())
        self.fotos = self.data['fotos']
        self.dockwidget.label_40.setText("Número total de fotos.:{}".format(
            len(self.fotos)))
        if len(self.fotos) > 0:
            self.dockwidget.label_41.setText(
                "Mostrando fotos de la 1 a la {}.".format(len(self.fotos)))
        else:
            self.dockwidget.label_41.setText("No tiene fotod que mostrar.")
        for image in self.fotos:
            pixmap = QPixmap()
            pixmap.loadFromData(base64.b64decode(image['archivo']))
            item = QListWidgetItem()
            icon = QIcon()
            icon.addPixmap(pixmap, QIcon.Normal, QIcon.Off)
            item.setIcon(icon)
            self.dockwidget.listWidget.addItem(item)

        self.dockwidget.twListaVias_3.cellClicked.connect(
            self.cell_was_clicked)
        self.dockwidget.label_44.setText(
            str(self.data['valoracion']['cuentaCatastral']))
        self.dockwidget.label_46.setText(
            str(self.data['valoracion']['valorUnitario']) + " $/m^2")
        self.dockwidget.label_49.setText(
            str(self.data['valoracion']['superficie']) + " m^3")
        self.dockwidget.label_51.setText(
            "$ " + str(self.data['valoracion']['valorSuelo']))
Ejemplo n.º 15
0
    def __init__(self, parent, confHandler):
        """
        :type confHandler: configHandler.ConfigHandler
        """
        QDialog.__init__(self, parent)
        self.confHandler = confHandler
        self.doSave = False

        self.setWindowTitle(self.tr('Output Optionen'))
        main_widget = QWidget(self)

        # Build up gui

        # Project title
        hbox1 = QHBoxLayout()
        projectNameLabel = QLabel(self.tr('Projektname'))
        projectNameLabel.setMinimumWidth(100)
        self.projectField = QLineEdit()
        self.projectField.setMinimumWidth(400)
        self.projectField.setSizePolicy(
            QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed))
        hbox1.addWidget(projectNameLabel)
        hbox1.addWidget(self.projectField)

        # Save path
        hbox2 = QHBoxLayout()
        saveLabel = QLabel(self.tr('Speicherpfad'))
        saveLabel.setMinimumWidth(100)
        self.pathField = QComboBox()
        self.pathField.setMinimumWidth(400)
        self.pathField.setSizePolicy(
            QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed))

        openButton = QPushButton()
        openButton.setMaximumSize(QSize(27, 27))
        icon = QIcon()
        iconPath = os.path.join(os.path.dirname(__file__), 'icons',
                                'icon_open.png')
        icon.addPixmap(QPixmap(iconPath), QIcon.Normal, QIcon.Off)
        openButton.setIcon(icon)
        openButton.setIconSize(QSize(24, 24))
        openButton.clicked.connect(self.onOpenDialog)

        hbox2.addWidget(saveLabel)
        hbox2.addWidget(self.pathField)
        hbox2.addWidget(openButton)
        # Create checkboxes
        questionLabel = QLabel(
            self.tr('Welche Produkte sollen erzeugt werden?'))
        self.checkBoxShortReport = QCheckBox(self.tr('Kurzbericht'))
        self.checkBoxReport = QCheckBox(self.tr('Technischer Bericht'))
        self.checkBoxPlot = QCheckBox(self.tr('Diagramm'))
        self.checkBoxGeodata = QCheckBox(
            self.tr('Shape-Daten der Stuetzen und Seillinie'))
        self.checkBoxKML = QCheckBox(
            self.tr('KML-Daten der Stuetzen und Seillinie'))
        self.checkBoxCoords = QCheckBox(
            self.tr('Koordinaten-Tabellen der Stuetzen und Seillinie'))

        # Set tick correctly
        self.checkBoxShortReport.setChecked(
            self.confHandler.outputOptions['shortReport'])
        self.checkBoxReport.setChecked(
            self.confHandler.outputOptions['report'])
        self.checkBoxPlot.setChecked(self.confHandler.outputOptions['plot'])
        self.checkBoxGeodata.setChecked(
            self.confHandler.outputOptions['geodata'])
        self.checkBoxKML.setChecked(self.confHandler.outputOptions['kml'])
        self.checkBoxCoords.setChecked(
            self.confHandler.outputOptions['coords'])
        # Create Ok/Cancel Button and connect signal
        buttonBox = QDialogButtonBox(main_widget)
        buttonBox.setStandardButtons(QDialogButtonBox.Save
                                     | QDialogButtonBox.Cancel)
        buttonBox.button(QDialogButtonBox.Save).setText(self.tr("Speichern"))
        buttonBox.button(QDialogButtonBox.Cancel).setText(self.tr("Abbrechen"))
        buttonBox.button(QDialogButtonBox.Cancel).clicked.connect(
            self.onCancel)
        buttonBox.button(QDialogButtonBox.Save).clicked.connect(self.onSave)
        # Layout
        container = QVBoxLayout(main_widget)
        container.addLayout(hbox1)
        container.addLayout(hbox2)
        container.addWidget(QLabel(''))
        container.addWidget(questionLabel)
        container.addWidget(self.checkBoxShortReport)
        container.addWidget(self.checkBoxReport)
        container.addWidget(self.checkBoxPlot)
        container.addWidget(self.checkBoxGeodata)
        container.addWidget(self.checkBoxKML)
        container.addWidget(self.checkBoxCoords)
        container.addWidget(buttonBox)
        container.setAlignment(Qt.AlignLeft)
        self.setLayout(container)

        self.fillInData()
Ejemplo n.º 16
0
class HistoryDialog(BASE, WIDGET):
    def __init__(self):
        super(HistoryDialog, self).__init__(None)
        self.setupUi(self)

        self.groupIcon = QIcon()
        self.groupIcon.addPixmap(
            self.style().standardPixmap(QStyle.SP_DirClosedIcon), QIcon.Normal,
            QIcon.Off)
        self.groupIcon.addPixmap(
            self.style().standardPixmap(QStyle.SP_DirOpenIcon), QIcon.Normal,
            QIcon.On)

        self.keyIcon = QIcon()
        self.keyIcon.addPixmap(self.style().standardPixmap(QStyle.SP_FileIcon))

        self.clearButton = QPushButton(self.tr('Clear'))
        self.clearButton.setToolTip(self.tr('Clear history'))
        self.buttonBox.addButton(self.clearButton, QDialogButtonBox.ActionRole)

        self.saveButton = QPushButton(
            QCoreApplication.translate('HistoryDialog', 'Save As…'))
        self.saveButton.setToolTip(self.tr('Save history'))
        self.buttonBox.addButton(self.saveButton, QDialogButtonBox.ActionRole)

        self.tree.doubleClicked.connect(self.executeAlgorithm)
        self.tree.currentItemChanged.connect(self.changeText)
        self.clearButton.clicked.connect(self.clearLog)
        self.saveButton.clicked.connect(self.saveLog)

        self.tree.setContextMenuPolicy(Qt.CustomContextMenu)
        self.tree.customContextMenuRequested.connect(self.showPopupMenu)

        self.fillTree()

    def clearLog(self):
        reply = QMessageBox.question(
            self, self.tr('Confirmation'),
            self.tr('Are you sure you want to clear the history?'),
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            ProcessingLog.clearLog()
            self.fillTree()

    def saveLog(self):
        fileName, filter = QFileDialog.getSaveFileName(
            self, self.tr('Save File'), '.',
            self.tr('Log files (*.log *.LOG)'))

        if fileName == '':
            return

        if not fileName.lower().endswith('.log'):
            fileName += '.log'

        ProcessingLog.saveLog(fileName)

    def fillTree(self):
        self.tree.clear()
        entries = ProcessingLog.getLogEntries()
        groupItem = QTreeWidgetItem()
        groupItem.setText(0, 'ALGORITHM')
        groupItem.setIcon(0, self.groupIcon)
        for entry in entries:
            item = TreeLogEntryItem(entry, True)
            item.setIcon(0, self.keyIcon)
            groupItem.insertChild(0, item)
        self.tree.addTopLevelItem(groupItem)
        groupItem.setExpanded(True)

    def executeAlgorithm(self):
        item = self.tree.currentItem()
        if isinstance(item, TreeLogEntryItem):
            if item.isAlg:
                script = 'import processing\n'
                script += 'from qgis.core import QgsProcessingOutputLayerDefinition, QgsProcessingFeatureSourceDefinition, QgsProperty\n'
                script += item.entry.text.replace(
                    'processing.run(', 'processing.execAlgorithmDialog(')
                self.close()
                exec(script)

    def changeText(self):
        item = self.tree.currentItem()
        if isinstance(item, TreeLogEntryItem):
            self.text.setText(item.entry.text.replace('|', '\n'))

    def createTest(self):
        item = self.tree.currentItem()
        if isinstance(item, TreeLogEntryItem):
            if item.isAlg:
                TestTools.createTest(item.entry.text)

    def showPopupMenu(self, point):
        item = self.tree.currentItem()
        if isinstance(item, TreeLogEntryItem):
            if item.isAlg:
                popupmenu = QMenu()
                createTestAction = QAction(
                    QCoreApplication.translate('HistoryDialog',
                                               'Create Test…'), self.tree)
                createTestAction.triggered.connect(self.createTest)
                popupmenu.addAction(createTestAction)
                popupmenu.exec_(self.tree.mapToGlobal(point))
Ejemplo n.º 17
0
class ConfigDialog(BASE, WIDGET):
    def __init__(self):
        super(ConfigDialog, self).__init__(None)
        self.setupUi(self)

        self.groupIcon = QIcon()
        self.groupIcon.addPixmap(
            self.style().standardPixmap(QStyle.SP_DirClosedIcon), QIcon.Normal,
            QIcon.Off)
        self.groupIcon.addPixmap(
            self.style().standardPixmap(QStyle.SP_DirOpenIcon), QIcon.Normal,
            QIcon.On)

        if hasattr(self.searchBox, 'setPlaceholderText'):
            self.searchBox.setPlaceholderText(self.tr('Search...'))

        self.model = QStandardItemModel()
        self.tree.setModel(self.model)

        self.delegate = SettingDelegate()
        self.tree.setItemDelegateForColumn(1, self.delegate)

        self.searchBox.textChanged.connect(self.textChanged)

        self.fillTree()

        self.saveMenus = False
        self.tree.expanded.connect(self.itemExpanded)

    def textChanged(self):
        text = str(self.searchBox.text().lower())
        self._filterItem(self.model.invisibleRootItem(), text)
        if text:
            self.tree.expandAll()
        else:
            self.tree.collapseAll()

    def _filterItem(self, item, text):
        if item.hasChildren():
            show = False
            for i in range(item.rowCount()):
                child = item.child(i)
                showChild = self._filterItem(child, text)
                show = (showChild or show)
            self.tree.setRowHidden(item.row(), item.index().parent(), not show)
            return show

        elif isinstance(item, QStandardItem):
            hide = bool(text) and (text not in item.text().lower())
            self.tree.setRowHidden(item.row(), item.index().parent(), hide)
            return not hide

    def fillTree(self):
        self.fillTreeUsingProviders()

    def fillTreeUsingProviders(self):
        self.items = {}
        self.model.clear()
        self.model.setHorizontalHeaderLabels(
            [self.tr('Setting'), self.tr('Value')])

        settings = ProcessingConfig.getSettings()

        rootItem = self.model.invisibleRootItem()
        """
        Filter 'General', 'Models' and 'Scripts' items
        """
        priorityKeys = [
            self.tr('General'),
            self.tr('Models'),
            self.tr('Scripts')
        ]
        for group in priorityKeys:
            groupItem = QStandardItem(group)
            icon = ProcessingConfig.getGroupIcon(group)
            groupItem.setIcon(icon)
            groupItem.setEditable(False)
            emptyItem = QStandardItem()
            emptyItem.setEditable(False)

            rootItem.insertRow(0, [groupItem, emptyItem])
            # add menu item only if it has any search matches
            for setting in settings[group]:
                if setting.hidden or setting.name.startswith("MENU_"):
                    continue

                labelItem = QStandardItem(setting.description)
                labelItem.setIcon(icon)
                labelItem.setEditable(False)
                self.items[setting] = SettingItem(setting)
                groupItem.insertRow(0, [labelItem, self.items[setting]])
        """
        Filter 'Providers' items
        """
        providersItem = QStandardItem(self.tr('Providers'))
        icon = QgsApplication.getThemeIcon("/processingAlgorithm.svg")
        providersItem.setIcon(icon)
        providersItem.setEditable(False)
        emptyItem = QStandardItem()
        emptyItem.setEditable(False)

        rootItem.insertRow(0, [providersItem, emptyItem])
        for group in list(settings.keys()):
            if group in priorityKeys or group == menusSettingsGroup:
                continue

            groupItem = QStandardItem(group)
            icon = ProcessingConfig.getGroupIcon(group)
            groupItem.setIcon(icon)
            groupItem.setEditable(False)

            for setting in settings[group]:
                if setting.hidden:
                    continue

                labelItem = QStandardItem(setting.description)
                labelItem.setIcon(icon)
                labelItem.setEditable(False)
                self.items[setting] = SettingItem(setting)
                groupItem.insertRow(0, [labelItem, self.items[setting]])

            emptyItem = QStandardItem()
            emptyItem.setEditable(False)
            providersItem.appendRow([groupItem, emptyItem])
        """
        Filter 'Menus' items
        """
        self.menusItem = QStandardItem(self.tr('Menus'))
        icon = QIcon(os.path.join(pluginPath, 'images', 'menu.png'))
        self.menusItem.setIcon(icon)
        self.menusItem.setEditable(False)
        emptyItem = QStandardItem()
        emptyItem.setEditable(False)

        rootItem.insertRow(0, [self.menusItem, emptyItem])

        button = QPushButton(self.tr('Reset to defaults'))
        button.clicked.connect(self.resetMenusToDefaults)
        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(button)
        layout.addStretch()
        widget = QWidget()
        widget.setLayout(layout)
        self.tree.setIndexWidget(emptyItem.index(), widget)

        for provider in QgsApplication.processingRegistry().providers():
            providerDescription = provider.name()
            groupItem = QStandardItem(providerDescription)
            icon = provider.icon()
            groupItem.setIcon(icon)
            groupItem.setEditable(False)

            for alg in provider.algorithms():
                algItem = QStandardItem(alg.displayName())
                algItem.setIcon(icon)
                algItem.setEditable(False)
                try:
                    settingMenu = ProcessingConfig.settings["MENU_" + alg.id()]
                    settingButton = ProcessingConfig.settings["BUTTON_" +
                                                              alg.id()]
                    settingIcon = ProcessingConfig.settings["ICON_" + alg.id()]
                except:
                    continue
                self.items[settingMenu] = SettingItem(settingMenu)
                self.items[settingButton] = SettingItem(settingButton)
                self.items[settingIcon] = SettingItem(settingIcon)
                menuLabelItem = QStandardItem("Menu path")
                menuLabelItem.setEditable(False)
                buttonLabelItem = QStandardItem("Add button in toolbar")
                buttonLabelItem.setEditable(False)
                iconLabelItem = QStandardItem("Icon")
                iconLabelItem.setEditable(False)
                emptyItem = QStandardItem()
                emptyItem.setEditable(False)
                algItem.insertRow(0, [menuLabelItem, self.items[settingMenu]])
                algItem.insertRow(0,
                                  [buttonLabelItem, self.items[settingButton]])
                algItem.insertRow(0, [iconLabelItem, self.items[settingIcon]])
                groupItem.insertRow(0, [algItem, emptyItem])

            emptyItem = QStandardItem()
            emptyItem.setEditable(False)

            self.menusItem.appendRow([groupItem, emptyItem])

        self.tree.sortByColumn(0, Qt.AscendingOrder)
        self.adjustColumns()

    def resetMenusToDefaults(self):
        for provider in QgsApplication.processingRegistry().providers():
            for alg in provider.algorithms():
                d = defaultMenuEntries.get(alg.id(), "")
                setting = ProcessingConfig.settings["MENU_" + alg.id()]
                item = self.items[setting]
                item.setData(d, Qt.EditRole)
        self.saveMenus = True

    def accept(self):
        qsettings = QgsSettings()
        for setting in list(self.items.keys()):
            if setting.group != menusSettingsGroup or self.saveMenus:
                if isinstance(setting.value, bool):
                    setting.setValue(
                        self.items[setting].checkState() == Qt.Checked)
                else:
                    try:
                        setting.setValue(str(self.items[setting].text()))
                    except ValueError as e:
                        QMessageBox.warning(
                            self, self.tr('Wrong value'),
                            self.tr('Wrong value for parameter "{0}":\n\n{1}').
                            format(setting.description, str(e)))
                        return
                setting.save(qsettings)

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        for p in QgsApplication.processingRegistry().providers():
            p.refreshAlgorithms()
        QApplication.restoreOverrideCursor()

        settingsWatcher.settingsChanged.emit()

    def itemExpanded(self, idx):
        if idx == self.menusItem.index():
            self.saveMenus = True
        self.adjustColumns()

    def adjustColumns(self):
        self.tree.resizeColumnToContents(0)
        self.tree.resizeColumnToContents(1)
Ejemplo n.º 18
0
    def __init__(self, parent, interface, drawTool, projectHandler):
        """
        :type drawTool: gui.mapMarker.MapMarkerTool
        :type projectHandler: projectHandler.ProjectConfHandler
        """
        QDialog.__init__(self, parent)
        self.iface = interface
        self.projectHandler = projectHandler
        self.drawTool = drawTool
        self.setWindowTitle(self.tr('Gelaendelinie'))
        self.setWindowModality(Qt.WindowModal)
        
        self.profile = None
        # Array with properties fixed poles
        self.poleData = []
        # Array with sections without poles
        self.noPoleSection = []
        # Profile data
        self.xdata = None
        self.zdata = None
        self.profileMin = 0
        self.profileMax = None

        # Plot
        self.sc = ProfilePlot(self)
        # Pan/Zoom Tools for diagram
        tbar = MyNavigationToolbar(self.sc, self)
        tbar.pan()
        self.sc.setToolbar(tbar)

        # Layout
        main_widget = QWidget(self)
        self.container = QVBoxLayout(main_widget)
        self.outerLayout = QVBoxLayout()

        # GUI fields
        stueTitle = QLabel('<b>' + self.tr('Stuetzenoptimierung einschraenken') + '</b>')
        hbox = QHBoxLayout()
        line1 = QFrame()
        line1.setFrameShape(QFrame.HLine)
        line1.setFrameShadow(QFrame.Sunken)

        # Create labels and buttons
        self.fixStueAdd = QPushButton(self.tr('Fixe Stuetze definieren'))
        self.noStueAdd = QPushButton(self.tr('Abschnitt ohne Stuetzen definieren'))
        self.noStueDel = QPushButton()
        icon = QIcon()
        icon.addPixmap(
            QPixmap(':/plugins/SeilaplanPlugin/gui/icons/icon_bin.png'),
            QIcon.Normal, QIcon.Off)
        self.noStueDel.setIcon(icon)
        self.noStueDel.setIconSize(QSize(16, 16))
        self.fixStueAdd.setToolTip(self.tr('Tooltip Fixe Stuetzen'))
        self.noStueAdd.setToolTip(self.tr('Tooltip Abschnitte ohne Stuetzen'))
        self.noStueDel.setToolTip(self.tr('Tooltip Abschnitte loeschen'))
        spacerItem1 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                        QSizePolicy.Minimum)
        hbox.addWidget(self.fixStueAdd)
        hbox.addItem(spacerItem1)
        hbox.addWidget(self.noStueAdd)
        hbox.addWidget(self.noStueDel)
        hbox.setAlignment(self.noStueAdd, Qt.AlignRight)
        btnBoxSpacer = QSpacerItem(40, 40, QSizePolicy.Fixed,
                                        QSizePolicy.Fixed)
        self.buttonBox = QDialogButtonBox(main_widget)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Ok)
        # Build up Gui
        self.container.addWidget(self.sc)
        self.container.addWidget(tbar, alignment=Qt.AlignHCenter | Qt.AlignTop)
        self.container.addWidget(line1)
        self.container.addWidget(stueTitle)
        self.container.addLayout(hbox)
        self.container.addLayout(self.outerLayout)
        self.container.addItem(btnBoxSpacer)
        self.container.addWidget(self.buttonBox)

        # Connect signals
        self.fixStueAdd.clicked.connect(self.sc.acitvateCrosshairPole)
        self.noStueAdd.clicked.connect(self.sc.activateCrosshairSection)
        self.noStueDel.clicked.connect(self.deleteSections)
        self.buttonBox.accepted.connect(self.Apply)
        self.setLayout(self.container)
        
        # Gui's functionality for fixed pole gui fields
        self.buildPoleHeader()
        self.poleLayout = CustomPoleWidget(self, self.outerLayout, self.poleData)
        self.poleLayout.sig_updatePole.connect(self.updatePole)
        self.poleLayout.sig_deletePole.connect(self.deletePole)