def paintEvent(self, event): if not self.tenant: return paint = QPainter(self) for e in self.tenant.edges: if e == self.selectedEdge: paint.setPen(self.colors["selected"]) else: paint.setPen(self.colors["line"]) self.drawArrow(paint, self.vertices[e.e1].x() + self.size / 2, self.vertices[e.e1].y() + self.size / 2, self.vertices[e.e2].x() + self.size / 2, self.vertices[e.e2].y() + self.size / 2) for v in self.vertices.keys(): pen = paint.pen() paint.setPen(Qt.red) if self.selectedVertex == self.vertices[v]: paint.drawRect(self.vertices[v]) if isinstance(v, VM): paint.drawImage(self.vertices[v], self.computericon) elif isinstance(v, Storage): paint.drawImage(self.vertices[v], self.storageicon) elif isinstance(v, NetElement): if v.router: paint.drawImage(self.vertices[v], self.routericon) else: paint.drawImage(self.vertices[v], self.switchicon) elif isinstance(v, Vnf): paint.drawImage(self.vertices[v], self.serviceicon) elif isinstance(v, Domain): paint.drawImage(self.vertices[v], self.domainicon) paint.setPen(self.colors["line"]) if self.edgeDraw: self.drawArrow(paint, self.curEdge[0].x() + self.size / 2, self.curEdge[0].y() + self.size / 2, QCursor.pos().x() - self.mapToGlobal(self.geometry().topLeft()).x(), QCursor.pos().y() - self.mapToGlobal(self.geometry().topLeft()).y()) paint.end()
def paintEvent(self, event): if not self.resources: return paint = QPainter(self) for e in self.resources.edges: if e == self.selectedEdge: paint.setPen(self.colors["selected"]) else: paint.setPen(self.colors["line"]) self.drawArrow(paint, self.vertices[e.e1].x() + self.size / 2, self.vertices[e.e1].y() + self.size / 2, self.vertices[e.e2].x() + self.size / 2, self.vertices[e.e2].y() + self.size / 2) for v in self.vertices.keys(): if isinstance(v, Computer): if self.selectedVertex != self.vertices[v]: paint.drawImage(self.vertices[v], self.computericon) else: paint.drawImage(self.vertices[v], self.computerselectedicon) elif isinstance(v, Storage): if self.selectedVertex != self.vertices[v]: paint.drawImage(self.vertices[v], self.storageicon) else: paint.drawImage(self.vertices[v], self.storageselectedicon) elif isinstance(v, Router): if self.selectedVertex != self.vertices[v]: paint.drawImage(self.vertices[v], self.routericon) else: paint.drawImage(self.vertices[v], self.routerselectedicon) paint.setPen(self.colors["line"]) if self.edgeDraw: self.drawArrow(paint, self.curEdge[0].x() + self.size / 2, self.curEdge[0].y() + self.size / 2, QCursor.pos().x() - self.mapToGlobal(self.geometry().topLeft()).x(), QCursor.pos().y() - self.mapToGlobal(self.geometry().topLeft()).y()) paint.end()
def onTodoListContextMenuReqeusted(self, pos): index = self.tvTodoList.indexAt(pos) if index.isValid(): self.tvTodoList.setCurrentIndex(index) menu = QMenu() if index.isValid(): task = self.todoListModel.taskAt(index) if task["finishment"] == 0: menu.addAction(self.actionMarkProcessing) menu.addAction(self.actionMarkFinished) elif task["finishment"] < 100: menu.addAction(self.actionMarkUnfinished) menu.addAction(self.actionMarkFinished) else: menu.addAction(self.actionMarkUnfinished) menu.addAction(self.actionMarkProcessing) menu.addSeparator() menu.addAction(self.actionCreateTodo) if index.isValid(): menu.addAction(self.actionRemoveTodo) menu.addAction(self.actionModifyTodoSubject) menu.addAction(self.actionEditTodo) try: getattr(menu, "exec")(QCursor.pos()) except AttributeError: getattr(menu, "exec_")(QCursor.pos())
def eventFilter( self, obj, event ): if obj == self.sequencesTable.horizontalHeader(): if event.type() == QEvent.HoverMove: newColumn = self.sequencesTable.horizontalHeader().logicalIndexAt( event.pos() ) if newColumn != self.deleteColumn: if not self.removeInputButton.isVisible() and newColumn >= 0: self.removeInputButton.show() elif self.removeInputButton.isVisible() and newColumn == -1: self.removeInputButton.hide() self.deleteColumn = newColumn if newColumn >= 0: x = sum( map( self.sequencesTable.columnWidth, range( self.deleteColumn + 1 ) ) ) - 20 if self.sequencesTable.rowCount() > 0: x += 15 self.removeInputButton.move( x, 2 ) elif event.type() == QEvent.HoverLeave: child = self.childAt( self.mapFromGlobal( QCursor.pos() ) ) if not isinstance( child, QToolButton ): self.removeInputButton.hide() self.deleteColumn = -1 elif obj == self.removeInputButton: if event.type() == QEvent.HoverLeave: child = self.childAt( self.mapFromGlobal( QCursor.pos() ) ) if isinstance( child, QToolButton ): self.removeInputButton.hide() self.deleteColumn = -1 return DesignerWidget.eventFilter( self, obj, event )
def show(self): """ This method reimplements the :meth:`QWidget.show` method. """ self.move(QCursor.pos().x() - self.width() / 2, QCursor.pos().y() - self.height() / 2) self.Interfaces_lineEdit.setText(RuntimeGlobals.popupPattern or QString()) self.Interfaces_lineEdit.setFocus() super(Popup, self).show()
def broadTheMousePos(self): currentPosX = QCursor.pos().x() currentPosY = QCursor.pos().y() msg = "mousepos#" + str(currentPosX) + "#" + str(currentPosY) if self.currentPosMsg != msg: self.currentPosMsg = msg self.udpSocketTwo.writeDatagram(msg, self.mcast_addr_two, self.porttwo) else: pass
def wheelEvent(self, event): pos = QCursor().pos() x_image = float(self.width() - self.w)/2 y_image = float(self.height() - self.h)/2 print "I'm in a wheel event1:", self.height(), self.h, self.ratio print "I'm in a wheel event:", pos.x(), pos.y(), x_image, y_image self.scale_pdf_image_geometry(dr=0.1 * float(event.delta())/8/15/20, # * self.ratio, x_m = pos.x() - x_image, y_m = pos.y() - y_image) self.rerender_pdf_image() self.update()
def showContextMenu(self): """Called when the user right-clicks or presses the context menu key.""" pos = self.view.mapToGlobal(QPoint(0, 0)) link, cursor = None, None # mouse inside view? if self.view.mapFromGlobal(QCursor.pos()) in self.view.viewport().rect(): pos = QCursor.pos() pos_in_surface = self.view.surface().mapFromGlobal(pos) page, link = self.view.surface().pageLayout().linkAt(pos_in_surface) if link: cursor = self._links.cursor(link, True) from . import contextmenu contextmenu.show(pos, self.parent(), link, cursor)
def __showContextMenu( self, coord ): " Shows the context menu " index = self.currentIndex() if not index.isValid(): return sindex = self.toSourceIndex( index ) if not sindex.isValid(): return bp = self.__model.getBreakPointByIndex( sindex ) if not bp: return enableCount, disableCount = self.__model.getCounts() self.__editAct.setEnabled( True ) self.__enableAct.setEnabled( not bp.isEnabled() ) self.__disableAct.setEnabled( bp.isEnabled() ) self.__jumpToCodeAct.setEnabled( True ) self.__delAct.setEnabled( True ) self.__enableAllAct.setEnabled( disableCount > 0 ) self.__disableAllAct.setEnabled( enableCount > 0 ) self.__delAllAct.setEnabled( enableCount + disableCount > 0 ) self.menu.popup( QCursor.pos() ) return
def right_click(self, type, champ): u"Retourne une fonction qui sera executée lors d'un clic droit sur le champ 'champ'." champ.setFocus() plusieurs = isinstance(type, list) if plusieurs: type = type[0] liste_objets = self.onglet_actuel.feuille_actuelle.objets.lister(False, type = type) liste_objets.sort(key = attrgetter('nom')) # ordre alphabétique if not liste_objets: return menu = QMenu() for obj in liste_objets: action = menu.addAction(obj.nom_complet) action.nom = obj.nom action = menu.exec_(QCursor.pos()) if action: if plusieurs: # le champ doit contenir non pas un objet, mais une liste d'objets val = champ.text().strip() if val: if not val.endswith(","): val += "," val += " " champ.setText(val + action.nom) else: # le champ contient un seul objet champ.setText(action.nom)
def mouse_position ( self ): """ Returns the current mouse position (in screen coordinates) as a tuple of the form: (x,y). """ position = QCursor.pos() return ( position.x(), position.y() )
def showMenu( self ): """ Creates a menu to display for the editing of template information. """ item = self.uiMenuTREE.currentItem() menu = QMenu(self) act = menu.addAction('Add Menu...') act.setIcon(QIcon(projexui.resources.find('img/folder.png'))) act.triggered.connect(self.createMenu) if ( item and item.data(0, Qt.UserRole) == 'menu' ): act = menu.addAction('Rename Menu...') ico = QIcon(projexui.resources.find('img/edit.png')) act.setIcon(ico) act.triggered.connect(self.renameMenu) act = menu.addAction('Add Separator') act.setIcon(QIcon(projexui.resources.find('img/ui/splitter.png'))) act.triggered.connect(self.createSeparator) menu.addSeparator() act = menu.addAction('Remove Item') act.setIcon(QIcon(projexui.resources.find('img/remove.png'))) act.triggered.connect(self.removeItem) act.setEnabled(item is not None) menu.exec_(QCursor.pos())
def activated(self, reason): if reason == QSystemTrayIcon.DoubleClick: self.setup() elif reason == QSystemTrayIcon.Trigger: menu = QMenu() self.populateMenuFromSettings(menu) menu.exec_(QCursor.pos())
def mousePressEvent(self, event): index = self.indexAt(event.pos()) if index.isValid(): item = self.itemAt(event.pos()) if event.button() == Qt.RightButton: self.copyMenu.popup(QCursor.pos()) QTreeWidget.mousePressEvent(self, event)
def _menu_context_tree(self, point): index = self.indexAt(point) if not index.isValid(): return menu = QMenu(self) f_all = menu.addAction(self.tr("Fold all")) u_all = menu.addAction(self.tr("Unfold all")) menu.addSeparator() u_class = menu.addAction(self.tr("Unfold classes")) u_class_method = menu.addAction(self.tr("Unfold classes and methods")) u_class_attr = menu.addAction(self.tr("Unfold classes and attributes")) menu.addSeparator() #save_state = menu.addAction(self.tr("Save State")) self.connect(f_all, SIGNAL("triggered()"), lambda: self.collapseAll()) self.connect(u_all, SIGNAL("triggered()"), lambda: self.expandAll()) self.connect(u_class, SIGNAL("triggered()"), self._unfold_class) self.connect(u_class_method, SIGNAL("triggered()"), self._unfold_class_method) self.connect(u_class_attr, SIGNAL("triggered()"), self._unfold_class_attribute) #self.connect(save_state, SIGNAL("triggered()"), #self._save_symbols_state) menu.exec_(QCursor.pos())
def _menu_context_tree(self, point): """Context menu""" index = self.tree.indexAt(point) if not index.isValid(): return menu = QMenu(self) f_all = menu.addAction(translations.TR_FOLD_ALL) u_all = menu.addAction(translations.TR_UNFOLD_ALL) menu.addSeparator() u_class = menu.addAction(translations.TR_UNFOLD_CLASSES) u_class_method = menu.addAction( translations.TR_UNFOLD_CLASSES_AND_METHODS) u_class_attr = menu.addAction( translations.TR_UNFOLD_CLASSES_AND_ATTRIBUTES) menu.addSeparator() #save_state = menu.addAction(self.tr("Save State")) self.connect(f_all, SIGNAL("triggered()"), lambda: self.tree.collapseAll()) self.connect(u_all, SIGNAL("triggered()"), lambda: self.tree.expandAll()) self.connect(u_class, SIGNAL("triggered()"), self._unfold_class) self.connect(u_class_method, SIGNAL("triggered()"), self._unfold_class_method) self.connect(u_class_attr, SIGNAL("triggered()"), self._unfold_class_attribute) #self.connect(save_state, SIGNAL("triggered()"), #self._save_symbols_state) menu.exec_(QCursor.pos())
def __init__(self, iface, settings, action, index_action): """ Class constructor """ self.iface = iface self.canvas = self.iface.mapCanvas() self.settings = settings self.show_help = bool(int(self.settings.value("status/show_help", 1))) self.index_action = index_action self.layer_arc = None self.layer_connec = None self.layer_node = None self.schema_name = None self.controller = None self.dao = None # Call superclass constructor and set current action QgsMapTool.__init__(self, self.canvas) self.setAction(action) # Snapper self.snapperManager = SnappingConfigManager(self.iface) self.snapper = QgsMapCanvasSnapper(self.canvas) # Change map tool cursor self.cursor = QCursor() self.cursor.setShape(Qt.CrossCursor) # Get default cursor self.stdCursor = self.parent().cursor()
def __link_clicked(self, url): if url == "cmd:add_columns": self.base.show_column_menu(QCursor.pos()) elif url == "cmd:add_accounts": self.base.show_accounts_dialog() elif url == "cmd:restart": self.base.restart()
def replace(self): log.trace("Icon is %r", self._icon) self._icon_geometry = rect = self._icon.geometry() log.trace("IconRect is : %s,%s | %s,%s",rect.x(), rect.y(), rect.width(), rect.height()) from PyQt4.QtGui import QApplication, QCursor from PyQt4.QtCore import QRect desktop = QApplication.desktop() log.trace("Screen id is %d", desktop.screenNumber(rect.topLeft())) screen = desktop.availableGeometry(desktop.screenNumber(rect.topLeft())) pos = screen log.trace("AvailableRect is : %s,%s | %s,%s",pos.x(), pos.y(), pos.width(), pos.height()) pos = desktop.screenGeometry(desktop.screenNumber(rect.topLeft())) log.trace("ScreenRect is : %s,%s | %s,%s",pos.x(), pos.y(), pos.width(), pos.height()) pos = QCursor.pos() log.trace("Cursor is : %s,%s",pos.x(), pos.y()) if not rect.contains(pos) or (rect.x() == 0 and rect.y() == 0): # Avoid any modulo 0 if rect.width() == 0 or rect.height() == 0: rect = QRect(pos.x(), pos.y(), rect.width(), rect.height()) else: rect = QRect(pos.x()-pos.x()%rect.width(), pos.y()-pos.y()%rect.height(), rect.width(), rect.height()) log.trace("Adjusting X/Y to %d/%d", rect.x(), rect.y()) pos = rect log.trace("New rect is : %s,%s | %s,%s",pos.x(), pos.y(), pos.width(), pos.height()) x = rect.x() + rect.width() - self.width() y = rect.y() - self.height() # Prevent the systray to be hidden if y < 0: y = rect.y() + rect.height() if x < 0: x = rect.x() log.trace("Move systray menu to %d/%d", x, y) self.move(x, y)
def _menu_context_tree(self, point, isRoot=False, root_path=None): index = self.indexAt(point) if not index.isValid() and not isRoot: return handler = None menu = QMenu(self) if isRoot or self.model().isDir(index): self._add_context_menu_for_folders(menu, isRoot, root_path) else: filename = self.model().fileName(index) lang = file_manager.get_file_extension(filename) self._add_context_menu_for_files(menu, lang) if isRoot: #get the extra context menu for this projectType handler = settings.get_project_type_handler( self.project.project_type) self._add_context_menu_for_root(menu) menu.addMenu(self._folding_menu) #menu for the Project Type(if present) if handler: for m in handler.get_context_menus(): if isinstance(m, QMenu): menu.addSeparator() menu.addMenu(m) #show the menu! menu.exec_(QCursor.pos())
def showSnippets(self, evt): popupmenu = QMenu() for name, snippet in self.snippets.iteritems(): action = QAction(self.tr(name), self.btnSnippets) action.triggered[()].connect(lambda snippet=snippet: self.editor.insert(snippet)) popupmenu.addAction(action) popupmenu.exec_(QCursor.pos())
def show(widget, pos=None, timeout=10000): """Show the widget at position.""" if pos is None: pos = QCursor.pos() global _widget if _widget: if _widget is not widget: _widget.hide() else: global _handler if _handler is None: _handler = EventHandler() QApplication.instance().installEventFilter(_handler) # where to display the tooltip screen = QApplication.desktop().availableGeometry(pos) x = pos.x() + 2 y = pos.y() + 20 if x + widget.width() > screen.x() + screen.width(): x -= 4 + widget.width() if y + widget.height() > screen.y() + screen.height(): y -= 24 + widget.height() if y < screen.y(): y = screen.y() if x < screen.x(): x = screen.x() widget.move(x, y) if widget.windowFlags() & Qt.ToolTip != Qt.ToolTip: widget.setWindowFlags(Qt.ToolTip) widget.ensurePolished() widget.show() _widget = widget _timer.start(timeout)
def _menu_context_tree(self, point): index = self.indexAt(point) if not index.isValid(): return item = self.itemAt(point) handler = None menu = QMenu(self) if item.isFolder or item.parent() is None: self._add_context_menu_for_folders(menu, item) elif not item.isFolder: self._add_context_menu_for_files(menu, item) if item.parent() is None: #get the extra context menu for this projectType handler = settings.get_project_type_handler(item.projectType) self._add_context_menu_for_root(menu, item) menu.addMenu(self._folding_menu) #menu for all items (legacy API)! extra_menus = self.extra_menus.get('all', ()) #menu for all items! for m in extra_menus: if isinstance(m, QMenu): menu.addSeparator() menu.addMenu(m) #menu for the Project Type(if present) if handler: for m in handler.get_context_menus(): if isinstance(m, QMenu): menu.addSeparator() menu.addMenu(m) #show the menu! menu.exec_(QCursor.pos())
def verifier_feuille(self, eq1, eq2): print eq1, eq2 for nom, eq in (('d1', eq1), ('d2', eq2)): if nom in self.feuille_actuelle.objets.noms: d = self.feuille_actuelle.objets[nom] d.label(mode=NOM) champ = self.feuille_actuelle.objets['champcache_' + nom] M, N = d M = (int(M.x), int(M.y)) N = (int(N.x), int(N.y)) if self.eq_reduite(M, N) == eq: d.style(couleur='g') champ.texte = 'ok' msg = 'La droite %s est correcte.' % nom if nom == 'd1': msg += ' Construisez maintenant d2.' else: print self.eq_reduite(*d), eq d.style(couleur='r') # On peut mettre n'importe quoi différent de ok dans # champ, l'idée étant que si la droite est fausse mais # n'a pas changé, on ne perde pas de point, et par # contre on perde des points en cas de changement si # c'est toujours faux. champ.texte = str(d.equation) msg = "Attention, la droite %s est fausse." % nom QToolTip.showText(QCursor.pos(), msg) self.canvas.message(msg, temporaire=False)
def __autoScrollAdvance(self): """Advance the auto scroll """ pos = QCursor.pos() pos = self.mapFromGlobal(pos) margin = self.__autoScrollMargin vvalue = self.verticalScrollBar().value() hvalue = self.horizontalScrollBar().value() vrect = QRect(0, 0, self.width(), self.height()) # What should be the speed advance = 10 # We only do auto scroll if the mouse is inside the view. if vrect.contains(pos): if pos.x() < vrect.left() + margin: self.horizontalScrollBar().setValue(hvalue - advance) if pos.y() < vrect.top() + margin: self.verticalScrollBar().setValue(vvalue - advance) if pos.x() > vrect.right() - margin: self.horizontalScrollBar().setValue(hvalue + advance) if pos.y() > vrect.bottom() - margin: self.verticalScrollBar().setValue(vvalue + advance) if self.verticalScrollBar().value() == vvalue and \ self.horizontalScrollBar().value() == hvalue: self.__stopAutoScroll() else: self.__stopAutoScroll() log.debug("Auto scroll advance")
def process_custom_menu(self, point): item = self.select_item_at(point) if not item: return node = item.node menu = QMenu(self.view) # Populate menu if node.tag == 'run': menu.addAction(self.actGetInfoSimulationRuns) menu.addAction(self.actDeleteRun) elif node.tag == 'indicator_batches': menu.addAction(self.actAddNewIndicatorBatch) elif node.tag == 'simulation_runs': menu.addAction(self.actImportRun) elif node.tag == 'indicator_batch': menu.addAction(self.actAddVisualizationToBatch) run_batch_on_menu = QMenu('Run indicator batch on...') self._createBatchRunMenu(run_batch_on_menu) menu.addMenu(run_batch_on_menu) elif node.tag == 'batch_visualization': # get('type') == 'batch_visualization': menu.addAction(self.actConfigureExistingBatchIndicatorVis) self.add_default_menu_items_for_node(node, menu) if not menu.isEmpty(): menu.exec_(QCursor.pos())
def _shouldSaveEvent(self, event): if isinstance(event, QMouseEvent): # Ignore most mouse movement events if the user isn't pressing anything. if event.type() == QEvent.MouseMove \ and int(event.button()) == 0 \ and int(event.buttons()) == 0 \ and int(event.modifiers()) == 0: # Somewhat hackish (and slow), but we have to record mouse movements during combo box usage. # Same for QMenu usage (on Mac, it doesn't seem to matter, but on Fedora it does matter.) widgetUnderCursor = QApplication.instance().widgetAt( QCursor.pos() ) if widgetUnderCursor is not None and widgetUnderCursor.objectName() == "qt_scrollarea_viewport": return has_ancestor(widgetUnderCursor, QComboBox) if isinstance(widgetUnderCursor, QMenu): return True return False else: return True # Ignore non-spontaneous events if not event.spontaneous(): return False if event.type() in self.IgnoredEventTypes: return False if isinstance(event, self.IgnoredEventClasses): return False return True
def timerEvent(self, event): """Handle events sent by the kinetic timer to decrease progressively the scrolling speed, eventually halting it. """ count = 0 if self._kineticData._state == KineticData.ManualScroll: count += 1 cursorPos = QCursor.pos() self._kineticData._speed = cursorPos - self._kineticData._dragPos self._kineticData._dragPos = cursorPos elif self._kineticData._state == KineticData.AutoScroll: count += 1 p = self.scrollOffset() if self._kineticData._speed == QPoint(0, 0) or not self.setScrollOffset(p - self._kineticData._speed): self._kineticData._state = KineticData.Steady # reset speed to 0, as wheel scrolling accumulates speed instead of setting it to a fixed value. self._kineticData._speed = QPoint(0,0) # reset count to 0 to stop iterating. count = 0 self._kineticData._speed = deaccelerate(self._kineticData._speed, 1, self._kineticData._maxSpeed) if count == 0: self._kineticData._ticker.stop() self.kineticScrollingActive.emit(False) super(KineticScrollArea, self).timerEvent(event);
def process_custom_menu(self, point): ''' See XmlController for documentation ''' item = self.select_item_at(point) if not item: return menu = QMenu() node = item.node if node.get('executable') == 'True': menu.addAction(self.actRunScenario) elif node.get('type') in ['selectable', 'model_choice']: menu.addAction(self.actMoveNodeUp) menu.addAction(self.actMoveNodeDown) elif node.tag == 'models_to_run': # special case of a selectable list models_menu = QMenu(menu) models_menu.setTitle('Add model to run') models_menu.setIcon(IconLibrary.icon('add')) available_model_names = get_model_names(self.project) for model_name in available_model_names: cb = lambda x = model_name, y = self.selected_index(): self.addModel(y, x) action = self.create_action('model', model_name, cb) models_menu.addAction(action) menu.addMenu(models_menu) self.add_default_menu_items_for_node(node, menu) if not menu.isEmpty(): menu.exec_(QCursor.pos())
def showContextMenu(self): opts = [ [_("Mark Note"), "*", self.onMark], [_("Bury Note"), "-", self.onBuryNote], [_("Suspend Card"), "@", self.onSuspendCard], [_("Suspend Note"), "!", self.onSuspend], [_("Delete Note"), "Delete", self.onDelete], [_("Options"), "O", self.onOptions], None, [_("Replay Audio"), "R", self.replayAudio], [_("Record Own Voice"), "Shift+V", self.onRecordVoice], [_("Replay Own Voice"), "V", self.onReplayRecorded], ] m = QMenu(self.mw) for row in opts: if not row: m.addSeparator() continue label, scut, func = row a = m.addAction(label) a.setShortcut(QKeySequence(scut)) a.connect(a, SIGNAL("triggered()"), func) #Only change is the following statement runHook("Reviewer.contextMenuEvent", self, m) m.exec_(QCursor.pos())
def wait_cursor(): try: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) except: pass
def accept(self): self.settings.setValue("/Processing/dialogBase", self.saveGeometry()) checkCRS = ProcessingConfig.getSetting( ProcessingConfig.WARN_UNMATCHING_CRS) try: self.setParamValues() if checkCRS and not self.alg.checkInputCRS(): reply = QMessageBox.question( self, self.tr("Unmatching CRS's"), self.tr('Layers do not all use the same CRS. This can ' 'cause unexpected results.\nDo you want to ' 'continue?'), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.No: return msg = self.alg._checkParameterValuesBeforeExecuting() if msg: QMessageBox.warning(self, self.tr('Unable to execute algorithm'), msg) return self.btnRun.setEnabled(False) self.btnClose.setEnabled(False) buttons = self.mainWidget.iterateButtons self.iterateParam = None for i in range(len(buttons.values())): button = buttons.values()[i] if button.isChecked(): self.iterateParam = buttons.keys()[i] break self.progressBar.setMaximum(0) self.lblProgress.setText(self.tr('Processing algorithm...')) # Make sure the Log tab is visible before executing the algorithm try: self.tabWidget.setCurrentIndex(1) self.repaint() except: pass QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.setInfo( self.tr('<b>Algorithm %s starting...</b>') % self.alg.name) if self.iterateParam: if runalgIterating(self.alg, self.iterateParam, self): self.finish() else: QApplication.restoreOverrideCursor() self.resetGUI() else: command = self.alg.getAsCommand() if command: ProcessingLog.addToLog(ProcessingLog.LOG_ALGORITHM, command) if runalg(self.alg, self): self.finish() else: QApplication.restoreOverrideCursor() self.resetGUI() except AlgorithmDialogBase.InvalidParameterValue as e: try: self.buttonBox.accepted.connect( lambda: e.widget.setPalette(QPalette())) palette = e.widget.palette() palette.setColor(QPalette.Base, QColor(255, 255, 0)) e.widget.setPalette(palette) self.lblProgress.setText( self.tr('<b>Missing parameter value: %s</b>') % e.parameter.description) return except: QMessageBox.critical( self, self.tr('Unable to execute algorithm'), self.tr('Wrong or missing parameter values'))
def waitCursor(): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
def writeLeaflet(cls, iface, feedback, folder, layer_list, visible, cluster, json, params, popup): outputProjectFileName = folder QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) legends = {} canvas = iface.mapCanvas() project = QgsProject.instance() mapSettings = canvas.mapSettings() title = project.title() pluginDir = os.path.dirname(os.path.realpath(__file__)) stamp = datetime.now().strftime("%Y_%m_%d-%H_%M_%S_%f") outputProjectFileName = os.path.join(outputProjectFileName, 'qgis2web_' + unicode(stamp)) outputIndex = os.path.join(outputProjectFileName, 'index.html') mapLibLocation = params["Data export"]["Mapping library location"] minify = params["Data export"]["Minify GeoJSON files"] precision = params["Data export"]["Precision"] debugLibs = params["Data export"]["Use debug libraries"] extent = params["Scale/Zoom"]["Extent"] minZoom = params["Scale/Zoom"]["Min zoom level"] maxZoom = params["Scale/Zoom"]["Max zoom level"] restrictToExtent = params["Scale/Zoom"]["Restrict to extent"] basemapList = params["Appearance"]["Base layer"] matchCRS = params["Appearance"]["Match project CRS"] addressSearch = params["Appearance"]["Add address search"] locate = params["Appearance"]["Geolocate user"] measure = params["Appearance"]["Measure tool"] highlight = params["Appearance"]["Highlight on hover"] layerSearch = params["Appearance"]["Layer search"] popupsOnHover = params["Appearance"]["Show popups on hover"] template = params["Appearance"]["Template"] usedFields = [ALL_ATTRIBUTES] * len(popup) QgsApplication.initQgis() dataStore, cssStore = writeFoldersAndFiles( pluginDir, feedback, outputProjectFileName, cluster, measure, matchCRS, layerSearch, canvas, mapLibLocation, addressSearch, locate, debugLibs) writeCSS(cssStore, mapSettings.backgroundColor().name(), feedback) wfsLayers = "" labelCode = "" useMultiStyle = False useHeat = False useShapes = False useOSMB = False useWMTS = False useRaster = False scaleDependentLayers = "" labelVisibility = "" new_src = "" crs = QgsCoordinateReferenceSystem.EpsgCrsId exp_crs = QgsCoordinateReferenceSystem(4326, crs) lyrCount = 0 for layer, jsonEncode, eachPopup, clst in zip(layer_list, json, popup, cluster): rawLayerName = layer.name() safeLayerName = re.sub('[\W_]+', '', rawLayerName) + unicode(lyrCount) if layer.providerType() != 'WFS' or jsonEncode is True and layer: if layer.type() == QgsMapLayer.VectorLayer: feedback.showFeedback('Exporting %s to JSON...' % layer.name()) exportVector(layer, safeLayerName, eachPopup, dataStore, restrictToExtent, iface, extent, precision, exp_crs, minify) new_src += jsonScript(safeLayerName) scaleDependentLabels =\ scaleDependentLabelScript(layer, safeLayerName) labelVisibility += scaleDependentLabels feedback.completeStep() elif layer.type() == QgsMapLayer.RasterLayer: if layer.dataProvider().name() != "wms": layersFolder = os.path.join(outputProjectFileName, "data") exportRaster(layer, lyrCount, layersFolder, feedback) if layer.hasScaleBasedVisibility(): scaleDependentLayers += scaleDependentLayerScript( layer, safeLayerName, clst) lyrCount += 1 if scaleDependentLayers != "": scaleDependentLayers = scaleDependentScript(scaleDependentLayers) crsSrc = mapSettings.destinationCrs() crsAuthId = crsSrc.authid() crsProj4 = crsSrc.toProj4() middle = """ <script>""" if highlight or popupsOnHover: selectionColor = mapSettings.selectionColor().name() middle += highlightScript(highlight, popupsOnHover, selectionColor) if extent == "Canvas extent": pt0 = canvas.extent() crsDest = QgsCoordinateReferenceSystem(4326) xform = QgsCoordinateTransform(crsSrc, crsDest) pt1 = xform.transform(pt0) bbox_canvas = [ pt1.yMinimum(), pt1.yMaximum(), pt1.xMinimum(), pt1.xMaximum() ] bounds = '[[' + unicode(pt1.yMinimum()) + ',' bounds += unicode(pt1.xMinimum()) + '],[' bounds += unicode(pt1.yMaximum()) + ',' bounds += unicode(pt1.xMaximum()) + ']]' if matchCRS and crsAuthId != 'EPSG:4326': middle += crsScript(crsAuthId, crsProj4) else: bounds = 0 if matchCRS and crsAuthId != 'EPSG:4326': middle += crsScript(crsAuthId, crsProj4) middle += mapScript(extent, matchCRS, crsAuthId, measure, maxZoom, minZoom, bounds, locate) middle += featureGroupsScript() if (len(basemapList) == 0 or matchCRS): basemapText = "" else: basemapText = basemapsScript(basemapList, maxZoom) extentCode = extentScript(extent, restrictToExtent) new_src += middle new_src += basemapText new_src += extentCode for count, layer in enumerate(layer_list): rawLayerName = layer.name() safeLayerName = re.sub('[\W_]+', '', rawLayerName) + unicode(count) if layer.type() == QgsMapLayer.VectorLayer: (new_src, legends, wfsLayers, labelCode, useMultiStyle, useHeat, useShapes, useOSMB) = writeVectorLayer( layer, safeLayerName, usedFields[count], highlight, popupsOnHover, popup[count], outputProjectFileName, wfsLayers, cluster[count], visible[count], json[count], legends, new_src, canvas, count, restrictToExtent, extent, feedback, labelCode, useMultiStyle, useHeat, useShapes, useOSMB) elif layer.type() == QgsMapLayer.RasterLayer: if layer.dataProvider().name() == "wms": feedback.showFeedback('Writing %s as WMS layer...' % layer.name()) new_obj, useWMTS = wmsScript(layer, safeLayerName, useWMTS) feedback.completeStep() else: useRaster = True feedback.showFeedback('Writing %s as raster layer...' % layer.name()) new_obj = rasterScript(layer, safeLayerName) feedback.completeStep() if visible[count]: new_obj += """ map.addLayer(overlay_""" + safeLayerName + """);""" new_src += new_obj new_src += scaleDependentLayers if title != "": titleStart = unicode(titleSubScript(title).decode("utf-8")) new_src += unicode(titleStart) if addressSearch: address_text = addressSearchScript() new_src += address_text if (params["Appearance"]["Add layers list"] and params["Appearance"]["Add layers list"] != "" and params["Appearance"]["Add layers list"] != "None"): new_src += addLayersList( basemapList, matchCRS, layer_list, cluster, legends, params["Appearance"]["Add layers list"] == "Expanded") if project.readBoolEntry("ScaleBar", "/Enabled", False)[0]: placement = project.readNumEntry("ScaleBar", "/Placement", 0)[0] placement = PLACEMENT[placement] end = scaleBar(placement) else: end = '' if cluster[count]: layerType = "cluster" else: layerType = "layer" searchLayer = "%s_%s" % (layerType, params["Appearance"]["Search layer"]) end += endHTMLscript(wfsLayers, layerSearch, labelCode, labelVisibility, searchLayer, useHeat, useRaster) new_src += end try: writeHTMLstart(outputIndex, title, cluster, addressSearch, measure, matchCRS, layerSearch, canvas, mapLibLocation, locate, new_src, template, feedback, debugLibs, useMultiStyle, useHeat, useShapes, useOSMB, useWMTS) except Exception as e: QgsMessageLog.logMessage(traceback.format_exc(), "qgis2web", level=QgsMessageLog.CRITICAL) finally: QApplication.restoreOverrideCursor() return outputIndex
def __init__(self, canvas): super(QgsMapTool, self).__init__(canvas) self.mCanvas = canvas self.mCursor = QCursor(Qt.ArrowCursor) self.mDragging = False
def __init__(self, canvas): self.canvas = canvas QgsMapToolIdentify.__init__(self, canvas) self.setCursor(QCursor(QPixmap(Cursor), 1, 6))
def show_menu_navigation(self): self.menuNavigate.exec_(QCursor.pos())
def __init__(self, layer, settingsdict={}): #show the user this may take a long time... QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.settingsdict = settingsdict provider = layer.dataProvider() # OGR provider kolumnindex = provider.fieldNameIndex( 'obsid') # To find the column named 'obsid' observations = layer.selectedFeatures() reportfolder = os.path.join(QDir.tempPath(), 'midvatten_reports') if not os.path.exists(reportfolder): os.makedirs(reportfolder) reportpath = os.path.join(reportfolder, "w_qual_report.html") #f = open(reportpath, "wb" ) f = codecs.open(reportpath, "wb", "utf-8") #write some initiating html rpt = r"""<head><title>%s</title></head>""" % ru( QCoreApplication.translate( u'Wqualreport', u'water quality report from Midvatten plugin for QGIS')) rpt += r""" <meta http-equiv="content-type" content="text/html; charset=utf-8" />""" #NOTE, all report data must be in 'utf-8' rpt += "<html><body>" #rpt += "<table width=\"100%\" border=\"1\">\n" #rpt2 = rpt.encode("utf-8") f.write(rpt) dbconnection = db_utils.DbConnectionManager() for i, object in enumerate(observations): attributes = observations[i] obsid = attributes[kolumnindex] try: print('about to get data for ' + obsid + ', at time: ' + str(time.time())) #debug except: pass ReportData = self.GetData( self.settingsdict['database'], obsid, dbconnection) # one observation at a time try: print('done with getting data for ' + obsid + ', at time: ' + str(time.time())) #debug except: pass if ReportData: self.WriteHTMLReport(ReportData, f) try: print('wrote html report for ' + obsid + ', at time: ' + str(time.time())) #debug except: pass dbconnection.closedb() #write some finishing html and close the file f.write("\n</body></html>") f.close() QApplication.restoreOverrideCursor( ) #now this long process is done and the cursor is back as normal if ReportData: QDesktopServices.openUrl(QUrl.fromLocalFile(reportpath))
app.window.showFullScreen() app.template_path = os.path.abspath(".") app.static_path = os.path.abspath(".") app.template = ("index.html", {"username": "******"}) app.bind(pyGUI()) # Instructions for running application if __name__ == "__main__": qtGuiHandler = QTGuiHandler() qtGuiHandler.set_text("Bereit") QApplication.setOverrideCursor(QCursor(Qt.BlankCursor)) cherrypy.tree.mount(RESTService(), '/') if sys.platform.startswith('linux'): cherrypy.config.update({ 'server.socket_host': 'raspi.local', 'server.socket_port': 8888 }) else: cherrypy.config.update({'server.socket_port': 8888}) cherrypy.engine.start() # The driver file will have to be imported everywhere in back-end. # So, always keep app.start() in if __name__ == "__main__" conditional
def export_gcode(self): """ Generate and export G-code. """ suggestion = '{}.nc'.format(splitext(self.pt.pathmap)[0]) if self.QGIS_VERSION == 2: gcode_file = \ QFileDialog.getSaveFileName(self, 'Save G-code as...', suggestion, filter='G-code file (*.nc)') else: gcode_file, __ = \ QFileDialog.getSaveFileName(self, 'Save G-code as...', suggestion, filter='G-code file (*.nc)') if gcode_file: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.pt.gcodefile = gcode_file self.pt.outputpng = '{}_preview.png'.format( splitext(gcode_file)[0]) if self.laser_mode.isChecked(): power = float(self.power_pct.text()) / 100.0 power_max = float(self.power_max.text()) power_min = float(self.power_min.text()) spindle_speed = power * (power_max - power_min) + power_min laser_mode = True else: spindle_speed = None laser_mode = False if self.enable_offsets.isChecked(): try: offset_x = float(self.offset_x.text()) except ValueError: offset_x = 0 try: offset_y = float(self.offset_y.text()) except ValueError: offset_y = 0 try: offset_z = float(self.offset_z.text()) except ValueError: offset_z = 0 else: offset_x = 0 offset_y = 0 offset_z = 0 try: optimize = float(self.optimize.text()) except ValueError: optimize = 0 self.pt.trace_paths(float(self.x_width.text()), float(self.z_depth.text()), float(self.zero_x.text()) / 100.0, float(self.zero_y.text()) / 100.0, float(self.safe_z.text()), float(self.feed_plunge.text()), float(self.feed_carve.text()), float(optimize), spindle_speed, offset_x, offset_y, offset_z, laser_mode, self.rescale_heightmap.isChecked()) QApplication.restoreOverrideCursor() QMessageBox.about(self, 'PathTracer', 'G-code exported.')
def trackMouse(self): """ Mouse position presentation in GUI TODO: after implementing workspace calibration display the world coordinates the mouse points to in the RGB video image. """ x = QWidget.mapFromGlobal(self, QCursor.pos()).x() y = QWidget.mapFromGlobal(self, QCursor.pos()).y() count = 0 if ((x < MIN_X) or (x >= MAX_X) or (y < MIN_Y) or (y >= MAX_Y)): self.ui.rdoutMousePixels.setText("(-,-,-)") self.ui.rdoutMouseWorld.setText("(-,-,-)") # posesall = self.rexarm.get_positions() # endeffectorpos = FK_dh(posesall,0) # if path.exists("traj_fast_not_smooth.txt"): # with open('traj_fast_not_smooth.txt','a') as f: # f.write(str(self.rexarm.get_wrist_pose())+'\n') # else : # with open('traj_fast_not_smooth.txt','w') as f: # f.write("Traj Not Smooth\n") else: # Subtracting the X and Y distance corresponding to image origin frame to find cursor location with reference to imae frame x = x - MIN_X y = y - MIN_Y # Checking if the Kinect depth camera is producing output if (self.kinect.currentDepthFrame.any() != 0): z = self.kinect.currentDepthFrame[y][x] # Display the x,y (pixels), z (10 bit number) coordinates self.ui.rdoutMousePixels.setText("(%.0f,%.0f,%.0f)" % (x, y, z)) # Checking if the calibration has been done if self.sm.calibration_state() == True: ############################################# # CAMERA FRAME TO DEPTH FRAME # ############################################# # Taking in the pixel values in camera frame and transforming to the kinect depth frame pixel_value = np.array([x, y]) # Converting 10 bit depth to real distance using provided analytical function z = self.kinect.currentDepthFrame[int( pixel_value.item(1))][int(pixel_value.item(0))] Z = 12.36 * np.tan(float(z) / 2842.5 + 1.1863) # 95 cm marks the z location of the base plane wrt to the camera. Subtracting 95 to measure +z from the base plane Z_modified = 95 - Z ############################################# # CAMERA FRAME TO WORLD FRAME # ############################################# # Extracting the origin of the camera frame (Following 4 quadrant system) pix_center = self.sm.pixel_center_loc() # X and Y locations in the RGB space in pixels with (0,0) at the robot base center x = x - pix_center.item(0) y = pix_center.item(1) - y # Taking in the pixel values in camera frame and transforming to the world frame pixel_value = np.array([x, y]) pixel_value = np.transpose(pixel_value) # Extracting the affine matrix computed during camera calibration affine = self.sm.return_affine() affine = affine[0:2, 0:2] # World x,y location corresponding to iamge frame x,y location world_value = np.matmul(affine, pixel_value) ############################################# # SOLVE PNP # ############################################# # rot,trans = self.sm.return_solvepnp() # cam = self.sm.return_intrinsic() # xyz_c = Z*rgb_pt.T # xyz_c = np.linalg.inv(cam).dot(xyz_c) # xyz_c = xyz_c - trans # world_value = xyz_c*rot # -0.197*float(z) + 142.772 # self.kinect.detectBlocksInDepthImage() # self.kinect.processVideoFrame() # Displaying the World X,Y and Z coordinates in GUI self.ui.rdoutMouseWorld.setText( "(%.0f,%.0f,%.1f)" % (world_value.item(0), world_value.item(1), Z_modified)) # self.sm.WC = [world_value.item(0)*10,world_value.item(1)*10,ZZ*10] else: self.ui.rdoutMouseWorld.setText("(-,-,-)")
def open_table(self): if self.tablecombo.currentIndex() <= 0: return if self.tablecombo.currentIndex() < self.tablecombo.count() - 1: self.table = self.tablecombo.currentText() else: self.table = self.sqltext.toPlainText() table = SqlTable(dict(host=self.host, port=self.port, database=self.database, user=self.username, password=self.password), self.table, inspect_values=False) sample = False if table.approx_len() > LARGE_TABLE and self.guess_values: confirm = QMessageBox(self) confirm.setIcon(QMessageBox.Warning) confirm.setText("Attribute discovery might take " "a long time on large tables.\n" "Do you want to auto discover attributes?") confirm.addButton("Yes", QMessageBox.YesRole) no_button = confirm.addButton("No", QMessageBox.NoRole) sample_button = confirm.addButton("Yes, on a sample", QMessageBox.YesRole) confirm.exec() if confirm.clickedButton() == no_button: self.guess_values = False elif confirm.clickedButton() == sample_button: sample = True self.information(1) if self.guess_values: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) if sample: s = table.sample_time(1) domain = s.get_domain(guess_values=True) self.information( 1, "Domain was generated from a sample of the table.") else: domain = table.get_domain(guess_values=True) QApplication.restoreOverrideCursor() table.domain = domain if self.download: if table.approx_len() > MAX_DL_LIMIT: QMessageBox.warning( self, 'Warning', "Data is too big to download.\n" "Consider using the Data Sampler widget to download " "a sample instead.") self.download = False elif table.approx_len() > AUTO_DL_LIMIT: confirm = QMessageBox.question( self, 'Question', "Data appears to be big. Do you really " "want to download it to local memory?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if confirm == QMessageBox.No: self.download = False if self.download: table.download_data(MAX_DL_LIMIT) table = Table(table) self.send("Data", table)
def fillColumnCombos(self): query = self._getSqlQuery() if query == "": return QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.uniqueCombo.clear() self.geomCombo.clear() # get a new alias aliasIndex = 0 while True: alias = "_%s__%d" % ("subQuery", aliasIndex) escaped = re.compile('\\b("?)' + re.escape(alias) + '\\1\\b') if not escaped.search(query): break aliasIndex += 1 # remove a trailing ';' from query if present if query.strip().endswith(';'): query = query.strip()[:-1] # get all the columns cols = [] connector = self.db.connector sql = u"SELECT * FROM (%s\n) AS %s LIMIT 0" % ( unicode(query), connector.quoteId(alias) ) c = None try: c = connector._execute(None, sql) cols = connector._get_cursor_columns(c) except BaseError as e: QApplication.restoreOverrideCursor() DlgDbError.showError(e, self) return finally: if c: c.close() del c # get sensible default columns. do this before sorting in case there's hints in the column order (eg, id is more likely to be first) try: defaultGeomCol = next(col for col in cols if col in ['geom','geometry','the_geom']) except: defaultGeomCol = None try: defaultUniqueCol = [col for col in cols if 'id' in col][0] except: defaultUniqueCol = None cols.sort() self.uniqueCombo.addItems( cols ) self.geomCombo.addItems( cols ) # set sensible default columns try: self.geomCombo.setCurrentIndex( cols.index(defaultGeomCol) ) except: pass try: self.uniqueCombo.setCurrentIndex( cols.index(defaultUniqueCol) ) except: pass QApplication.restoreOverrideCursor()
def _menu_context_tree(self, point): index = self.indexAt(point) if not index.isValid(): return item = self.itemAt(point) handler = None menu = QMenu(self) if item.isFolder or item.parent() is None: action_add_file = menu.addAction(QIcon(resources.IMAGES['new']), self.tr("Add New File")) self.connect(action_add_file, SIGNAL("triggered()"), self._add_new_file) action_add_folder = menu.addAction(QIcon( resources.IMAGES['openProj']), self.tr("Add New Folder")) self.connect(action_add_folder, SIGNAL("triggered()"), self._add_new_folder) action_create_init = menu.addAction( self.tr("Create '__init__' Complete")) self.connect(action_create_init, SIGNAL("triggered()"), self._create_init) if item.isFolder and (item.parent() != None): action_remove_folder = menu.addAction(self.tr("Remove Folder")) self.connect(action_remove_folder, SIGNAL("triggered()"), self._delete_folder) elif not item.isFolder: action_rename_file = menu.addAction(self.tr("Rename File")) action_move_file = menu.addAction(self.tr("Move File")) action_copy_file = menu.addAction(self.tr("Copy File")) action_remove_file = menu.addAction( self.style().standardIcon(QStyle.SP_DialogCloseButton), self.tr("Delete File")) self.connect(action_remove_file, SIGNAL("triggered()"), self._delete_file) self.connect(action_rename_file, SIGNAL("triggered()"), self._rename_file) self.connect(action_copy_file, SIGNAL("triggered()"), self._copy_file) self.connect(action_move_file, SIGNAL("triggered()"), self._move_file) #Allow to edit Qt UI files with the appropiate program if item.lang() == 'ui': action_edit_ui_file = menu.addAction(self.tr("Edit UI File")) self.connect(action_edit_ui_file, SIGNAL("triggered()"), self._edit_ui_file) #menu per file language! for m in self.EXTRA_MENUS.get(item.lang(), ()): menu.addSeparator() menu.addMenu(m) if item.parent() is None: menu.addSeparator() actionRunProject = menu.addAction(QIcon( resources.IMAGES['play']), self.tr("Run Project")) self.connect(actionRunProject, SIGNAL("triggered()"), SIGNAL("runProject()")) actionMainProject = menu.addAction(self.tr("Set as Main Project")) self.connect(actionMainProject, SIGNAL("triggered()"), lambda: self.set_default_project(item)) if item.addedToConsole: actionRemoveFromConsole = menu.addAction( self.tr("Remove this Project from the Python Console")) self.connect(actionRemoveFromConsole, SIGNAL("triggered()"), self._remove_project_from_console) else: actionAdd2Console = menu.addAction( self.tr("Add this Project to the Python Console")) self.connect(actionAdd2Console, SIGNAL("triggered()"), self._add_project_to_console) actionProperties = menu.addAction(QIcon(resources.IMAGES['pref']), self.tr("Project Properties")) self.connect(actionProperties, SIGNAL("triggered()"), self.open_project_properties) #get the extra context menu for this projectType handler = settings.get_project_type_handler(item.projectType) menu.addSeparator() action_refresh = menu.addAction( self.style().standardIcon(QStyle.SP_BrowserReload), self.tr("Refresh Project")) self.connect(action_refresh, SIGNAL("triggered()"), self._refresh_project) action_close = menu.addAction( self.style().standardIcon(QStyle.SP_DialogCloseButton), self.tr("Close Project")) self.connect(action_close, SIGNAL("triggered()"), self._close_project) #menu for all items! for m in self.EXTRA_MENUS.get('all', ()): menu.addSeparator() menu.addMenu(m) #menu for the Project Type(if present) if handler: for m in handler.get_context_menus(): menu.addSeparator() menu.addMenu(m) #show the menu! menu.exec_(QCursor.pos())
def _actionHovered(self, action): tip = action.toolTip() QToolTip.showText(QCursor.pos(), tip)
class ParentMapTool(QgsMapTool): def __init__(self, iface, settings, action, index_action): """ Class constructor """ self.iface = iface self.canvas = self.iface.mapCanvas() self.settings = settings self.show_help = bool(int(self.settings.value('status/show_help', 1))) self.index_action = index_action self.layer_arc = None self.layer_connec = None self.layer_node = None self.layer_arc_man = None self.layer_connec_man = None self.layer_node_man = None self.layer_gully_man = None self.schema_name = None self.controller = None self.dao = None # Call superclass constructor and set current action QgsMapTool.__init__(self, self.canvas) self.setAction(action) # Snapper self.snapper_manager = SnappingConfigManager(self.iface) self.snapper = QgsMapCanvasSnapper(self.canvas) # Change map tool cursor self.cursor = QCursor() self.cursor.setShape(Qt.CrossCursor) # Get default cursor self.std_cursor = self.parent().cursor() # Set default vertex marker color = QColor(255, 100, 255) self.vertex_marker = QgsVertexMarker(self.canvas) self.vertex_marker.setIconType(QgsVertexMarker.ICON_CIRCLE) self.vertex_marker.setColor(color) self.vertex_marker.setIconSize(15) self.vertex_marker.setPenWidth(3) # Set default rubber band color_selection = QColor(254, 178, 76, 63) self.rubber_band = QgsRubberBand(self.canvas, QGis.Polygon) self.rubber_band.setColor(color) self.rubber_band.setFillColor(color_selection) self.rubber_band.setWidth(1) self.reset() self.force_active_layer = True # Set default encoding reload(sys) sys.setdefaultencoding('utf-8') #@UndefinedVariable def get_cursor_multiple_selection(self): """ Set cursor for multiple selection """ path_folder = os.path.join(os.path.dirname(__file__), os.pardir) path_cursor = os.path.join(path_folder, 'icons', '201.png') if os.path.exists(path_cursor): cursor = QCursor(QPixmap(path_cursor)) else: cursor = QCursor(Qt.ArrowCursor) return cursor def set_layers(self, layer_arc_man, layer_connec_man, layer_node_man, layer_gully_man=None): """ Sets layers involved in Map Tools functions Sets Snapper Manager """ self.layer_arc_man = layer_arc_man self.layer_connec_man = layer_connec_man self.layer_node_man = layer_node_man self.layer_gully_man = layer_gully_man self.snapper_manager.set_layers(layer_arc_man, layer_connec_man, layer_node_man, layer_gully_man) def set_controller(self, controller): self.controller = controller self.schema_name = controller.schema_name self.plugin_dir = self.controller.plugin_dir self.snapper_manager.controller = controller def deactivate(self): # Uncheck button self.action().setChecked(False) # Restore previous snapping self.snapper_manager.recover_snapping_options() # Recover cursor self.canvas.setCursor(self.std_cursor) # Remove highlight self.vertex_marker.hide() def set_icon(self, widget, icon): """ Set @icon to selected @widget """ # Get icons folder icons_folder = os.path.join(self.plugin_dir, 'icons') icon_path = os.path.join(icons_folder, str(icon) + ".png") if os.path.exists(icon_path): widget.setIcon(QIcon(icon_path)) else: self.controller.log_info("File not found", parameter=icon_path) def set_action_pan(self): """ Set action 'Pan' """ try: self.iface.actionPan().trigger() except Exception: pass def reset(self): # Graphic elements self.rubber_band.reset(QGis.Polygon) # Selection self.snapped_feat = None def cancel_map_tool(self): """ Executed if user press right button or escape key """ # Reset rubber band self.reset() # Deactivate map tool self.deactivate() self.set_action_pan() def remove_markers(self): """ Remove previous markers """ vertex_items = [i for i in self.canvas.scene().items() if issubclass(type(i), QgsVertexMarker)] for ver in vertex_items: if ver in self.canvas.scene().items(): self.canvas.scene().removeItem(ver) def refresh_map_canvas(self): """ Refresh all layers present in map canvas """ self.canvas.refreshAllLayers() for layer_refresh in self.canvas.layers(): layer_refresh.triggerRepaint() def open_dialog(self, dlg=None, dlg_name=None, maximize_button=True, stay_on_top=True): """ Open dialog """ if dlg is None or type(dlg) is bool: dlg = self.dlg # Manage i18n of the dialog if dlg_name: self.controller.manage_translation(dlg_name, dlg) # Manage stay on top and maximize button if maximize_button and stay_on_top: dlg.setWindowFlags(Qt.WindowMinimizeButtonHint | Qt.WindowMaximizeButtonHint | Qt.WindowStaysOnTopHint) elif not maximize_button and stay_on_top: dlg.setWindowFlags(Qt.WindowMinimizeButtonHint | Qt.WindowStaysOnTopHint) elif maximize_button and not stay_on_top: dlg.setWindowFlags(Qt.WindowMaximizeButtonHint) # Open dialog dlg.open() def close_dialog(self, dlg=None, set_action_pan=True): """ Close dialog """ if dlg is None or type(dlg) is bool: dlg = self.dlg try: self.save_settings(dlg) dlg.close() if set_action_pan: map_tool = self.canvas.mapTool() # If selected map tool is from the plugin, set 'Pan' as current one if map_tool.toolName() == '': self.set_action_pan() except AttributeError: pass def load_settings(self, dialog=None): """ Load QGIS settings related with dialog position and size """ if dialog is None: dialog = self.dlg try: x = self.controller.plugin_settings_value(dialog.objectName() + "_x") y = self.controller.plugin_settings_value(dialog.objectName() + "_y") width = self.controller.plugin_settings_value(dialog.objectName() + "_width", dialog.property('width')) height = self.controller.plugin_settings_value(dialog.objectName() + "_height", dialog.property('height')) if int(x) < 0 or int(y) < 0: dialog.resize(int(width), int(height)) else: screens = ctypes.windll.user32 screen_x = screens.GetSystemMetrics(78) screen_y = screens.GetSystemMetrics(79) if int(x) > screen_x: x = int(screen_x) - int(width) if int(y) > screen_y: y = int(screen_y) dialog.setGeometry(int(x), int(y), int(width), int(height)) except: pass def save_settings(self, dialog=None): """ Save QGIS settings related with dialog position and size """ if dialog is None: dialog = self.dlg try: self.controller.plugin_settings_set_value(dialog.objectName() + "_width", dialog.property('width')) self.controller.plugin_settings_set_value(dialog.objectName() + "_height", dialog.property('height')) self.controller.plugin_settings_set_value(dialog.objectName() + "_x", dialog.pos().x()) self.controller.plugin_settings_set_value(dialog.objectName() + "_y", dialog.pos().y()) except: pass def check_expression(self, expr_filter, log_info=False): """ Check if expression filter @expr is valid """ if log_info: self.controller.log_info(expr_filter) expr = QgsExpression(expr_filter) if expr.hasParserError(): message = "Expression Error" self.controller.log_warning(message, parameter=expr_filter) return (False, expr) return (True, expr) def canvasMoveEvent(self, event): # Make sure active layer is always 'v_edit_node' cur_layer = self.iface.activeLayer() if cur_layer != self.layer_node and self.force_active_layer: self.iface.setActiveLayer(self.layer_node) # Hide highlight self.vertex_marker.hide() try: # Get current mouse coordinates x = event.pos().x() y = event.pos().y() event_point = QPoint(x, y) except(TypeError, KeyError): self.iface.actionPan().trigger() return # Snapping (retval, result) = self.snapper.snapToCurrentLayer(event_point, 2) # @UnusedVariable # That's the snapped features if result: # Get the point and add marker on it point = QgsPoint(result[0].snappedVertex) self.vertex_marker.setCenter(point) self.vertex_marker.show()
def handleHeaderMenu(self, pos): print('column(%d)' % self.table.horizontalHeader().logicalIndexAt(pos)) menu = QMenu() menu.addAction('Add') menu.addAction('Delete') menu.exec_(QCursor.pos())
def wait_cursor(application): application.setOverrideCursor(QCursor(Qt.WaitCursor)) try: yield finally: application.restoreOverrideCursor()
def readUrl(url): try: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) return urllib2.urlopen(url).read() finally: QApplication.restoreOverrideCursor()
def context_menu(self): menu = QMenu(self) menu.addAction("Primera opción") menu.addAction("Segunda opción") menu.addAction(":)") menu.exec_(QCursor.pos())
def openContextMenu(self, menu): menu.addAction(QIcon(":/icons/images/minus.png"), "Remove %s" % self.var.exp, self.remove) menu.addAction(QIcon(":/icons/images/save-html.png"), "Save HTML for %s" % self.var.exp, self.saveHtml) menu.exec_(QCursor.pos())
def process_custom_menu(self, position): ''' See XmlConfig.processCustomMenu for documentation ''' item = self.select_item_at(position) index = self.view.indexAt(position) cnt = self.model.rowCount(index.parent()) istop = index.row() == 0 isbottom = index.row() == cnt - 1 isonly = cnt == 1 if not item: return node = item.node menu = QMenu(self.view) # Tool files are the "actual" tools if node.tag == "tool": menu.addAction(self.actExecToolFile) if not isonly: menu.addSeparator() if not istop: menu.addAction(self.actMoveNodeUp) if not isbottom: menu.addAction(self.actMoveNodeDown) elif node.tag == "class_module": menu.addAction(self.actChangeClassModule) elif node.tag == "path_to_tool_modules": menu.addAction(self.actChangePathToTools) # "Tool library is a collection of tool groups elif node.tag == "tool_library": menu.addAction(self.actAddToolGroup) # Tool groups are groups of "tool files" elif node.tag == "tool_group": menu.addAction(self.actAddToolFile) if not isonly: menu.addSeparator() if not istop: menu.addAction(self.actMoveNodeUp) if not isbottom: menu.addAction(self.actMoveNodeDown) # Param Template is the parameter node for the tools -- where # users can build up a list of parameters that gets passed to the # tool function elif node.tag == "params": menu.addAction(self.actAddParam) elif node.tag == "param": menu.addAction(self.actEditParam) # A "tool config" is an alternative configuration for a tool that can be # put in a Tool Set elif node.tag == "tool_config": menu.addAction(self.actExecToolConfig) if not isonly: menu.addSeparator() if not istop: menu.addAction(self.actMoveNodeUp) if not isbottom: menu.addAction(self.actMoveNodeDown) # "Tool sets" is a collection of multiple tool sets elif node.tag == "tool_sets": menu.addAction(self.actAddNewToolSet) # A Tool set is a collection of (alternative) configurations for # existing tools. elif node.tag == "tool_set": menu.addAction(self.actExecBatch) menu.addSeparator() menu.addAction(self.actNewConfig) if not isonly: menu.addSeparator() if not istop: menu.addAction(self.actMoveNodeUp) if not isbottom: menu.addAction(self.actMoveNodeDown) elif node.tag == "documentation_path": menu.addAction(self.actOpenDocumentation) menu.addSeparator() menu.addAction(self.actCloneNode) # Default menu items self.add_default_menu_items_for_node(node, menu) # Now add the export and import methods menu.addSeparator() menu.addAction(self.actExportXMLToFile) menu.addAction(self.actImportXMLFromFile) # Check if the menu has any elements before exec is called if not menu.isEmpty(): menu.exec_(QCursor.pos())
def hoverEnterEvent(self, event): cursor = QCursor(Qt.OpenHandCursor) QApplication.instance().setOverrideCursor(cursor)
def __handleShowFileContextMenu(self, coord): " File context menu " self.__fileContextItem = self.recentFilesView.itemAt(coord) if self.__fileContextItem is not None: self.__fileMenu.popup(QCursor.pos()) return
def runAlgorithm(algOrName, onFinish, *args, **kwargs): if isinstance(algOrName, GeoAlgorithm): alg = algOrName else: alg = Processing.getAlgorithm(algOrName) if alg is None: print 'Error: Algorithm not found\n' QgsMessageLog.logMessage( Processing.tr('Error: Algorithm {0} not found\n').format( algOrName), Processing.tr("Processing")) return alg = alg.getCopy() if len(args) == 1 and isinstance(args[0], dict): # Set params by name and try to run the alg even if not all parameter values are provided, # by using the default values instead. setParams = [] for (name, value) in args[0].items(): param = alg.getParameterFromName(name) if param and param.setValue(value): setParams.append(name) continue output = alg.getOutputFromName(name) if output and output.setValue(value): continue print 'Error: Wrong parameter value %s for parameter %s.' % ( value, name) QgsMessageLog.logMessage( Processing.tr( 'Error: Wrong parameter value {0} for parameter {1}.'). format(value, name), Processing.tr("Processing")) ProcessingLog.addToLog( ProcessingLog.LOG_ERROR, Processing. tr('Error in %s. Wrong parameter value %s for parameter %s.' ) % (alg.name, value, name)) return # fill any missing parameters with default values if allowed for param in alg.parameters: if param.name not in setParams: if not param.setDefaultValue(): print( 'Error: Missing parameter value for parameter %s.' % (param.name)) QgsMessageLog.logMessage( Processing. tr('Error: Missing parameter value for parameter {0}.' ).format(param.name), Processing.tr("Processing")) ProcessingLog.addToLog( ProcessingLog.LOG_ERROR, Processing. tr('Error in %s. Missing parameter value for parameter %s.' ) % (alg.name, param.name)) return else: if len(args) != alg.getVisibleParametersCount( ) + alg.getVisibleOutputsCount(): print 'Error: Wrong number of parameters' QgsMessageLog.logMessage( Processing.tr('Error: Wrong number of parameters'), Processing.tr("Processing")) processing.alghelp(algOrName) return i = 0 for param in alg.parameters: if not param.hidden: if not param.setValue(args[i]): print 'Error: Wrong parameter value: ' \ + unicode(args[i]) QgsMessageLog.logMessage( Processing.tr('Error: Wrong parameter value: ') + unicode(args[i]), Processing.tr("Processing")) return i = i + 1 for output in alg.outputs: if not output.hidden: if not output.setValue(args[i]): print 'Error: Wrong output value: ' + unicode(args[i]) QgsMessageLog.logMessage( Processing.tr('Error: Wrong output value: ') + unicode(args[i]), Processing.tr("Processing")) return i = i + 1 msg = alg._checkParameterValuesBeforeExecuting() if msg: print 'Unable to execute algorithm\n' + unicode(msg) QgsMessageLog.logMessage( Processing.tr('Unable to execute algorithm\n{0}').format(msg), Processing.tr("Processing")) return if not alg.checkInputCRS(): print 'Warning: Not all input layers use the same CRS.\n' \ + 'This can cause unexpected results.' QgsMessageLog.logMessage( Processing. tr('Warning: Not all input layers use the same CRS.\nThis can cause unexpected results.' ), Processing.tr("Processing")) # Don't set the wait cursor twice, because then when you # restore it, it will still be a wait cursor. overrideCursor = False if iface is not None: cursor = QApplication.overrideCursor() if cursor is None or cursor == 0: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) overrideCursor = True elif cursor.shape() != Qt.WaitCursor: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) overrideCursor = True progress = None if kwargs is not None and "progress" in kwargs.keys(): progress = kwargs["progress"] elif iface is not None: progress = MessageBarProgress() ret = runalg(alg, progress) if ret: if onFinish is not None: onFinish(alg, progress) else: QgsMessageLog.logMessage( Processing.tr("There were errors executing the algorithm."), Processing.tr("Processing")) if overrideCursor: QApplication.restoreOverrideCursor() if isinstance(progress, MessageBarProgress): progress.close() return alg
def onGenerate(self): """ Slot raised to initiate the certificate generation process. """ self._notif_bar.clear() success_status = True config = self.current_config() self.last_data_source = config.data_source() if config is None: self._notif_bar.insertErrorNotification( QApplication.translate( "DocumentGeneratorDialog", "The entity configuration could not be extracted.")) return # Get selected records and validate records = self.tabWidget.currentWidget().entities() if self.chk_template_datasource.isChecked(): records = self._dummy_template_records() if len(records) == 0: self._notif_bar.insertErrorNotification( QApplication.translate( "DocumentGeneratorDialog", "Please load at least one entity record")) return if not self._docTemplatePath: self._notif_bar.insertErrorNotification( QApplication.translate( "DocumentGeneratorDialog", "Please select a document template to use")) return documentNamingAttrs = self.lstDocNaming.selectedMappings() if self.chkUseOutputFolder.checkState() == Qt.Checked and len( documentNamingAttrs) == 0: self._notif_bar.insertErrorNotification( QApplication.translate( "DocumentGeneratorDialog", "Please select at least one field for naming the output document" )) return # Set output file properties if self.rbExpImage.isChecked(): outputMode = DocumentGenerator.Image fileExtension = self.cboImageType.currentText() saveAsText = "Image File" else: outputMode = DocumentGenerator.PDF fileExtension = "pdf" saveAsText = "PDF File" # Show save file dialog if not using output folder if self.chkUseOutputFolder.checkState() == Qt.Unchecked: docDir = source_document_location() if self._outputFilePath: fileInfo = QFileInfo(self._outputFilePath) docDir = fileInfo.dir().path() self._outputFilePath = QFileDialog.getSaveFileName( self, QApplication.translate("DocumentGeneratorDialog", "Save Document"), docDir, "{0} (*.{1})".format( QApplication.translate("DocumentGeneratorDialog", saveAsText), fileExtension)) if not self._outputFilePath: self._notif_bar.insertErrorNotification( QApplication.translate( "DocumentGeneratorDialog", "Process aborted. No output file was specified.")) return # Include extension in file name self._outputFilePath = self._outputFilePath # + "." + fileExtension else: # Multiple files to be generated. pass self._doc_generator.set_link_field(config.link_field()) self._doc_generator.clear_attr_value_formatters() if not self.chk_template_datasource.isChecked(): # Apply cell formatters for naming output files self._doc_generator.set_attr_value_formatters(config.formatters()) entity_field_name = "id" # Iterate through the selected records progressDlg = QProgressDialog(self) progressDlg.setMaximum(len(records)) try: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) if self.pre_generate_func: self.pre_generate_func() for i, record in enumerate(records): progressDlg.setValue(i) if progressDlg.wasCanceled(): success_status = False break should_continue = True if self.record_process_func: should_continue = self.record_process_func(record, records) QgsApplication.processEvents() if not should_continue: continue # User-defined location if self.chkUseOutputFolder.checkState() == Qt.Unchecked: status, msg = self._doc_generator.run( self._docTemplatePath, entity_field_name, record.id, outputMode, filePath=self._outputFilePath) self._doc_generator.clear_temporary_layers() # Output folder location using custom naming else: status, msg = self._doc_generator.run( self._docTemplatePath, entity_field_name, record.id, outputMode, dataFields=documentNamingAttrs, fileExtension=fileExtension, data_source=self.ds_entity.name) self._doc_generator.clear_temporary_layers() if status: if self.record_post_process_func: self.record_post_process_func(record, records) if not status: result = QMessageBox.warning( self, QApplication.translate("DocumentGeneratorDialog", "Document Generate Error"), msg, QMessageBox.Ignore | QMessageBox.Abort) if result == QMessageBox.Abort: progressDlg.close() success_status = False # Restore cursor QApplication.restoreOverrideCursor() return # If its the last record and user has selected to ignore if i + 1 == len(records): progressDlg.close() success_status = False # Restore cursor QApplication.restoreOverrideCursor() return else: progressDlg.setValue(len(records)) QApplication.restoreOverrideCursor() if self.post_generate_func: self.post_generate_func() QMessageBox.information( self, QApplication.translate("DocumentGeneratorDialog", "Document Generation Complete"), QApplication.translate( "DocumentGeneratorDialog", "Document generation has successfully completed.")) except Exception as ex: LOGGER.debug(str(ex)) err_msg = sys.exc_info()[1] QApplication.restoreOverrideCursor() QMessageBox.critical( self, "STDM", QApplication.translate( "DocumentGeneratorDialog", "Error Generating documents - %s" % (err_msg))) success_status = False # Reset UI self.reset(success_status)
def hoverEnterEvent(self, event): # Change the cursor to indicate the line is draggable cursor = QCursor( Qt.OpenHandCursor ) QApplication.instance().setOverrideCursor( cursor )
def mousePressEvent(self, event): # Change the cursor to indicate "currently dragging" cursor = QCursor( Qt.ClosedHandCursor ) QApplication.instance().setOverrideCursor( cursor )
def sort(self, column, order): """ Sort model's list and check. """ self.headerorder.clear() self.headerorder[column] = order QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) if order == Qt.DescendingOrder: Reverse = True else: Reverse = False attrs = self.availableAttributes() try: attrpath = str(unicode(attrs[column]).encode('utf-8')) except IndexError: QApplication.restoreOverrideCursor() self.headerorder.clear() self.headerorder = {0:0} self.refresh(0) self.select(0) return if isinstance(self._list, VecNode): tmplist = [] for i in range(0, len(self._list)): tmplist.append(self._list[i]) self._list = tmplist if attrpath in self._default_attributes: if attrpath == "name": self._list = sorted(self._list, cmp=locale.strcoll, key=lambda Node: Node.name(), reverse=Reverse) elif attrpath == "size": self._list = sorted(self._list, key=lambda Node: Node.size(), reverse=Reverse) elif attrpath == "extension": self._list = sorted(self._list, cmp=locale.strcoll, key=lambda Node: Node.extension(), reverse=Reverse) elif attrpath == "path": self._list = sorted(self._list, cmp=locale.strcoll, key=lambda Node: Node.path(), reverse=Reverse) elif attrpath == "absolute": self._list = sorted(self._list, cmp=locale.strcoll, key=lambda Node: Node.absolute(), reverse=Reverse) elif attrpath == "module": self._list = sorted(self._list, cmp=self.cmp_fsobj, key=lambda Node: Node.fsobj(), reverse=Reverse) elif attrpath == "has children": self._list = sorted(self._list, key=lambda Node: Node.hasChildren(), reverse=Reverse) elif attrpath == "child count": self._list = sorted(self._list, key=lambda Node: Node.childCount(), reverse=Reverse) elif attrpath == "is deleted": self._list = sorted(self._list, key=lambda Node: Node.isDeleted(), reverse=Reverse) elif attrpath == "tags": self._list = sorted(self._list, key=lambda Node: len(Node.tags()), reverse=Reverse) else: self._list = sorted(self._list, cmp=self.cmp_none, key=lambda Node: self.attributesByName(Node, attrpath, ABSOLUTE_ATTR_NAME), reverse=Reverse) QApplication.restoreOverrideCursor() self.refresh(0) self.select(0) return
def __init__(self, parent=None): super(Surface, self).__init__(parent) self.setWindowFlags(Qt.SplashScreen | Qt.WindowStaysOnTopHint) self.setCursor(QCursor(Qt.CrossCursor)) self.setGeometry(getScreenDimensions()) self.prepareSurface()