class MiTraceView(QWidget): def __init__(self, do, parent): QWidget.__init__(self, parent) self.ui = Ui_MiTraceView() self.ui.setupUi(self) self.__do = do self.ui.commandEdit.lineEdit().returnPressed.connect(self.executeMiCommand) self.__do.gdb_connector.commandExecuted.connect(self.appendCommand) self.__do.gdb_connector.reader.asyncRecordReceived.connect(self.appendAsync) self.__timeAction = QAction(Icons.time, "Show Elapsed Time", self) self.__timeAction.setCheckable(True) self.__timeAction.setChecked(True) parent.titleBarWidget().addAction(self.__timeAction) parent.addClearAction() parent.clearRequested.connect(self.ui.traceView.clear) def appendCommand(self, cmd, rec, time): timestr = "[<i>%.3f</i>] " % time if self.__timeAction.isChecked() else "" self.ui.traceView.append("%s<b>%s</b>" % (timestr, cmd)) color = 'color="#ff3333"' if rec.class_ == GdbOutput.ERROR else "" self.ui.traceView.append("<font %s>%s</font>" % (color, rec.raw)) def appendAsync(self, rec): self.ui.traceView.append('<font color="#777777">%s</font>' % rec.raw) def executeMiCommand(self): cmd = str(self.ui.commandEdit.lineEdit().text()) self.ui.commandEdit.lineEdit().setText("") self.__do.gdb_connector.execute(cmd)
def load(self): self.initTranslations() cfg = SimuVis4.Globals.config cfgsec = self.name.lower() if not cfg.has_section(cfgsec): cfg.add_section(cfgsec) cfg.set_def(cfgsec, 'set_default_backend', 'yes') cfg.set_def(cfgsec, 'zoom_step_factor', '0.189207115002721') cfg.set_def(cfgsec, 'mouse_wheel_step', '15') glb = SimuVis4.Globals import matplotlib if matplotlib.__version__ < mplMinVersion or matplotlib.__version__ > mplMaxVersion: SimuVis4.Globals.logger.error(unicode(QCoreApplication.translate('MatPlot', 'MatPlot: need matplotlib version between %s and %s, but found %s')) % \ (mplMinVersion, mplMaxVersion, matplotlib.__version__)) return False self.matplotlib = matplotlib if cfg.getboolean(cfgsec, 'set_default_backend'): try: sys.path.append(os.path.split(__file__)[0]) matplotlib.use('module://backend_sv4agg') except: pass import backend_sv4agg self.backend_sv4agg = backend_sv4agg dpath = matplotlib.rcParams['datapath'] tmp = os.path.join(dpath, 'images') if os.path.isdir(tmp): dpath = tmp winIcon = QIcon(os.path.join(dpath, 'matplotlib.png')) testAction = QAction(winIcon, QCoreApplication.translate('MatPlot', '&MatPlot/PyLab Test'), SimuVis4.Globals.mainWin) testAction.setStatusTip(QCoreApplication.translate('MatPlot', 'Show a matplotlib/pylab test window')) QWidget.connect(testAction, SIGNAL("triggered()"), self.test) SimuVis4.Globals.mainWin.plugInMenu.addAction(testAction) return True
class ItemAutoConnecter( QObject ): def __init__( self, scene ): QObject.__init__( self, scene ) self.scene = scene self._action = QAction( "Auto Connect Items", self ) self.connect( self._action, SIGNAL( 'triggered( bool )' ), self.autoConnect ) def action( self ): return self._action def updateAction( self ): self._action.setEnabled( self.canConnect() ) def canConnect( self ): # Get all items sort by y position items = sorted( self.scene.graph.items(), key = lambda item: item.scenePos().y() ) # We need at least two items if len( items ) < 2: #print "Less than two items" return False # Top is source, bottom is sink if len( items[0].requiresPorts ) != 0 or len( items[-1].providesPorts ) != 0: #print "Top must be bottom and bottom sink" return False # Only single port items in between if len( items ) > 2 and set( sum( [ [ len( item.requiresPorts ), len( item.providesPorts ) ] for item in items[1:-1] ], [] ) ) != set([1]): #print "There are items with multiple ports" return False # Ports sequence ports = [ items[0].providesPorts[0] ] + sum( [ [ item.requiresPorts[0], item.providesPorts[0] ] for item in items[1:-1] ], [] ) + [ items[-1].requiresPorts[0] ] # Cancel if ports are already connected if max( [ len( self.scene.graph.outEdges( p ) ) for p in ports[0::2] ] ) != 0 or \ max( [ len( self.scene.graph.inEdges( p ) ) for p in ports[1::2] ] ) != 0: #print "Already connected" return False datatypes = [ p.datatype for p in ports ] if False in [ datatypes[i] == datatypes[i+1] for i in range( 0, len( datatypes ), 2 ) ]: return False return True # TODO allow more cases, respect already connected edges def autoConnect( self ): # Get all items sort by y position items = sorted( self.scene.graph.items(), key = lambda item: item.scenePos().y() ) # Connect? if not self.canConnect(): return ports = [ items[0].providesPorts[0] ] + sum( [ [ item.requiresPorts[0], item.providesPorts[0] ] for item in items[1:-1] ], [] ) + [ items[-1].requiresPorts[0] ] for i in range( 0, len( ports ), 2 ): self.scene.graph.addEdge( ports[i], ports[i+1] )
def _addFilterAction(self, filterAction, text): action = QAction(text, self) action.setCheckable(True) action.setData(filterAction) action.triggered.connect(self._filterActionSelected) self._filterActionGroup.addAction(action) return action
def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" # Initialize main button icon = QIcon(':/plugins/Geokoderen/icon.png') self.geokoderen_action = QAction( icon, self.tr(u'Aktiver knappen, tryk herefter i kortet for at åbne i Geokoderen.dk'), self.iface.mainWindow() ) self.geokoderen_action.triggered.connect(self.run) self.geokoderen_action.setEnabled(True) # add action to plugin menu self.iface.addPluginToMenu(self.menu, self.geokoderen_action) # Add button to toolbar self.iface.addToolBarIcon(self.geokoderen_action) # add to self.action for proper deletion self.actions.append(self.geokoderen_action) # Initialize about menu self.about_action = QAction( self.tr(u'Om pluginet'), self.iface.mainWindow() ) self.about_action.triggered.connect(self.open_about_dialog) self.about_action.setEnabled(True) # Add action to plugin menu self.iface.addPluginToMenu(self.menu, self.about_action) # add to self.action for proper deletion self.actions.append(self.about_action) self.pointtool.activated.connect(self.set_icon_active) self.pointtool.deactivated.connect(self.set_icon_inactive)
def add_toggle_action_to_menu(self, menu, caption, checked, call ): action = QAction(caption, menu) action.setCheckable(True) action.setChecked(checked) menu.addAction(action) action.toggled.connect(call) return action
def createActions(self, parent=None): self.engrave_sticky = QAction(parent) self.engrave_sticky.setCheckable(True) self.engrave_runner = QAction(parent) self.engrave_preview = QAction(parent) self.engrave_publish = QAction(parent) self.engrave_debug = QAction(parent) self.engrave_custom = QAction(parent) self.engrave_abort = QAction(parent) self.engrave_autocompile = QAction(parent) self.engrave_autocompile.setCheckable(True) self.engrave_show_available_fonts = QAction(parent) self.engrave_open_lilypond_datadir = QAction(parent) self.engrave_preview.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_M)) self.engrave_publish.setShortcut(QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_P)) self.engrave_custom.setShortcut(QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_M)) self.engrave_abort.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_Pause)) self.engrave_sticky.setIcon(icons.get('pushpin')) self.engrave_preview.setIcon(icons.get('lilypond-run')) self.engrave_publish.setIcon(icons.get('lilypond-run')) self.engrave_debug.setIcon(icons.get('lilypond-run')) self.engrave_custom.setIcon(icons.get('lilypond-run')) self.engrave_abort.setIcon(icons.get('process-stop'))
def setup_context_menu(self): self.menuFilter = QMenu(self) self.hide_action = QAction('Hide selected values', self) self.show_only_action = QAction('Show only selected values', self) self.clear_all_filters_action = QAction('Clear all filters', self) self.copy_selection_action = QAction('Copy selection', self) self.unhide_menu = QMenu('Unhide item from selected column', self.menuFilter) self.hide_action.triggered.connect(self.hide_rows_based_on_selected_cells) self.show_only_action.triggered.connect(self.show_rows_based_on_selected_cells) self.clear_all_filters_action.triggered.connect(self.clear_all_filters) self.copy_selection_action.triggered.connect(self.prepare_clipboard_text) self.menuFilter.addAction(self.hide_action) self.menuFilter.addMenu(self.unhide_menu) self.menuFilter.addAction(self.show_only_action) self.menuFilter.addAction(self.clear_all_filters_action) self.menuFilter.addSeparator() self.menuFilter.addAction(self.copy_selection_action) self.hide_action.setShortcut('Ctrl+H') self.show_only_action.setShortcut('Ctrl+O') self.clear_all_filters_action.setShortcut('Ctrl+Del') self.copy_selection_action.setShortcut("Ctrl+C")
def __init__(self, parent, path): self.pluginldr = parent QAction.__init__(self, parent) self.classname = os.path.basename(path)[:-3] self.modulename = os.path.dirname(path)[os.path.dirname(path).rfind('/') + 1:] self.path = path self.setObjectName("actionPlugin" + os.path.basename(path)[:-3]) self.setCheckable(True) self.setChecked(False) # import classname of plugin from __init__.py try: pluginmodule = __import__("plugins.%s" % self.modulename) module = getattr(pluginmodule, self.modulename) self.setText(module.PluginName) except ImportError: logging.error("No module named " + self.modulename + " found") raise except AttributeError: logging.error("Error finding name of plugin " + path + ". No PluginName function found") # if PluginName is not defined, name plugin like file self.setText(os.path.basename(path)) try: self.setIcon(QIcon(module.PluginIcon)) except AttributeError: pass # connect action to initPlugin() and deInitPlugin methods self.triggered.connect(self.__togglePlugin)
def initOptions(self): self.options = {} for o in ["Fit-to-window mode"]: action = QAction(o, self) action.setCheckable(True) self.ui.menuOptions.addAction(action) self.options[o] = action
def initGui(self): """startup""" # run run_icon = QIcon('%s/%s' % (self.context.ppath, 'images/MetaSearch.png')) self.action_run = QAction(run_icon, 'MetaSearch', self.iface.mainWindow()) self.action_run.setWhatsThis(QCoreApplication.translate('MetaSearch', 'MetaSearch plugin')) self.action_run.setStatusTip(QCoreApplication.translate('MetaSearch', 'Search Metadata Catalogues')) self.action_run.triggered.connect(self.run) self.iface.addToolBarIcon(self.action_run) self.iface.addPluginToWebMenu(self.web_menu, self.action_run) # help help_icon = QIcon('%s/%s' % (self.context.ppath, 'images/help.png')) self.action_help = QAction(help_icon, 'Help', self.iface.mainWindow()) self.action_help.setWhatsThis(QCoreApplication.translate('MetaSearch', 'MetaSearch plugin help')) self.action_help.setStatusTip(QCoreApplication.translate('MetaSearch', 'Get Help on MetaSearch')) self.action_help.triggered.connect(self.help) self.iface.addPluginToWebMenu(self.web_menu, self.action_help) # prefab the dialog but not open it yet self.dialog = MetaSearchDialog(self.iface)
def addDocument(self, doc): a = QAction(self) a.setCheckable(True) if doc is self.mainwindow().currentDocument(): a.setChecked(True) self._acts[doc] = a self.setDocumentStatus(doc)
def contextMenuEvent(self, event): def correctWord(cursor, word): # From QTextCursor doc: # if there is a selection, the selection is deleted and replaced return lambda: cursor.insertText(word) popup_menu = self.createStandardContextMenu() # Spellcheck the word under mouse cursor, not self.textCursor cursor = self.cursorForPosition(event.pos()) cursor.select(QTextCursor.WordUnderCursor) text = cursor.selectedText() if self.speller and text: if not self.speller.check(text): lastAction = popup_menu.actions()[0] for word in self.speller.suggest(text)[:10]: action = QAction(word, popup_menu) action.triggered.connect(correctWord(cursor, word)) action.setFont(QFont("sans", weight=QFont.Bold)) popup_menu.insertAction(lastAction, action) popup_menu.insertSeparator(lastAction) popup_menu.exec_(event.globalPos())
def initModeMenu(self): self.modeGroup = QActionGroup(self) self.modeGroup.setExclusive(True) self.modeGroup.selected.connect(self.parent.setMode) self.action_Squirrel = QAction(Icons.nut, 'Squ', self.modeGroup) self.action_Squirrel.setCheckable(True) self.action_Emo = QAction(Icons.emo, 'Emo', self.modeGroup) self.action_Emo.setCheckable(True) self.action_And = QAction(Icons.android, 'Android', self.modeGroup) self.action_And.setCheckable(True) self.action_Ios = QAction(Icons.ios, 'ios', self.modeGroup) self.action_Ios.setCheckable(True) self.modeGroup.addAction(self.action_Squirrel) self.modeGroup.addAction(self.action_Emo) self.modeGroup.addAction(self.action_And) self.modeGroup.addAction(self.action_Ios) self.addActions(self.modeGroup.actions()) if(config.mode() == 0): self.action_Squirrel.setChecked(True) self.action_Build.setEnabled(False) self.action_Run.setEnabled(False) elif(config.mode() == 1): self.action_Emo.setChecked(True) self.action_Build.setEnabled(True) self.action_Run.setEnabled(True) elif(config.mode() == 2): self.action_And.setChecked(True) self.action_Build.setEnabled(True) self.action_Run.setEnabled(True) elif(config.mode() == 3): self.action_Ios.setChecked(True) self.action_Build.setEnabled(False) self.action_Run.setEnabled(False)
def initGui(self): Processing.initialize() self.commander = None self.toolbox = ProcessingToolbox() self.iface.addDockWidget(Qt.RightDockWidgetArea, self.toolbox) self.toolbox.hide() Processing.addAlgListListener(self.toolbox) self.menu = QMenu(self.iface.mainWindow().menuBar()) self.menu.setObjectName('processing') self.menu.setTitle(self.tr('Pro&cessing')) self.toolboxAction = self.toolbox.toggleViewAction() self.toolboxAction.setObjectName('toolboxAction') self.toolboxAction.setIcon( QIcon(os.path.join(cmd_folder, 'images', 'alg.png'))) self.toolboxAction.setText(self.tr('&Toolbox')) self.menu.addAction(self.toolboxAction) self.modelerAction = QAction( QIcon(os.path.join(cmd_folder, 'images', 'model.png')), self.tr('Graphical &Modeler...'), self.iface.mainWindow()) self.modelerAction.setObjectName('modelerAction') self.modelerAction.triggered.connect(self.openModeler) self.menu.addAction(self.modelerAction) self.historyAction = QAction( QIcon(os.path.join(cmd_folder, 'images', 'history.gif')), self.tr('&History and Log...'), self.iface.mainWindow()) self.historyAction.setObjectName('historyAction') self.historyAction.triggered.connect(self.openHistory) self.menu.addAction(self.historyAction) self.configAction = QAction( QIcon(os.path.join(cmd_folder, 'images', 'config.png')), self.tr('&Options...'), self.iface.mainWindow()) self.configAction.setObjectName('configAction') self.configAction.triggered.connect(self.openConfig) self.menu.addAction(self.configAction) self.resultsAction = QAction( QIcon(os.path.join(cmd_folder, 'images', 'results.png')), self.tr('&Results Viewer...'), self.iface.mainWindow()) self.resultsAction.setObjectName('resultsAction') self.resultsAction.triggered.connect(self.openResults) self.menu.addAction(self.resultsAction) menuBar = self.iface.mainWindow().menuBar() menuBar.insertMenu( self.iface.firstRightStandardMenu().menuAction(), self.menu) self.commanderAction = QAction( QIcon(os.path.join(cmd_folder, 'images', 'commander.png')), self.tr('&Commander'), self.iface.mainWindow()) self.commanderAction.setObjectName('commanderAction') self.commanderAction.triggered.connect(self.openCommander) self.menu.addAction(self.commanderAction) self.iface.registerMainWindowAction(self.commanderAction, self.tr('Ctrl+Alt+M'))
def __init__(self, Ui_MainWindow, timeout=1000): super(FellesGui, self).__init__() self.setAttribute(Qt.WA_DeleteOnClose) exitAction = QAction('Quit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Quit application') print("Push 'Ctrl+Q' to quit the application") exitAction.triggered.connect(self.close) # Create Widget for the purpose of updating the widgets periodically #self.timer = QTimer() #self.timer.timeout.connect(self.paintEvent) #self.timer.start(timeout) # --> Instantiate UI !!! This is where the widgets are initiated !!! self.buildUi(Ui_MainWindow) # --> Setup the Menu Bar fileMenu = self.menuBar().addMenu('&File') fileMenu.addAction(exitAction) # --> Order widgets to connect to their slaves self.initialiseSlaves.emit() # --> Initialise "Threads" performing the sampling ports = QFellesWidgetBaseClass.___ports___.keys() self.sampling_threads = [ FellesThread(port) for port in ports ] #self.statusBar().showMessage.connect(FellesThread.sample_failed) self.statusBar().showMessage('Idling...')
def initGui(self): # Create action that will start plugin configuration self.copy_action = QAction( QIcon(':/plugins/geometrycopier/mActionEditCopyGeom.png'), self.tr(u"Copy geometry"), self.iface.mainWindow()) self.insert_action = QAction( QIcon(':/plugins/geometrycopier/mActionEditPasteGeom.png'), self.tr(u"Insert geometry"), self.iface.mainWindow()) # connect the action to the run method QObject.connect(self.copy_action, SIGNAL("triggered()"), self.copy_geometry) QObject.connect(self.insert_action, SIGNAL("triggered()"), self.insert_geometry) # Add hotkeys self.iface.registerMainWindowAction(self.copy_action, "F7") self.iface.registerMainWindowAction(self.insert_action, "F8") # Add toolbar button and menu item self.iface.digitizeToolBar().addAction(self.copy_action) self.iface.digitizeToolBar().addAction(self.insert_action) self.iface.addPluginToVectorMenu(u"&Geometry copier", self.copy_action) self.iface.addPluginToVectorMenu(u"&Geometry copier", self.insert_action) # Add global signals QObject.connect(self.iface, SIGNAL('currentLayerChanged(QgsMapLayer *)'), self.check_buttons_state) QObject.connect(self.iface.mapCanvas(), SIGNAL('selectionChanged(QgsMapLayer *)'), self.check_buttons_state) QObject.connect(self.iface.actionToggleEditing(), SIGNAL('triggered()'), self.check_buttons_state) #iface.actionToggleEditing().triggered # init state self.check_buttons_state(None)
def createActions(self, parent=None): self.lyrics_hyphenate = QAction(parent) self.lyrics_dehyphenate = QAction(parent) self.lyrics_copy_dehyphenated = QAction(parent) self.lyrics_hyphenate.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_L))
def initUi(self): openPixmap = QPixmap(os.path.dirname(os.path.realpath(__file__)) + '/Open.png') savePixmap = QPixmap(os.path.dirname(os.path.realpath(__file__)) + '/Save.png') openIcon = QIcon(openPixmap) saveIcon = QIcon(savePixmap) self.openToolButton = QToolButton(self.parent) self.saveToolButton = QToolButton(self.parent) self.openToolButton.setIcon(openIcon) self.saveToolButton.setIcon(saveIcon) self.openToolButton.setIconSize(QSize(32, 32)) self.saveToolButton.setIconSize(QSize(32, 32)) self.openToolButton.clicked.connect(self.openToolButtonClicked) self.saveToolButton.clicked.connect(self.saveToolButtonClicked) self.openAction = QAction("Open", self.parent) self.openAction.triggered.connect(self.openToolButtonClicked) self.saveAction = QAction("Save", self.parent) self.saveAction.triggered.connect(self.saveToolButtonClicked) menuCapture = self.parent.GetMenu("File") if menuCapture != None: menuCapture.addAction(self.openAction) menuCapture.addAction(self.saveAction) menuCapture.addSeparator() toolBarCapture = self.parent.GetToolBar("File") if toolBarCapture != None: toolBarCapture.addWidget(self.openToolButton) toolBarCapture.addWidget(self.saveToolButton)
def create_exampleActs(self): """ Create Actions to open example files """ exdir = None self.menuExamples.menuAction().setVisible(False) bpath = sys.path[0] + os.sep for p in ['../share/openscadpy/examples', '../../share/openscadpy/examples', '../../examples','../examples','examples']: exdir = bpath + p if os.access(exdir, os.R_OK ): break else: exdir = None if not exdir: return for e in sorted(os.listdir(exdir)): if e[-3:] == '.py': fname = exdir + os.sep + e a = QAction(self) QtCore.QObject.connect(a, QtCore.SIGNAL(_fromUtf8("triggered()")), self.on_open_menu_file) a.setText(e) a.setData(fname) self.menuExamples.addAction(a) self.menuExamples.menuAction().setVisible(True)
class CToolBar(QToolBar): def __init__(self, parent=None): super(CToolBar, self).__init__() self.setMovable(False) self.dir = QAction(self.style().standardIcon(QStyle.SP_DirHomeIcon), 'Change directory', self) self.dir.setShortcut('Ctrl+D') self.tab = QAction(self.style().standardIcon(QStyle.SP_ToolBarHorizontalExtensionButton), 'Add tab', self) self.tab.setShortcut('Ctrl+T') self.addAction(self.dir) self.addAction(self.tab) self.connect(self.dir, SIGNAL('triggered()'), self.addPath) self.connect(self.tab, SIGNAL('triggered()'), self.addTab) def addPath(self): dialog = AddPathDialog() dialog.exec() if dialog.lineEdit.text(): self.parent().centralWidget().files = listFiles(dialog.lineEdit.text()) self.parent().centralWidget().refreshTables() def addTab(self): dialog = AddTabDialog() dialog.exec() if dialog.lineEdit.text() and dialog.lineEdit_2.text(): self.parent().centralWidget().addTab(dialog.lineEdit.text(), ('Filename', 'Filesize', 'Path'), dialog.lineEdit_2.text())
def createActions(self, parent=None): self.scorewiz = QAction(parent) self.scorewiz.setIcon(icons.get("tools-score-wizard")) self.scorewiz.setShortcut(QKeySequence("Ctrl+Shift+N")) self.newwithwiz = QAction(parent) self.newwithwiz.setIcon(icons.get("tools-score-wizard")) self.scorewiz.setMenuRole(QAction.NoRole)
def captureLayer(self, layer): text = layer.icontext tool = layer.getMaptool(self.iface.mapCanvas()) # Hack until I fix it later if isinstance(tool, PointTool): add = functools.partial(self.addNewFeature, qgslayer) tool.geometryComplete.connect(add) else: tool.finished.connect(self.openForm) tool.error.connect(functools.partial(self.showToolError, text)) action = QAction(QIcon(layer.icon), text, self.mainwindow) action.setData(layer) action.setCheckable(True) action.toggled.connect(functools.partial(self.setMapTool, tool)) self.toolbar.insertAction(self.editingmodeaction, action) if not tool.isEditTool(): # Connect the GPS tools strip to the action pressed event. showgpstools = (functools.partial(self.extraaddtoolbar.showToolbar, action, None)) action.toggled.connect(showgpstools) self.actionGroup.addAction(action) self.actions.append(action)
def __init__(self, fileBrowser): QObject.__init__(self) self._fileBrowser = fileBrowser self._currDir = None self._currIsActive = False self._history = [] self._historyIndex = -1 fileBrowser.titleBarWidget().addSeparator() self._aBack = QAction( QIcon(':enkiicons/previous.png'), self.tr("Back"), self) self._aBack.setShortcut('Alt+Left') fileBrowser.titleBarWidget().addAction(self._aBack) core.actionManager().addAction("mNavigation/mFileBrowser/aBack", self._aBack) self._aBack.triggered.connect(self._onTbBackTriggered) self._aForward = QAction( QIcon(':enkiicons/next.png'), self.tr("Forward"), self) self._aForward.setShortcut('Alt+Right') fileBrowser.titleBarWidget().addAction(self._aForward) core.actionManager().addAction("mNavigation/mFileBrowser/aForward", self._aForward) self._aForward.triggered.connect(self._onTbForwardTriggered) fileBrowser.titleBarWidget().addSeparator() # incoming connections fileBrowser.rootChanged.connect(self._onRootChanged) fileBrowser.fileActivated.connect(self._onFileActivated)
def _create_actions(self): """ Create actions for basic image navigation. """ self._zoom_in_act = QAction(QApplication.translate("PhotoViewer","Zoom &In (25%)"), self) self._zoom_in_act.setShortcut(QApplication.translate("PhotoViewer","Ctrl++")) self._zoom_in_act.setEnabled(False) self._zoom_in_act.triggered.connect(self.zoom_in) self._zoom_out_act = QAction(QApplication.translate("PhotoViewer","Zoom &Out (25%)"), self) self._zoom_out_act.setShortcut(QApplication.translate("PhotoViewer","Ctrl+-")) self._zoom_out_act.setEnabled(False) self._zoom_out_act.triggered.connect(self.zoom_out) self._normal_size_act = QAction(QApplication.translate("PhotoViewer","&Normal Size"), self) self._normal_size_act.setShortcut(QApplication.translate("PhotoViewer","Ctrl+S")) self._normal_size_act.setEnabled(False) self._normal_size_act.triggered.connect(self.normal_size) self._fit_to_window_act = QAction(QApplication.translate("PhotoViewer","&Fit to Window"), self) self._fit_to_window_act.setShortcut(QApplication.translate("PhotoViewer","Ctrl+F")) self._fit_to_window_act.setEnabled(False) self._fit_to_window_act.setCheckable(True) self._fit_to_window_act.triggered.connect(self.fit_to_window) self._print_act = QAction(QApplication.translate("PhotoViewer","&Print"), self) self._print_act .setShortcut(QApplication.translate("PhotoViewer","Ctrl+P")) self._print_act .setEnabled(False) self._print_act .triggered.connect(self.print_photo)
class Plugin: def __init__(self): self.timer = QTimer(None) self.timer.setInterval(10000) self.timer.timeout.connect(self.Timeout) self.timer.setSingleShot(True) self.action = QAction("Preview mode", None) self.action.setCheckable(True) self.action.triggered.connect(self.Enabled) clementine.ui.AddAction("playlist_menu", self.action) clementine.player.Playing.connect(self.Playing) clementine.player.Paused.connect(self.Stopped) clementine.player.Stopped.connect(self.Stopped) self.enabled = False def Enabled(self, enabled): self.enabled = enabled if enabled: if clementine.player.GetState() == 2: # Playing self.timer.start() else: self.timer.stop() def Playing(self): if self.enabled: self.timer.start() def Stopped(self): self.timer.stop() def Timeout(self): if clementine.player.GetState() == 2: clementine.player.Next()
def init(): action = QAction("Open audio in Audacity", mw) action.setShortcut('Ctrl+Shift+A') action.setEnabled(True) mw.connect(action, SIGNAL('triggered()'), open_in_audacity) mw.form.menuTools.addAction(action)
def load(self): self.initTranslations() import vtk, VtkWidget, VtkWindow, Objects, Helpers self.vtk = vtk self.VtkWidget = VtkWidget self.VtkWindow = VtkWindow self.Objects = Objects self.Helpers = Helpers xpm = QPixmap() xpm.loadFromData(self.getFile('3dwin.xpm').read()) winIcon = QIcon(xpm) self.winManager = SubWinManager(glb.mainWin.workSpace, self.VtkWindow.VtkWindow, QCoreApplication.translate('VtkWindow', "Vtk Window"), winIcon) testAction = QAction(winIcon, QCoreApplication.translate('VtkWindow', '&VtkWindow Test'), glb.mainWin) testAction.setStatusTip(QCoreApplication.translate('VtkWindow', 'Show a new Vtk test window')) QWidget.connect(testAction, SIGNAL("triggered()"), self.test) glb.mainWin.plugInMenu.addAction(testAction) ftActions = glb.fileTypeActions ftActions.addType('application/x-3ds', '.3ds') ftActions.addAction(self.show3DS, ('application/x-3ds',), QCoreApplication.translate('VtkWindow', 'Open in VtkWindow'), 5) ftActions.addType('application/x-vrml', '.wrl') ftActions.addAction(self.showVRML, ('application/x-vrml',), QCoreApplication.translate('VtkWindow', 'Open in VtkWindow'), 5) return True
def _addDrawingAction(self, drawingAction, text): action = QAction(text, self) action.setCheckable(True) action.setData(drawingAction) action.triggered.connect(self._drawingActionSelected) self._drawingActionGroup.addAction(action) return action
def __init__(self, parent): RWidget.__init__(self, parent) self.parent = parent self.commandList = self.ListView(self) self.commandList.setToolTip("Right click item to view options") self.commandList.setWhatsThis("List of previous commands") self.copyAction = QAction("&Copy command(s)", self) self.copyAction.setStatusTip("Copy the selected command(s) to the clipboard") self.copyAction.setToolTip("Copy the selected command(s) to the clipboard") self.copyAction.setIcon(QIcon(":edit-copy")) self.copyAction.setEnabled(False) self.selectAction = QAction("Select &all", self) self.selectAction.setStatusTip("Select all commands") self.selectAction.setToolTip("Select all commands") self.selectAction.setIcon(QIcon(":edit-select-all")) self.runAction = QAction("&Run command(s)", self) self.runAction.setStatusTip("Run the selected command(s) in the console") self.runAction.setToolTip("Run the selected command(s) in the console") self.runAction.setIcon(QIcon(":utilities-terminal")) self.runAction.setEnabled(False) vbox = QVBoxLayout(self) vbox.addWidget(self.commandList) self.connect(self.copyAction, SIGNAL("triggered()"), self.copy) #self.connect(self.insertAction, SIGNAL("triggered()"), self.insert) self.connect(self.runAction, SIGNAL("triggered()"), self.run) #self.connect(self.clearAction, SIGNAL("triggered()"), self.clear) self.connect(self.selectAction, SIGNAL("triggered()"), self.selectAll) self.connect(self.commandList, SIGNAL("doubleClicked(QModelIndex)"), self.doubleClicked) self.connect(self.commandList, SIGNAL("selectionChanged()"), self.selectionChanged)
else: original_next_card(self) def next_card_toggle_off(): """Switch the next card action off.""" toggle_last_card_action.setChecked(False) # Make all the actions top level, so we can use them for the menu and # the tool bar. # Most of the icons are part of the standard version, but as they are # not currently used by the standard version, they may disappear when # dae gets around to doing some clean up. So bring them along, anyway. sync_action = QAction(mw) sync_action.setText(_(u"S&ync")) sync_action.setIcon(QIcon(os.path.join(icons_dir, 'sync.png'))) sync_action.setToolTip(_(u"Synchronize with AnkiWeb.")) mw.connect(sync_action, SIGNAL("triggered()"), mw.onSync) decks_action = QAction(mw) decks_action.setText(_(u"&Deck browser")) decks_action.setIcon(QIcon(os.path.join(icons_dir, 'deck_browser.png'))) decks_action.setToolTip(_(u"Go to the deck browser.")) mw.connect(decks_action, SIGNAL("triggered()"), go_deck_browse) overview_action = QAction(mw) overview_action.setText(_(u"Deck overview")) overview_action.setIcon(QIcon(os.path.join(icons_dir, 'study_options.png'))) overview_action.setToolTip(_(u"Go to the deck overview.")) mw.connect(overview_action, SIGNAL("triggered()"), mw.onOverview) study_action = QAction(mw)
def registerDatabaseActions(self, mainWindow): action = QAction( QApplication.translate("DBManagerPlugin", "&Re-connect"), self) mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Database"), self.reconnectActionSlot) if self.schemas() is not None: action = QAction( QApplication.translate("DBManagerPlugin", "&Create schema"), self) mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Schema"), self.createSchemaActionSlot) action = QAction( QApplication.translate("DBManagerPlugin", "&Delete (empty) schema"), self) mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Schema"), self.deleteSchemaActionSlot) action = QAction( QApplication.translate("DBManagerPlugin", "Delete selected item"), self) mainWindow.registerAction(action, None, self.deleteActionSlot) action.setShortcuts(QKeySequence.Delete) action = QAction( QIcon(":/db_manager/actions/create_table"), QApplication.translate("DBManagerPlugin", "&Create table"), self) mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Table"), self.createTableActionSlot) action = QAction( QIcon(":/db_manager/actions/edit_table"), QApplication.translate("DBManagerPlugin", "&Edit table"), self) mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Table"), self.editTableActionSlot) action = QAction( QIcon(":/db_manager/actions/del_table"), QApplication.translate("DBManagerPlugin", "&Delete table/view"), self) mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Table"), self.deleteTableActionSlot) action = QAction( QApplication.translate("DBManagerPlugin", "&Empty table"), self) mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Table"), self.emptyTableActionSlot) if self.schemas() is not None: action = QAction( QApplication.translate("DBManagerPlugin", "&Move to schema"), self) action.setMenu(QMenu(mainWindow)) invoke_callback = lambda: mainWindow.invokeCallback( self.prepareMenuMoveTableToSchemaActionSlot) QObject.connect(action.menu(), SIGNAL("aboutToShow()"), invoke_callback) mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Table"))
def createActions(self, parent=None): self.engrave_sticky = QAction(parent) self.engrave_sticky.setCheckable(True) self.engrave_runner = QAction(parent) self.engrave_preview = QAction(parent) self.engrave_publish = QAction(parent) self.engrave_debug = QAction(parent) self.engrave_custom = QAction(parent) self.engrave_abort = QAction(parent) self.engrave_autocompile = QAction(parent) self.engrave_autocompile.setCheckable(True) self.engrave_show_available_fonts = QAction(parent) self.engrave_open_lilypond_datadir = QAction(parent) self.engrave_preview.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_M)) self.engrave_publish.setShortcut( QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_P)) self.engrave_custom.setShortcut( QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_M)) self.engrave_abort.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_Pause)) self.engrave_sticky.setIcon(icons.get('pushpin')) self.engrave_preview.setIcon(icons.get('lilypond-run')) self.engrave_publish.setIcon(icons.get('lilypond-run')) self.engrave_debug.setIcon(icons.get('lilypond-run')) self.engrave_custom.setIcon(icons.get('lilypond-run')) self.engrave_abort.setIcon(icons.get('process-stop'))
class Actions(actioncollection.ActionCollection): name = "engrave" def createActions(self, parent=None): self.engrave_sticky = QAction(parent) self.engrave_sticky.setCheckable(True) self.engrave_runner = QAction(parent) self.engrave_preview = QAction(parent) self.engrave_publish = QAction(parent) self.engrave_debug = QAction(parent) self.engrave_custom = QAction(parent) self.engrave_abort = QAction(parent) self.engrave_autocompile = QAction(parent) self.engrave_autocompile.setCheckable(True) self.engrave_show_available_fonts = QAction(parent) self.engrave_open_lilypond_datadir = QAction(parent) self.engrave_preview.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_M)) self.engrave_publish.setShortcut( QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_P)) self.engrave_custom.setShortcut( QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_M)) self.engrave_abort.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_Pause)) self.engrave_sticky.setIcon(icons.get('pushpin')) self.engrave_preview.setIcon(icons.get('lilypond-run')) self.engrave_publish.setIcon(icons.get('lilypond-run')) self.engrave_debug.setIcon(icons.get('lilypond-run')) self.engrave_custom.setIcon(icons.get('lilypond-run')) self.engrave_abort.setIcon(icons.get('process-stop')) def translateUI(self): self.engrave_runner.setText(_("Engrave")) self.engrave_runner.setToolTip( _("Engrave (preview; Shift-click for custom)")) self.engrave_preview.setText(_("&Engrave (preview)")) self.engrave_publish.setText(_("Engrave (&publish)")) self.engrave_debug.setText(_("Engrave (&layout control)")) self.engrave_custom.setText(_("Engrave (&custom)...")) self.engrave_abort.setText(_("Abort Engraving &Job")) self.engrave_autocompile.setText(_("Automatic E&ngrave")) self.engrave_open_lilypond_datadir.setText( _("Open LilyPond &Data Directory")) self.engrave_show_available_fonts.setText( _("Show Available &Fonts..."))
def add_action(self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToVectorMenu(self.menu, action) self.actions.append(action) return action
def createActions(self): # 新建 self.newAction = QAction(str("&New"), self) self.newAction.setIcon(QIcon(":/images/new.png")) self.newAction.setShortcut(QKeySequence.New) self.newAction.setStatusTip(str("Create a new spreadsheet file")) self.connect(self.newAction, SIGNAL("triggered()"), self, SLOT("newFile()")) # 打开 self.openAction = QAction(str("&Open..."), self) self.openAction.setIcon(QIcon(":/images/open.png")) self.openAction.setShortcut(QKeySequence.Open) self.openAction.setStatusTip(str("Open an existing spreadsheet file")) self.connect(self.openAction, SIGNAL("triggered()"), self, SLOT("open()")) # 保存 self.saveAction = QAction(str("&Save"), self) self.saveAction.setIcon(QIcon(":/images/save.png")) self.saveAction.setShortcut(QKeySequence.Save) self.saveAction.setStatusTip(str("Save the spreadsheet to disk")) self.connect(self.saveAction, SIGNAL("triggered()"), self, SLOT("save()")) # 另存为 self.saveAsAction = QAction(str("Save &As..."), self) self.saveAsAction.setStatusTip( str("Save the spreadsheet under a name")) self.connect(self.saveAsAction, SIGNAL("triggered()"), self, SLOT("saveAs()")) for i in range(self.MaxRecentFiles): self.recentFileActions[i] = QAction(self) self.recentFileActions[i].setVisible(False) self.connect(self.recentFileActions[i], SIGNAL("triggered()"), self, SLOT("openRecentFile()")) # 退出 self.exitAction = QAction(str("E&xit"), self) self.exitAction.setShortcut(str("Ctrl+Q")) self.exitAction.setStatusTip(str("Exit the application")) self.connect(self.exitAction, SIGNAL("triggered()"), self, SLOT("close()")) # ------------- # 剪切 self.cutAction = QAction(str("Cu&t"), self) self.cutAction.setIcon(QIcon(":/images/cut.png")) self.cutAction.setShortcut(QKeySequence.Cut) self.cutAction.setStatusTip( str("Cut the current selection's contents " "to the clipboard")) self.connect(self.cutAction, SIGNAL("triggered()"), self.spreadsheet, SLOT("cut()")) # 拷贝 self.copyAction = QAction(str("&Copy"), self) self.copyAction.setIcon(QIcon(":/images/copy.png")) self.copyAction.setShortcut(QKeySequence.Copy) self.copyAction.setStatusTip( str("Copy the current selection's contents " "to the clipboard")) self.connect(self.copyAction, SIGNAL("triggered()"), self.spreadsheet, SLOT("copy()")) # 黏贴 self.pasteAction = QAction(str("&Paste"), self) self.pasteAction.setIcon(QIcon(":/images/paste.png")) self.pasteAction.setShortcut(QKeySequence.Paste) self.pasteAction.setStatusTip( str("Paste the clipboard's contents into " "the current selection")) self.connect(self.pasteAction, SIGNAL("triggered()"), self.spreadsheet, SLOT("paste()")) self.deleteAction = QAction(str("&Delete"), self) self.deleteAction.setShortcut(QKeySequence.Delete) self.deleteAction.setStatusTip( str("Delete the current selection's " "contents")) # self.connect(self.deleteAction, SIGNAL("triggered()"), # self.spreadsheet, SLOT(del())) self.selectRowAction = QAction(str("&Row"), self) self.selectRowAction.setStatusTip( str("Select all the cells in the " "current row")) self.connect(self.selectRowAction, SIGNAL("triggered()"), self.spreadsheet, SLOT("selectCurrentRow()")) self.selectColumnAction = QAction(str("&Column"), self) self.selectColumnAction.setStatusTip( str("Select all the cells in the " "current column")) self.connect(self.selectColumnAction, SIGNAL("triggered()"), self.spreadsheet, SLOT("selectCurrentColumn()")) self.selectAllAction = QAction(str("&All"), self) self.selectAllAction.setShortcut(QKeySequence.SelectAll) self.selectAllAction.setStatusTip( str("Select all the cells in the " "spreadsheet")) self.connect(self.selectAllAction, SIGNAL("triggered()"), self.spreadsheet, SLOT("selectAll()")) self.findAction = QAction(str("&Find..."), self) self.findAction.setIcon(QIcon(":/images/find.png")) self.findAction.setShortcut(QKeySequence.Find) self.findAction.setStatusTip(str("Find a matching cell")) self.connect(self.findAction, SIGNAL("triggered()"), self, SLOT("find()")) self.goToCellAction = QAction(str("&Go to Cell..."), self) self.goToCellAction.setIcon(QIcon(":/images/gotocell.png")) self.goToCellAction.setShortcut(str("Ctrl+G")) self.goToCellAction.setStatusTip(str("Go to the specified cell")) self.connect(self.goToCellAction, SIGNAL("triggered()"), self, SLOT("goToCell()")) self.recalculateAction = QAction(str("&Recalculate"), self) self.recalculateAction.setShortcut(str("F9")) self.recalculateAction.setStatusTip( str("Recalculate all the " "spreadsheet's formulas")) self.connect(self.recalculateAction, SIGNAL("triggered()"), self.spreadsheet, SLOT("recalculate()")) self.sortAction = QAction(str("&Sort..."), self) self.sortAction.setStatusTip( str("Sort the selected cells or all the " "cells")) self.connect(self.sortAction, SIGNAL("triggered()"), self, SLOT("sort()")) self.showGridAction = QAction(str("&Show Grid"), self) self.showGridAction.setCheckable(True) self.showGridAction.setChecked(self.spreadsheet.showGrid()) self.showGridAction.setStatusTip( str("Show or hide the spreadsheet's " "grid")) self.connect(self.showGridAction, SIGNAL("toggled(bool)"), self.spreadsheet, SLOT("setShowGrid(bool)")) self.autoRecalcAction = QAction(str("&Auto-Recalculate"), self) self.autoRecalcAction.setCheckable(True) # self.autoRecalcAction.setChecked(self.spreadsheet.autoRecalculate()) self.autoRecalcAction.setStatusTip( str("Switch auto-recalculation on or " "off")) # self.connect(self.autoRecalcAction, SIGNAL("toggled(bool)"),\ # self.spreadsheet, SLOT("setAutoRecalculate(bool)")) self.aboutAction = QAction(str("&About"), self) self.aboutAction.setStatusTip(str("Show the application's About box")) self.connect(self.aboutAction, SIGNAL("triggered()"), self, SLOT("about()")) self.aboutQtAction = QAction(str("About &Qt"), self) self.aboutQtAction.setStatusTip(str("Show the Qt library's About box"))
class MainWindow(QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setWindowIcon(QIcon(":/images/icon.png")) self.setCurrentFile("") # ----------- 数据 ------------- self.spreadsheet = Spreadsheet() self.setCentralWidget(self.spreadsheet) self.findDialog = None self.locationLabel = None self.formulaLabel = None self.recentFiles = None # QStringList recentFiles; self.curFile = None # QString curFile; self.MaxRecentFiles = 5 self.recentFileActions = [None] * self.MaxRecentFiles # self.separatorAction = None # # self.fileMenu = None self.editMenu = None self.selectSubMenu = None self.toolsMenu = None self.optionsMenu = None self.helpMenu = None self.fileToolBar = None self.editToolBar = None self.newAction = None self.openAction = None self.saveAction = None self.saveAsAction = None self.exitAction = None self.cutAction = None self.copyAction = None self.pasteAction = None self.deleteAction = None self.selectRowAction = None self.selectColumnAction = None self.selectAllAction = None self.findAction = None self.goToCellAction = None self.recalculateAction = None self.sortAction = None self.showGridAction = None self.autoRecalcAction = None self.aboutAction = None self.aboutQtAction = None # self.qApp = QApplication([]) # 这样写 有问题 self.createActions() self.createMenus() self.createContextMenu() self.createToolBars() self.createStatusBar() # self.readSettings() # def closeEvent(self, event): # if (self.okToContinue()): # self.writeSettings() # event.accept() # else: # event.ignore() @pyqtSlot() def newFile(self): if (self.okToContinue()): pass # spreadsheet.clear() # setCurrentFile("") @pyqtSlot() def open(self): pass @pyqtSlot() def save(self): pass @pyqtSlot() def saveAs(self): pass @pyqtSlot() def find(self): pass @pyqtSlot() def goToCell(self): pass @pyqtSlot() def sort(self): pass # 关于 @pyqtSlot() def about(self): QMessageBox.about( self, str("About Spreadsheet"), str("<h2>Spreadsheet 1.1</h2>" "<p>Copyright © 2008 Software Inc." "<p>Spreadsheet is a small application that " "demonstrates QAction, QMainWindow, QMenuBar, " "QStatusBar, QTableWidget, QToolBar, and many other " "Qt classes.")) @pyqtSlot() def openRecentFile(self): pass @pyqtSlot() def updateStatusBar(self): pass def spreadsheetModified(self): pass # 创建 Actions def createActions(self): # 新建 self.newAction = QAction(str("&New"), self) self.newAction.setIcon(QIcon(":/images/new.png")) self.newAction.setShortcut(QKeySequence.New) self.newAction.setStatusTip(str("Create a new spreadsheet file")) self.connect(self.newAction, SIGNAL("triggered()"), self, SLOT("newFile()")) # 打开 self.openAction = QAction(str("&Open..."), self) self.openAction.setIcon(QIcon(":/images/open.png")) self.openAction.setShortcut(QKeySequence.Open) self.openAction.setStatusTip(str("Open an existing spreadsheet file")) self.connect(self.openAction, SIGNAL("triggered()"), self, SLOT("open()")) # 保存 self.saveAction = QAction(str("&Save"), self) self.saveAction.setIcon(QIcon(":/images/save.png")) self.saveAction.setShortcut(QKeySequence.Save) self.saveAction.setStatusTip(str("Save the spreadsheet to disk")) self.connect(self.saveAction, SIGNAL("triggered()"), self, SLOT("save()")) # 另存为 self.saveAsAction = QAction(str("Save &As..."), self) self.saveAsAction.setStatusTip( str("Save the spreadsheet under a name")) self.connect(self.saveAsAction, SIGNAL("triggered()"), self, SLOT("saveAs()")) for i in range(self.MaxRecentFiles): self.recentFileActions[i] = QAction(self) self.recentFileActions[i].setVisible(False) self.connect(self.recentFileActions[i], SIGNAL("triggered()"), self, SLOT("openRecentFile()")) # 退出 self.exitAction = QAction(str("E&xit"), self) self.exitAction.setShortcut(str("Ctrl+Q")) self.exitAction.setStatusTip(str("Exit the application")) self.connect(self.exitAction, SIGNAL("triggered()"), self, SLOT("close()")) # ------------- # 剪切 self.cutAction = QAction(str("Cu&t"), self) self.cutAction.setIcon(QIcon(":/images/cut.png")) self.cutAction.setShortcut(QKeySequence.Cut) self.cutAction.setStatusTip( str("Cut the current selection's contents " "to the clipboard")) self.connect(self.cutAction, SIGNAL("triggered()"), self.spreadsheet, SLOT("cut()")) # 拷贝 self.copyAction = QAction(str("&Copy"), self) self.copyAction.setIcon(QIcon(":/images/copy.png")) self.copyAction.setShortcut(QKeySequence.Copy) self.copyAction.setStatusTip( str("Copy the current selection's contents " "to the clipboard")) self.connect(self.copyAction, SIGNAL("triggered()"), self.spreadsheet, SLOT("copy()")) # 黏贴 self.pasteAction = QAction(str("&Paste"), self) self.pasteAction.setIcon(QIcon(":/images/paste.png")) self.pasteAction.setShortcut(QKeySequence.Paste) self.pasteAction.setStatusTip( str("Paste the clipboard's contents into " "the current selection")) self.connect(self.pasteAction, SIGNAL("triggered()"), self.spreadsheet, SLOT("paste()")) self.deleteAction = QAction(str("&Delete"), self) self.deleteAction.setShortcut(QKeySequence.Delete) self.deleteAction.setStatusTip( str("Delete the current selection's " "contents")) # self.connect(self.deleteAction, SIGNAL("triggered()"), # self.spreadsheet, SLOT(del())) self.selectRowAction = QAction(str("&Row"), self) self.selectRowAction.setStatusTip( str("Select all the cells in the " "current row")) self.connect(self.selectRowAction, SIGNAL("triggered()"), self.spreadsheet, SLOT("selectCurrentRow()")) self.selectColumnAction = QAction(str("&Column"), self) self.selectColumnAction.setStatusTip( str("Select all the cells in the " "current column")) self.connect(self.selectColumnAction, SIGNAL("triggered()"), self.spreadsheet, SLOT("selectCurrentColumn()")) self.selectAllAction = QAction(str("&All"), self) self.selectAllAction.setShortcut(QKeySequence.SelectAll) self.selectAllAction.setStatusTip( str("Select all the cells in the " "spreadsheet")) self.connect(self.selectAllAction, SIGNAL("triggered()"), self.spreadsheet, SLOT("selectAll()")) self.findAction = QAction(str("&Find..."), self) self.findAction.setIcon(QIcon(":/images/find.png")) self.findAction.setShortcut(QKeySequence.Find) self.findAction.setStatusTip(str("Find a matching cell")) self.connect(self.findAction, SIGNAL("triggered()"), self, SLOT("find()")) self.goToCellAction = QAction(str("&Go to Cell..."), self) self.goToCellAction.setIcon(QIcon(":/images/gotocell.png")) self.goToCellAction.setShortcut(str("Ctrl+G")) self.goToCellAction.setStatusTip(str("Go to the specified cell")) self.connect(self.goToCellAction, SIGNAL("triggered()"), self, SLOT("goToCell()")) self.recalculateAction = QAction(str("&Recalculate"), self) self.recalculateAction.setShortcut(str("F9")) self.recalculateAction.setStatusTip( str("Recalculate all the " "spreadsheet's formulas")) self.connect(self.recalculateAction, SIGNAL("triggered()"), self.spreadsheet, SLOT("recalculate()")) self.sortAction = QAction(str("&Sort..."), self) self.sortAction.setStatusTip( str("Sort the selected cells or all the " "cells")) self.connect(self.sortAction, SIGNAL("triggered()"), self, SLOT("sort()")) self.showGridAction = QAction(str("&Show Grid"), self) self.showGridAction.setCheckable(True) self.showGridAction.setChecked(self.spreadsheet.showGrid()) self.showGridAction.setStatusTip( str("Show or hide the spreadsheet's " "grid")) self.connect(self.showGridAction, SIGNAL("toggled(bool)"), self.spreadsheet, SLOT("setShowGrid(bool)")) self.autoRecalcAction = QAction(str("&Auto-Recalculate"), self) self.autoRecalcAction.setCheckable(True) # self.autoRecalcAction.setChecked(self.spreadsheet.autoRecalculate()) self.autoRecalcAction.setStatusTip( str("Switch auto-recalculation on or " "off")) # self.connect(self.autoRecalcAction, SIGNAL("toggled(bool)"),\ # self.spreadsheet, SLOT("setAutoRecalculate(bool)")) self.aboutAction = QAction(str("&About"), self) self.aboutAction.setStatusTip(str("Show the application's About box")) self.connect(self.aboutAction, SIGNAL("triggered()"), self, SLOT("about()")) self.aboutQtAction = QAction(str("About &Qt"), self) self.aboutQtAction.setStatusTip(str("Show the Qt library's About box")) # self.connect(self.aboutQtAction, SIGNAL("triggered()"), self.qApp, SLOT("aboutQt()")) # 创建 菜单栏 def createMenus(self): self.fileMenu = self.menuBar().addMenu(str("&File")) self.fileMenu.addAction(self.newAction) self.fileMenu.addAction(self.openAction) self.fileMenu.addAction(self.saveAction) self.fileMenu.addAction(self.saveAsAction) self.separatorAction = self.fileMenu.addSeparator() for i in range(self.MaxRecentFiles): self.fileMenu.addAction(self.recentFileActions[i]) self.fileMenu.addSeparator() self.fileMenu.addAction(self.exitAction) self.editMenu = self.menuBar().addMenu(str("&Edit")) self.editMenu.addAction(self.cutAction) self.editMenu.addAction(self.copyAction) self.editMenu.addAction(self.pasteAction) self.editMenu.addAction(self.deleteAction) self.selectSubMenu = self.editMenu.addMenu(str("&Select")) self.selectSubMenu.addAction(self.selectRowAction) self.selectSubMenu.addAction(self.selectColumnAction) self.selectSubMenu.addAction(self.selectAllAction) self.editMenu.addSeparator() self.editMenu.addAction(self.findAction) self.editMenu.addAction(self.goToCellAction) self.toolsMenu = self.menuBar().addMenu(str("&Tools")) self.toolsMenu.addAction(self.recalculateAction) self.toolsMenu.addAction(self.sortAction) self.optionsMenu = self.menuBar().addMenu(str("&Options")) self.optionsMenu.addAction(self.showGridAction) self.optionsMenu.addAction(self.autoRecalcAction) self.menuBar().addSeparator() helpMenu = self.menuBar().addMenu(str("&Help")) helpMenu.addAction(self.aboutAction) helpMenu.addAction(self.aboutQtAction) # 添加 上下文菜单,右键快捷菜单 def createContextMenu(self): pass self.spreadsheet.addAction(self.cutAction) self.spreadsheet.addAction(self.copyAction) self.spreadsheet.addAction(self.pasteAction) self.spreadsheet.setContextMenuPolicy(Qt.ActionsContextMenu) def createToolBars(self): pass def createStatusBar(self): pass def readSettings(self): pass def writeSettings(self): pass def okToContinue(self): pass # def loadFile(const QString &fileName) def loadFile(self, fileName): pass # def saveFile(const QString &fileName) def saveFile(self, fileName): pass # def setCurrentFile(const QString &fileName) def setCurrentFile(self, fileName): pass def updateRecentFileActions(self): pass # def strippedName(const QString &fullFileName) def strippedName(self, fullFileName): pass
def createAction(parent: QObject, text: str, icon: object = None, shortcut: str = None, tooltip: str = None, enabled: bool = False, signal: str = "triggered", slot: object = None) -> object: action = QAction(parent) action.setText(text) if icon: action.setIcon( QIcon(icon)) # icon is expected as a string argument if shortcut: action.setShortcut(shortcut) if tooltip: action.setToolTip(tooltip) if enabled: action.setEnabled(enabled) if slot and signal == "triggered": action.pyqtConfigure(triggered=slot) return action
def initializeOperationActions(self): self.showAllAction = QAction( KIcon(("applications-other", "package_applications")), i18n("All Packages"), self) self.connect(self.showAllAction, SIGNAL("triggered()"), lambda: self.cw.switchState(StateManager.ALL)) self.cw.stateTab.addTab( QWidget(), KIcon(("applications-other", "package_applications")), i18n("All Packages")) self.showInstallAction = QAction(KIcon(("list-add", "add")), i18n("Installable Packages"), self) self.connect(self.showInstallAction, SIGNAL("triggered()"), lambda: self.cw.switchState(StateManager.INSTALL)) self.cw.stateTab.addTab(QWidget(), KIcon(("list-add", "add")), i18n("Installable Packages")) self.showRemoveAction = QAction(KIcon(("list-remove", "remove")), i18n("Installed Packages"), self) self.connect(self.showRemoveAction, SIGNAL("triggered()"), lambda: self.cw.switchState(StateManager.REMOVE)) self.cw.stateTab.addTab(QWidget(), KIcon(("list-remove", "remove")), i18n("Installed Packages")) self.showUpgradeAction = QAction( KIcon(("system-software-update", "gear")), i18n("Updates"), self) self.connect(self.showUpgradeAction, SIGNAL("triggered()"), lambda: self.cw.switchState(StateManager.UPGRADE)) self.cw.stateTab.addTab(QWidget(), KIcon(("system-software-update", "gear")), i18n("Updates")) self.showPreferences = QAction( KIcon(("preferences-system", "package_settings")), i18n("Settings"), self) self.connect(self.showPreferences, SIGNAL("triggered()"), self.settingsDialog.show) self.actionQuit = QAction(KIcon("exit"), i18n("Quit"), self) self.actionQuit.setShortcuts(QKeySequence.Quit) self.connect(self.actionQuit, SIGNAL("triggered()"), qApp.exit) self.cw.menuButton.setMenu(QMenu('MainMenu', self.cw.menuButton)) self.cw.menuButton.setIcon( KIcon(("preferences-system", "package_settings"))) self.cw.menuButton.menu().clear() self.cw.contentHistory.hide() self.cw.menuButton.menu().addAction(self.showPreferences) self.cw.menuButton.menu().addSeparator() self.cw.menuButton.menu().addAction(self.actionQuit) self.cw._states = { self.cw.state.ALL: (0, self.showAllAction), self.cw.state.INSTALL: (1, self.showInstallAction), self.cw.state.REMOVE: (2, self.showRemoveAction), self.cw.state.UPGRADE: (3, self.showUpgradeAction) } self.showAllAction.setChecked(True) self.cw.checkUpdatesButton.hide() self.cw.checkUpdatesButton.setIcon(KIcon(("view-refresh", "reload"))) self.cw.showBasketButton.clicked.connect(self.cw.showBasket) # Little time left for the new ui self.menuBar().setVisible(False) self.cw.switchState(self.cw.state.ALL)
def act(slot, icon=None): a = QAction(self, triggered=slot) self.addAction(a) icon and a.setIcon(icons.get(icon)) return a
def createActions(self, parent): self.edit_cut_assign = QAction(parent) self.view_highlighting = QAction(parent) self.view_highlighting.setCheckable(True) self.view_goto_file_or_definition = QAction(parent) self.tools_indent_auto = QAction(parent) self.tools_indent_auto.setCheckable(True) self.tools_indent_indent = QAction(parent) self.tools_reformat = QAction(parent) self.tools_remove_trailing_whitespace = QAction(parent) self.tools_convert_ly = QAction(parent) self.tools_quick_remove_articulations = QAction(parent) self.tools_quick_remove_ornaments = QAction(parent) self.tools_quick_remove_instrument_scripts = QAction(parent) self.tools_quick_remove_slurs = QAction(parent) self.tools_quick_remove_dynamics = QAction(parent) self.tools_quick_remove_markup = QAction(parent) self.edit_cut_assign.setIcon(icons.get('edit-cut')) self.view_goto_file_or_definition.setShortcut( QKeySequence(Qt.ALT + Qt.Key_Return)) self.edit_cut_assign.setShortcut( QKeySequence(Qt.SHIFT + Qt.CTRL + Qt.Key_X))
class MainWindow(QMainWindow, Ui_MainWindow): def __init__(self, app=None): QMainWindow.__init__(self, None) self.setupUi(self) self.app = app self.iface = backend.pm.Iface() self.busy = QProgressIndicator(self) self.busy.setFixedSize(QSize(20, 20)) self.setWindowIcon(QIcon(":/data/package-manager.png")) self.setCentralWidget(MainWidget(self)) self.cw = self.centralWidget() self.settingsDialog = SettingsDialog(self) self.initializeActions() self.initializeStatusBar() self.initializeTray() self.connectMainSignals() self.pdsMessageBox = PMessageBox(self) def connectMainSignals(self): self.cw.connectMainSignals() self.connect(QShortcut(QKeySequence(Qt.CTRL + Qt.Key_Tab), self), SIGNAL("activated()"), lambda: self.moveTab('next')) self.connect( QShortcut(QKeySequence(Qt.SHIFT + Qt.CTRL + Qt.Key_Tab), self), SIGNAL("activated()"), lambda: self.moveTab('prev')) self.connect(QShortcut(QKeySequence(Qt.CTRL + Qt.Key_F), self), SIGNAL("activated()"), self.cw.searchLine.setFocus) self.connect(QShortcut(QKeySequence(Qt.Key_F3), self), SIGNAL("activated()"), self.cw.searchLine.setFocus) self.connect(self.settingsDialog, SIGNAL("packagesChanged()"), self.cw.initialize) self.connect(self.settingsDialog, SIGNAL("packageViewChanged()"), self.cw.updateSettings) self.connect(self.settingsDialog, SIGNAL("traySettingChanged()"), self.tray.settingsChanged) self.connect(self.cw.state, SIGNAL("repositoriesChanged()"), self.tray.populateRepositoryMenu) self.connect(self.cw, SIGNAL("repositoriesUpdated()"), self.tray.updateTrayUnread) self.connect(qApp, SIGNAL("shutDown()"), self.slotQuit) def moveTab(self, direction): new_index = self.cw.stateTab.currentIndex() - 1 if direction == 'next': new_index = self.cw.stateTab.currentIndex() + 1 if new_index not in range(self.cw.stateTab.count()): new_index = 0 self.cw.stateTab.setCurrentIndex(new_index) def initializeTray(self): self.tray = Tray(self, self.iface) self.connect(self.cw.operation, SIGNAL("finished(QString)"), self.trayAction) self.connect(self.cw.operation, SIGNAL("finished(QString)"), self.tray.stop) self.connect(self.cw.operation, SIGNAL("operationCancelled()"), self.tray.stop) self.connect(self.cw.operation, SIGNAL("started(QString)"), self.tray.animate) self.connect(self.tray, SIGNAL("showUpdatesSelected()"), self.trayShowUpdates) def trayShowUpdates(self): self.showUpgradeAction.setChecked(True) self.cw.switchState(StateManager.UPGRADE) KApplication.kApplication().updateUserTimestamp() self.show() self.raise_() def trayAction(self, operation): if not self.isVisible() and operation in [ "System.Manager.updateRepository", "System.Manager.updateAllRepositories" ]: self.tray.showPopup() if self.tray.isVisible() and operation in [ "System.Manager.updatePackage", "System.Manager.installPackage", "System.Manager.removePackage" ]: self.tray.updateTrayUnread() def initializeStatusBar(self): self.cw.mainLayout.insertWidget(0, self.busy) self.statusBar().addPermanentWidget(self.cw.actions, 1) self.statusBar().show() self.updateStatusBar('') self.connect(self.cw, SIGNAL("selectionStatusChanged(QString)"), self.updateStatusBar) self.connect(self.cw, SIGNAL("updatingStatus()"), self.statusWaiting) def initializeActions(self): self.initializeOperationActions() def initializeOperationActions(self): self.showAllAction = QAction( KIcon(("applications-other", "package_applications")), i18n("All Packages"), self) self.connect(self.showAllAction, SIGNAL("triggered()"), lambda: self.cw.switchState(StateManager.ALL)) self.cw.stateTab.addTab( QWidget(), KIcon(("applications-other", "package_applications")), i18n("All Packages")) self.showInstallAction = QAction(KIcon(("list-add", "add")), i18n("Installable Packages"), self) self.connect(self.showInstallAction, SIGNAL("triggered()"), lambda: self.cw.switchState(StateManager.INSTALL)) self.cw.stateTab.addTab(QWidget(), KIcon(("list-add", "add")), i18n("Installable Packages")) self.showRemoveAction = QAction(KIcon(("list-remove", "remove")), i18n("Installed Packages"), self) self.connect(self.showRemoveAction, SIGNAL("triggered()"), lambda: self.cw.switchState(StateManager.REMOVE)) self.cw.stateTab.addTab(QWidget(), KIcon(("list-remove", "remove")), i18n("Installed Packages")) self.showUpgradeAction = QAction( KIcon(("system-software-update", "gear")), i18n("Updates"), self) self.connect(self.showUpgradeAction, SIGNAL("triggered()"), lambda: self.cw.switchState(StateManager.UPGRADE)) self.cw.stateTab.addTab(QWidget(), KIcon(("system-software-update", "gear")), i18n("Updates")) self.showPreferences = QAction( KIcon(("preferences-system", "package_settings")), i18n("Settings"), self) self.connect(self.showPreferences, SIGNAL("triggered()"), self.settingsDialog.show) self.actionQuit = QAction(KIcon("exit"), i18n("Quit"), self) self.actionQuit.setShortcuts(QKeySequence.Quit) self.connect(self.actionQuit, SIGNAL("triggered()"), qApp.exit) self.cw.menuButton.setMenu(QMenu('MainMenu', self.cw.menuButton)) self.cw.menuButton.setIcon( KIcon(("preferences-system", "package_settings"))) self.cw.menuButton.menu().clear() self.cw.contentHistory.hide() self.cw.menuButton.menu().addAction(self.showPreferences) self.cw.menuButton.menu().addSeparator() self.cw.menuButton.menu().addAction(self.actionQuit) self.cw._states = { self.cw.state.ALL: (0, self.showAllAction), self.cw.state.INSTALL: (1, self.showInstallAction), self.cw.state.REMOVE: (2, self.showRemoveAction), self.cw.state.UPGRADE: (3, self.showUpgradeAction) } self.showAllAction.setChecked(True) self.cw.checkUpdatesButton.hide() self.cw.checkUpdatesButton.setIcon(KIcon(("view-refresh", "reload"))) self.cw.showBasketButton.clicked.connect(self.cw.showBasket) # Little time left for the new ui self.menuBar().setVisible(False) self.cw.switchState(self.cw.state.ALL) def statusWaiting(self): self.updateStatusBar(i18n('Calculating dependencies...'), busy=True) def updateStatusBar(self, text, busy=False): if text == '': text = i18n("Currently your basket is empty.") self.busy.hide() self.cw.showBasketButton.hide() else: self.cw.showBasketButton.show() if busy: self.busy.busy() self.cw.showBasketButton.hide() else: self.busy.hide() self.cw.statusLabel.setText(text) self.cw.statusLabel.setToolTip(text) def queryClose(self): if config.PMConfig().systemTray(): self.hide() return False return True def queryExit(self): if not self.iface.operationInProgress(): if self.tray: del self.tray.notification return True return False def slotQuit(self): if self.iface.operationInProgress(): return
class MetadataDbLinker(object): """QGIS Plugin Implementation.""" def __init__(self, iface): """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__) self.plugin_metadata = plugin_metadata() # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join(self.plugin_dir, 'i18n', '{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) self.settings = MetadataDbLinkerSettings() # Create the dialog (after translation) and keep reference self.dlg = MetadataDialog() self.settings_dlg = SettingsDialog() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&{}'.format(self.plugin_metadata['name'])) # Initialize the fixes to DlgCreateTable class if not getattr(DlgCreateTable, 'original_createTable', None): DlgCreateTable.original_createTable = DlgCreateTable.createTable QgsMessageLog.logMessage("Adding the createTable patch.") DlgCreateTable.createTable = patched_createTable if not getattr(connector.PostGisDBConnector, 'accept_original', None): DlgImportVector.accept_original = DlgImportVector.accept DlgImportVector.accept = new_accept # menu DBTree.fireMetadataDlg = fireMetadataDlg DBTree.contextMenuEvent = newContextMenuEvent self.septimasearchprovider = MySeptimaSearchProvider(iface) # noinspection PyMethodMayBeStatic def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('MetadataDbLinker', message) def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" self.editmetadata_action = QAction( QIcon(':/plugins/MetadataDbLinker/resources/metadata.png'), self.tr(u'Enter or edit metadata'), self.iface.mainWindow()) self.editmetadata_action.triggered.connect(self.run) self.editmetadata_action.setEnabled(True) self.iface.addPluginToMenu(self.menu, self.editmetadata_action) self.iface.addToolBarIcon(self.editmetadata_action) self.actions.append(self.editmetadata_action) self.settings_action = QAction( QIcon(':/plugins/MetadataDbLinker/resources/settings.png'), self.tr(u'Settings'), self.iface.mainWindow()) self.settings_action.triggered.connect(self.settings_run) self.settings_action.setEnabled(True) self.iface.addPluginToMenu(self.menu, self.settings_action) self.actions.append(self.settings_action) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu( self.tr(u'&{}'.format(self.plugin_metadata['name'])), action) self.iface.removeToolBarIcon(action) def run(self): """Run method that performs all the real work""" errors = self.settings.verify_settings_set() if errors: QMessageBox.critical(None, u'Missing settings.', u'{}'.format(errors)) return None # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. pass def settings_run(self): """Run method that performs all the real work""" # show the dialog self.settings_dlg.show() # Run the dialog event loop result = self.settings_dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. pass
class MetaSearchPlugin(object): """base plugin""" def __init__(self, iface): """init""" self.iface = iface self.context = StaticContext() self.action_run = None self.action_help = None self.dialog = None self.web_menu = '&MetaSearch' LOGGER.debug('Setting up i18n') # TODO: does this work for locales like: pt_BR ? locale_name = QSettings().value("locale/userLocale")[0:2] # this one below does not pick up when you load QGIS with --lang param # locale_name = str(QLocale.system().name()).split('_')[0] LOGGER.debug('Locale name: %s', locale_name) # load if exists tr_file = os.path.join(self.context.ppath, 'locale', locale_name, 'LC_MESSAGES', 'ui.qm') if os.path.exists(tr_file): self.translator = QTranslator() result = self.translator.load(tr_file) if not result: msg = 'Failed to load translation: %s' % tr_file LOGGER.error(msg) raise RuntimeError(msg) QCoreApplication.installTranslator(self.translator) LOGGER.debug( QCoreApplication.translate('MetaSearch', 'Translation loaded: %s' % tr_file)) def initGui(self): """startup""" # run run_icon = QIcon('%s/%s' % (self.context.ppath, 'images/MetaSearch.png')) self.action_run = QAction(run_icon, 'MetaSearch', self.iface.mainWindow()) self.action_run.setWhatsThis( QCoreApplication.translate('MetaSearch', 'MetaSearch plugin')) self.action_run.setStatusTip( QCoreApplication.translate('MetaSearch', 'Search Metadata Catalogues')) self.action_run.triggered.connect(self.run) self.iface.addToolBarIcon(self.action_run) self.iface.addPluginToWebMenu(self.web_menu, self.action_run) # help help_icon = QIcon('%s/%s' % (self.context.ppath, 'images/help.png')) self.action_help = QAction(help_icon, 'Help', self.iface.mainWindow()) self.action_help.setWhatsThis( QCoreApplication.translate('MetaSearch', 'MetaSearch plugin help')) self.action_help.setStatusTip( QCoreApplication.translate('MetaSearch', 'Get Help on MetaSearch')) self.action_help.triggered.connect(self.help) self.iface.addPluginToWebMenu(self.web_menu, self.action_help) # prefab the dialog but not open it yet self.dialog = MetaSearchDialog(self.iface) def unload(self): """teardown""" # remove the plugin menu item and icon self.iface.removePluginWebMenu(self.web_menu, self.action_run) self.iface.removePluginWebMenu(self.web_menu, self.action_help) self.iface.removeToolBarIcon(self.action_run) self.iface.removeToolBarIcon(self.action_help) def run(self): """open MetaSearch""" self.dialog.exec_() def help(self): """open help in user's default web browser""" open_url(self.context.metadata.get('general', 'homepage'))
class GlobalsViewer(QWidget): """ The globals viewer widget """ def __init__(self, parent=None): QWidget.__init__(self, parent) self.filterEdit = None self.definitionButton = None self.findButton = None self.globalsViewer = None self.copyPathButton = None self.__createLayout() # create the context menu self.__menu = QMenu(self) self.__jumpMenuItem = self.__menu.addAction( \ PixmapCache().getIcon( 'definition.png' ), 'Jump to definition', self.__goToDefinition ) self.__menu.addSeparator() self.__findMenuItem = self.__menu.addAction( \ PixmapCache().getIcon( 'findusage.png' ), 'Find occurence', self.__findWhereUsed ) self.__menu.addSeparator() self.__copyMenuItem = self.__menu.addAction( \ PixmapCache().getIcon( 'copytoclipboard.png' ), 'Copy path to clipboard', self.globalsViewer.copyToClipboard ) self.globalsViewer.setContextMenuPolicy(Qt.CustomContextMenu) self.globalsViewer.customContextMenuRequested.connect( self.__handleShowContextMenu) GlobalData().project.projectChanged.connect(self.__onProjectChanged) self.connect(self.globalsViewer, SIGNAL("selectionChanged"), self.__selectionChanged) self.globalsViewer.openingItem.connect(self.itemActivated) self.connect(self.globalsViewer, SIGNAL("modelFilesChanged"), self.modelFilesChanged) self.filterEdit.lineEdit().setFocus() self.__contextItem = None return def __createLayout(self): " Helper to create the viewer layout " self.globalsViewer = GlobalsBrowser() # Toolbar part - buttons self.definitionButton = QAction( PixmapCache().getIcon('definition.png'), 'Jump to highlighted item definition', self) self.definitionButton.triggered.connect(self.__goToDefinition) self.findButton = QAction(PixmapCache().getIcon('findusage.png'), 'Find highlighted item occurences', self) self.findButton.triggered.connect(self.__findWhereUsed) self.copyPathButton = QAction( PixmapCache().getIcon('copytoclipboard.png'), 'Copy path to clipboard', self) self.copyPathButton.triggered.connect( self.globalsViewer.copyToClipboard) self.findNotUsedButton = QAction(PixmapCache().getIcon('notused.png'), 'Unused global variable analysis', self) self.findNotUsedButton.triggered.connect(self.__findNotUsed) self.findNotUsedButton.setEnabled(False) self.toolbar = QToolBar(self) self.toolbar.setMovable(False) self.toolbar.setAllowedAreas(Qt.TopToolBarArea) self.toolbar.setIconSize(QSize(16, 16)) self.toolbar.setFixedHeight(28) self.toolbar.setContentsMargins(0, 0, 0, 0) self.toolbar.addAction(self.definitionButton) self.toolbar.addAction(self.findButton) self.toolbar.addAction(self.copyPathButton) filterLabel = QLabel(" Filter ") self.toolbar.addWidget(filterLabel) self.filterEdit = CDMComboBox(True, self.toolbar) self.filterEdit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.filterEdit.lineEdit().setToolTip( "Space separated regular expressions") self.toolbar.addWidget(self.filterEdit) self.toolbar.addAction(self.findNotUsedButton) self.filterEdit.editTextChanged.connect(self.__filterChanged) self.filterEdit.itemAdded.connect(self.__filterItemAdded) self.filterEdit.enterClicked.connect(self.__enterInFilter) layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) layout.addWidget(self.toolbar) layout.addWidget(self.globalsViewer) self.setLayout(layout) return def __filterChanged(self, text): " Triggers when the filter text changed " self.globalsViewer.setFilter(text) self.globalsViewer.updateCounter() return def __selectionChanged(self, index): " Handles the changed selection " if index is None: self.__contextItem = None else: self.__contextItem = self.globalsViewer.model().item(index) self.__updateButtons() return def getItemCount(self): " Provides the number of items in the model - total, not only visible " return self.globalsViewer.model().sourceModel().rowCount() def itemActivated(self, path, line): " Handles the item activation " self.filterEdit.addItem(self.filterEdit.lineEdit().text()) return def __filterItemAdded(self): " The filter item has been added " project = GlobalData().project if project.fileName != "": project.setFindGlobalHistory(self.filterEdit.getItems()) return def __enterInFilter(self): " ENTER key has been clicked in the filter " # check if there any records displayed if self.globalsViewer.model().rowCount() == 0: return # Move the focus to the list and select the first row self.globalsViewer.clearSelection() flags = QItemSelectionModel.SelectCurrent | QItemSelectionModel.Rows self.globalsViewer.setSelection( QRect(0, 0, self.globalsViewer.width(), 1), flags) self.globalsViewer.setFocus() return def __onProjectChanged(self, what): " Triggered when a project is changed " if what == CodimensionProject.CompleteProject: self.__contextItem = None self.__updateButtons() self.filterEdit.clear() project = GlobalData().project if project.isLoaded(): self.filterEdit.editTextChanged.disconnect( self.__filterChanged) self.filterEdit.addItems(project.findGlobalHistory) self.filterEdit.editTextChanged.connect(self.__filterChanged) self.findNotUsedButton.setEnabled(self.getItemCount() > 0) else: self.findNotUsedButton.setEnabled(False) self.filterEdit.clearEditText() return def __handleShowContextMenu(self, coord): """ Show the context menu """ index = self.globalsViewer.indexAt(coord) if not index.isValid(): return # This will update the __contextItem self.__selectionChanged(index) if self.__contextItem is None: return self.__jumpMenuItem.setEnabled(self.definitionButton.isEnabled()) self.__findMenuItem.setEnabled(self.findButton.isEnabled()) self.__copyMenuItem.setEnabled(self.copyPathButton.isEnabled()) self.__menu.popup(QCursor.pos()) return def __goToDefinition(self): """ Jump to definition context menu handler """ if self.__contextItem is not None: self.globalsViewer.openItem(self.__contextItem) return def __findWhereUsed(self): """ Find where used context menu handler """ if self.__contextItem is not None: GlobalData().mainWindow.findWhereUsed( \ self.__contextItem.getPath(), self.__contextItem.sourceObj ) return def __findNotUsed(self): " Runs the unused global variable analysis " GlobalData().mainWindow.onNotUsedGlobals() return def __updateButtons(self): " Updates the toolbar buttons depending on what is selected " self.definitionButton.setEnabled(False) self.findButton.setEnabled(False) self.copyPathButton.setEnabled(False) if self.__contextItem is None: return if self.__contextItem.itemType == DecoratorItemType: self.definitionButton.setEnabled(True) self.copyPathButton.setEnabled(True) return if self.__contextItem.itemType in [ FunctionItemType, ClassItemType, AttributeItemType, GlobalItemType ]: self.definitionButton.setEnabled(True) self.findButton.setEnabled(True) self.copyPathButton.setEnabled(True) return def onFileUpdated(self, fileName, uuid): " Triggered when the file is updated " self.globalsViewer.onFileUpdated(fileName) self.findNotUsedButton.setEnabled( GlobalData().project.isLoaded() and \ self.getItemCount() > 0 ) return def modelFilesChanged(self): " Triggered when the source model has a file or files added or deleted " self.findNotUsedButton.setEnabled( GlobalData().project.isLoaded() and \ self.getItemCount() > 0 ) return
class Actions(actioncollection.ActionCollection): name = "documentactions" def createActions(self, parent): self.edit_cut_assign = QAction(parent) self.view_highlighting = QAction(parent) self.view_highlighting.setCheckable(True) self.view_goto_file_or_definition = QAction(parent) self.tools_indent_auto = QAction(parent) self.tools_indent_auto.setCheckable(True) self.tools_indent_indent = QAction(parent) self.tools_reformat = QAction(parent) self.tools_remove_trailing_whitespace = QAction(parent) self.tools_convert_ly = QAction(parent) self.tools_quick_remove_articulations = QAction(parent) self.tools_quick_remove_ornaments = QAction(parent) self.tools_quick_remove_instrument_scripts = QAction(parent) self.tools_quick_remove_slurs = QAction(parent) self.tools_quick_remove_dynamics = QAction(parent) self.tools_quick_remove_markup = QAction(parent) self.edit_cut_assign.setIcon(icons.get('edit-cut')) self.view_goto_file_or_definition.setShortcut( QKeySequence(Qt.ALT + Qt.Key_Return)) self.edit_cut_assign.setShortcut( QKeySequence(Qt.SHIFT + Qt.CTRL + Qt.Key_X)) def translateUI(self): self.edit_cut_assign.setText(_("Cut and Assign...")) self.view_highlighting.setText(_("Syntax &Highlighting")) self.view_goto_file_or_definition.setText( _("View File or Definition at &Cursor")) self.tools_indent_auto.setText(_("&Automatic Indent")) self.tools_indent_indent.setText(_("Re-&Indent")) self.tools_reformat.setText(_("&Format")) self.tools_remove_trailing_whitespace.setText( _("Remove Trailing &Whitespace")) self.tools_convert_ly.setText(_("&Update with convert-ly...")) self.tools_quick_remove_articulations.setText( _("Remove &Articulations")) self.tools_quick_remove_ornaments.setText(_("Remove &Ornaments")) self.tools_quick_remove_instrument_scripts.setText( _("Remove &Instrument Scripts")) self.tools_quick_remove_slurs.setText(_("Remove &Slurs")) self.tools_quick_remove_dynamics.setText(_("Remove &Dynamics")) self.tools_quick_remove_markup.setText( _("Remove Text &Markup (from music)"))
class BuilderGui ( QMainWindow ): def __init__ ( self, confFile, parent=None ): QMainWindow.__init__( self, parent ) self.setWindowTitle( 'Coriolis/Chams Builder' ) self._tabWidget = QTabWidget() self._configureWidget = ConfigureWidget(confFile) self._optionsWidget = OptionsWidget(self._configureWidget.conf) self._compileWidget = CompileWidget() self._aboutWidget = AboutWidget() self._tabWidget.addTab( self._optionsWidget , 'Options' ) self._tabWidget.addTab( self._compileWidget , 'Compile' ) self._tabWidget.addTab( self._configureWidget, 'Configure' ) self.setCentralWidget( self._tabWidget ) self._compileWidget.conf = self._configureWidget self._compileWidget.options = self._optionsWidget self._exitAction = QAction( '&Exit', self ) self._exitAction.setStatusTip( 'Exit CCB (settings are saved)' ) self._exitAction.setShortcut ( QKeySequence('CTRL+Q') ) self._exitAction.triggered.connect( QApplication.closeAllWindows ) self._saveAction = QAction( '&Save Settings', self ) self._saveAction.setStatusTip( 'Save Settings' ) self._saveAction.setShortcut ( QKeySequence('CTRL+S') ) self._saveAction.triggered.connect( self._configureWidget.saveSettings ) self._saveAction.triggered.connect( self._optionsWidget.saveSettings ) self._saveAction.triggered.connect( self._compileWidget.saveSettings ) self._aboutAction = QAction( '&About', self ) self._aboutAction.setStatusTip( 'A Word About Who\'s Responsible for This Thing' ) self._aboutAction.setShortcut ( QKeySequence('CTRL+A') ) self._aboutAction.triggered.connect( self._aboutWidget.show ) fileMenu = self.menuBar().addMenu( 'File' ) fileMenu.addAction( self._exitAction ) fileMenu.addAction( self._saveAction ) fileMenu.addAction( self._aboutAction ) return def closeEvent ( self, event ): self._configureWidget.saveSettings() self._optionsWidget .saveSettings() self._compileWidget .saveSettings() event.accept() return
class FileOutlineViewer( QWidget ): """ The file outline viewer widget """ def __init__( self, editorsManager, parent = None ): QWidget.__init__( self, parent ) self.__editorsManager = editorsManager self.__mainWindow = parent self.__editorsManager.currentChanged.connect( self.__onTabChanged ) self.connect( self.__editorsManager, SIGNAL( "tabClosed" ), self.__onTabClosed ) self.connect( self.__editorsManager, SIGNAL( 'bufferSavedAs' ), self.__onSavedBufferAs ) self.connect( self.__editorsManager, SIGNAL( 'fileTypeChanged' ), self.__onFileTypeChanged ) self.__outlineBrowsers = {} # UUID -> OutlineAttributes self.__currentUUID = None self.__updateTimer = QTimer( self ) self.__updateTimer.setSingleShot( True ) self.__updateTimer.timeout.connect( self.__updateView ) self.findButton = None self.outlineViewer = None self.toolbar = None self.__createLayout() self.__modifiedFormat = Settings().modifiedFormat # create the context menu self.__menu = QMenu( self ) self.__findMenuItem = self.__menu.addAction( PixmapCache().getIcon( 'findusage.png' ), 'Find where used', self.__findWhereUsed ) return def setTooltips( self, switchOn ): " Sets the tooltips mode " for key in self.__outlineBrowsers: self.__outlineBrowsers[ key ].browser.setTooltips( switchOn ) return def __connectOutlineBrowser( self, browser ): " Connects a new buffer signals " browser.setContextMenuPolicy( Qt.CustomContextMenu ) browser.customContextMenuRequested.connect( self.__handleShowContextMenu ) self.connect( browser, SIGNAL( "selectionChanged" ), self.__selectionChanged ) return def __createLayout( self ): " Helper to create the viewer layout " # Toolbar part - buttons self.findButton = QAction( PixmapCache().getIcon( 'findusage.png' ), 'Find where highlighted item is used', self ) self.findButton.setVisible( False ) self.findButton.triggered.connect( self.__findWhereUsed ) self.showParsingErrorsButton = QAction( PixmapCache().getIcon( 'showparsingerrors.png' ), 'Show lexer/parser errors', self ) self.showParsingErrorsButton.triggered.connect( self.__showParserError ) self.showParsingErrorsButton.setEnabled( False ) self.toolbar = QToolBar( self ) self.toolbar.setMovable( False ) self.toolbar.setAllowedAreas( Qt.TopToolBarArea ) self.toolbar.setIconSize( QSize( 16, 16 ) ) self.toolbar.setFixedHeight( 28 ) self.toolbar.setContentsMargins( 0, 0, 0, 0 ) self.toolbar.addAction( self.findButton ) self.toolbar.addAction( self.showParsingErrorsButton ) # Prepare members for reuse self.__noneLabel = QLabel( "\nNot a python file" ) self.__noneLabel.setFrameShape( QFrame.StyledPanel ) self.__noneLabel.setAlignment( Qt.AlignHCenter ) headerFont = self.__noneLabel.font() headerFont.setPointSize( headerFont.pointSize() + 2 ) self.__noneLabel.setFont( headerFont ) self.__noneLabel.setAutoFillBackground( True ) noneLabelPalette = self.__noneLabel.palette() noneLabelPalette.setColor( QPalette.Background, GlobalData().skin.nolexerPaper ) self.__noneLabel.setPalette( noneLabelPalette ) self.__layout = QVBoxLayout() self.__layout.setContentsMargins( 0, 0, 0, 0 ) self.__layout.setSpacing( 0 ) self.__layout.addWidget( self.toolbar ) self.__layout.addWidget( self.__noneLabel ) self.setLayout( self.__layout ) return def __selectionChanged( self, index ): " Handles the changed selection " if index is None: self.__outlineBrowsers[ self.__currentUUID ].contentItem = None else: self.__outlineBrowsers[ self.__currentUUID ].contentItem = \ self.__outlineBrowsers[ self.__currentUUID ].browser.model().item( index ) self.__updateButtons() return def __handleShowContextMenu( self, coord ): """ Show the context menu """ browser = self.__outlineBrowsers[ self.__currentUUID ].browser index = browser.indexAt( coord ) if not index.isValid(): return # This will update the contextItem self.__selectionChanged( index ) contextItem = self.__outlineBrowsers[ self.__currentUUID ].contentItem if contextItem is None: return self.__findMenuItem.setEnabled( self.findButton.isEnabled() ) self.__menu.popup( QCursor.pos() ) return def __goToDefinition( self ): " Jump to definition context menu handler " contextItem = self.__outlineBrowsers[ self.__currentUUID ].contentItem if contextItem is not None: self.__outlineBrowsers[ self.__currentUUID ].browser.openItem( contextItem ) return def __findWhereUsed( self ): """ Find where used context menu handler """ contextItem = self.__outlineBrowsers[ self.__currentUUID ].contentItem if contextItem is not None: GlobalData().mainWindow.findWhereUsed( contextItem.getPath(), contextItem.sourceObj ) return def __updateButtons( self ): " Updates the toolbar buttons depending on what is selected " self.findButton.setEnabled( False ) contextItem = self.__outlineBrowsers[ self.__currentUUID ].contentItem if contextItem is None: return if contextItem.itemType in [ FunctionItemType, ClassItemType, AttributeItemType, GlobalItemType ]: self.findButton.setEnabled( True ) return def __onTabChanged( self, index ): " Triggered when another tab becomes active " # If the timer is still active that means the tab was switched before # the handler had a chance to work. Therefore update the previous tab # first if so. if self.__updateTimer.isActive(): self.__updateTimer.stop() self.__updateView() # Now, switch the outline browser to the new tab if index == -1: widget = self.__editorsManager.currentWidget() else: widget = self.__editorsManager.getWidgetByIndex( index ) if widget is None: if self.__currentUUID is not None: self.__outlineBrowsers[ self.__currentUUID ].browser.hide() self.__currentUUID = None self.__noneLabel.show() self.showParsingErrorsButton.setEnabled( False ) return if widget.getType() not in [ MainWindowTabWidgetBase.PlainTextEditor, MainWindowTabWidgetBase.VCSAnnotateViewer ]: if self.__currentUUID is not None: self.__outlineBrowsers[ self.__currentUUID ].browser.hide() self.__currentUUID = None self.__noneLabel.show() self.showParsingErrorsButton.setEnabled( False ) return # This is text editor, detect the file type if widget.getFileType() not in [ PythonFileType, Python3FileType ]: if self.__currentUUID is not None: self.__outlineBrowsers[ self.__currentUUID ].browser.hide() self.__currentUUID = None self.__noneLabel.show() self.showParsingErrorsButton.setEnabled( False ) return # This is a python file, check if we already have the parsed info in # the cache uuid = widget.getUUID() if uuid in self.__outlineBrowsers: # We have it, hide the current and show the existed if self.__currentUUID is not None: self.__outlineBrowsers[ self.__currentUUID ].browser.hide() self.__currentUUID = None else: self.__noneLabel.hide() self.__currentUUID = uuid self.__outlineBrowsers[ self.__currentUUID ].browser.show() info = self.__outlineBrowsers[ self.__currentUUID ].info self.showParsingErrorsButton.setEnabled( info.isOK != True ) return # It is first time we are here, create a new editor = widget.getEditor() editor.SCEN_CHANGE.connect( self.__onBufferChanged ) editor.cursorPositionChanged.connect( self.__cursorPositionChanged ) info = getBriefModuleInfoFromMemory( editor.text() ) self.showParsingErrorsButton.setEnabled( info.isOK != True ) shortFileName = widget.getShortName() browser = OutlineBrowser( uuid, shortFileName, info, self ) browser.setHeaderHighlight( info.isOK != True ) self.__connectOutlineBrowser( browser ) self.__layout.addWidget( browser ) if self.__currentUUID is not None: self.__outlineBrowsers[ self.__currentUUID ].browser.hide() self.__currentUUID = None else: self.__noneLabel.hide() self.__currentUUID = uuid attributes = OutlineAttributes() attributes.browser = browser attributes.contextItem = None attributes.info = info attributes.shortFileName = shortFileName attributes.changed = False self.__outlineBrowsers[ self.__currentUUID ] = attributes self.__outlineBrowsers[ self.__currentUUID ].browser.show() return def getCurrentUsedInfo( self ): " Provides the info used to show the current outline window " if self.__currentUUID in self.__outlineBrowsers: return self.__outlineBrowsers[ self.__currentUUID ].info return None def __cursorPositionChanged( self, xpos, ypos ): " Triggered when a cursor position is changed " if self.__updateTimer.isActive(): # If a file is very large and the cursor is moved # straight after changes this will delay the update till # the real pause. self.__updateTimer.stop() self.__updateTimer.start( 1500 ) return def __onBufferChanged( self ): " Triggered when a change in the buffer is identified " if self.__currentUUID is None: return widget = self.__editorsManager.getWidgetByUUID( self.__currentUUID ) if widget is None: return if widget.getEditor().ignoreBufferChangedSignal: return if self.__mainWindow.debugMode: return self.__updateTimer.stop() if self.__currentUUID in self.__outlineBrowsers: if self.__outlineBrowsers[ self.__currentUUID ].changed == False: self.__outlineBrowsers[ self.__currentUUID ].changed = True browser = self.__outlineBrowsers[ self.__currentUUID ].browser fName = self.__outlineBrowsers[ self.__currentUUID ].shortFileName title = self.__modifiedFormat % fName browser.model().sourceModel().updateRootData( 0, title ) self.__updateTimer.start( 1500 ) return def __updateView( self ): " Updates the view when a file is changed " self.__updateTimer.stop() info = self.getCurrentBufferInfo() if info is None: return self.showParsingErrorsButton.setEnabled( info.isOK != True ) browser = self.__outlineBrowsers[ self.__currentUUID ].browser fName = self.__outlineBrowsers[ self.__currentUUID ].shortFileName browser.setHeaderHighlight( info.isOK != True ) if not info.isOK: title = self.__modifiedFormat % fName browser.model().sourceModel().updateRootData( 0, title ) return browser.model().sourceModel().updateRootData( 0, fName ) self.__outlineBrowsers[ self.__currentUUID ].changed = False browser.updateFileItem( browser.model().sourceModel().rootItem, info ) self.__outlineBrowsers[ self.__currentUUID ].info = info return def getCurrentBufferInfo( self ): " Provides the current buffer parsed info " if self.__currentUUID is None: return None widget = self.__editorsManager.getWidgetByUUID( self.__currentUUID ) if widget is None: return None editor = widget.getEditor() info = getBriefModuleInfoFromMemory( editor.text() ) return info def __onTabClosed( self, uuid ): " Triggered when a tab is closed " if uuid in self.__outlineBrowsers: del self.__outlineBrowsers[ uuid ] return def __onSavedBufferAs( self, fileName, uuid ): " Triggered when a file is saved with a new name " if uuid in self.__outlineBrowsers: baseName = os.path.basename( fileName ) if detectFileType( fileName ) not in [ PythonFileType, Python3FileType ]: # It's not a python file anymore if uuid == self.__currentUUID: self.__outlineBrowsers[ uuid ].browser.hide() self.__noneLabel.show() self.__currentUUID = None del self.__outlineBrowsers[ uuid ] self.showParsingErrorsButton.setEnabled( False ) self.findButton.setEnabled( False ) return # Still python file with a different name browser = self.__outlineBrowsers[ uuid ].browser self.__outlineBrowsers[ uuid ].shortFileName = baseName if self.__outlineBrowsers[ uuid ].changed: title = self.__modifiedFormat % baseName else: title = baseName browser.model().sourceModel().updateRootData( 0, title ) return def __onFileTypeChanged( self, fileName, uuid, newFileType ): " Triggered when the current buffer file type is changed, e.g. .cgi " if newFileType in [ PythonFileType, Python3FileType ]: # The file became a python one if uuid not in self.__outlineBrowsers: self.__onTabChanged( -1 ) else: if uuid in self.__outlineBrowsers: # It's not a python file any more if uuid == self.__currentUUID: self.__outlineBrowsers[ uuid ].browser.hide() self.__noneLabel.show() self.__currentUUID = None del self.__outlineBrowsers[ uuid ] self.showParsingErrorsButton.setEnabled( False ) self.findButton.setEnabled( False ) return def __showParserError( self ): " Shows the parser errors window " if self.__currentUUID is None: return try: fName = self.__outlineBrowsers[ self.__currentUUID ].shortFileName widget = self.__editorsManager.getWidgetByUUID( self.__currentUUID ) if widget is None: return editor = widget.getEditor() info = getBriefModuleInfoFromMemory( editor.text() ) dialog = ParserErrorsDialog( fName, info ) dialog.exec_() except Exception, ex: logging.error( str( ex ) ) return
class PythonConsoleWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.setWindowTitle( QCoreApplication.translate("PythonConsole", "Python Console")) self.settings = QSettings() self.shell = ShellScintilla(self) self.setFocusProxy(self.shell) self.shellOut = ShellOutputScintilla(self) self.tabEditorWidget = EditorTabWidget(self) ##------------ UI ------------------------------- self.splitterEditor = QSplitter(self) self.splitterEditor.setOrientation(Qt.Horizontal) self.splitterEditor.setHandleWidth(6) self.splitterEditor.setChildrenCollapsible(True) self.shellOutWidget = QWidget(self) self.shellOutWidget.setLayout(QVBoxLayout()) self.shellOutWidget.layout().setContentsMargins(0, 0, 0, 0) self.shellOutWidget.layout().addWidget(self.shellOut) self.splitter = QSplitter(self.splitterEditor) self.splitter.setOrientation(Qt.Vertical) self.splitter.setHandleWidth(3) self.splitter.setChildrenCollapsible(False) self.splitter.addWidget(self.shellOutWidget) self.splitter.addWidget(self.shell) #self.splitterEditor.addWidget(self.tabEditorWidget) self.splitterObj = QSplitter(self.splitterEditor) self.splitterObj.setHandleWidth(3) self.splitterObj.setOrientation(Qt.Horizontal) #self.splitterObj.setSizes([0, 0]) #self.splitterObj.setStretchFactor(0, 1) self.widgetEditor = QWidget(self.splitterObj) self.widgetFind = QWidget(self) self.listClassMethod = QTreeWidget(self.splitterObj) self.listClassMethod.setColumnCount(2) objInspLabel = QCoreApplication.translate("PythonConsole", "Object Inspector") self.listClassMethod.setHeaderLabels([objInspLabel, '']) self.listClassMethod.setColumnHidden(1, True) self.listClassMethod.setAlternatingRowColors(True) #self.splitterEditor.addWidget(self.widgetEditor) #self.splitterObj.addWidget(self.listClassMethod) #self.splitterObj.addWidget(self.widgetEditor) # Hide side editor on start up self.splitterObj.hide() self.listClassMethod.hide() # Hide search widget on start up self.widgetFind.hide() sizes = self.splitter.sizes() self.splitter.setSizes(sizes) ##----------------Restore Settings------------------------------------ self.restoreSettingsConsole() ##------------------Toolbar Editor------------------------------------- ## Action for Open File openFileBt = QCoreApplication.translate("PythonConsole", "Open file") self.openFileButton = QAction(self) self.openFileButton.setCheckable(False) self.openFileButton.setEnabled(True) self.openFileButton.setIcon( QgsApplication.getThemeIcon("console/iconOpenConsole.png")) self.openFileButton.setMenuRole(QAction.PreferencesRole) self.openFileButton.setIconVisibleInMenu(True) self.openFileButton.setToolTip(openFileBt) self.openFileButton.setText(openFileBt) openExtEditorBt = QCoreApplication.translate( "PythonConsole", "Open in external editor") self.openInEditorButton = QAction(self) self.openInEditorButton.setCheckable(False) self.openInEditorButton.setEnabled(True) self.openInEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconShowEditorConsole.png")) self.openInEditorButton.setMenuRole(QAction.PreferencesRole) self.openInEditorButton.setIconVisibleInMenu(True) self.openInEditorButton.setToolTip(openExtEditorBt) self.openInEditorButton.setText(openExtEditorBt) ## Action for Save File saveFileBt = QCoreApplication.translate("PythonConsole", "Save") self.saveFileButton = QAction(self) self.saveFileButton.setCheckable(False) self.saveFileButton.setEnabled(False) self.saveFileButton.setIcon( QgsApplication.getThemeIcon("console/iconSaveConsole.png")) self.saveFileButton.setMenuRole(QAction.PreferencesRole) self.saveFileButton.setIconVisibleInMenu(True) self.saveFileButton.setToolTip(saveFileBt) self.saveFileButton.setText(saveFileBt) ## Action for Save File As saveAsFileBt = QCoreApplication.translate("PythonConsole", "Save As...") self.saveAsFileButton = QAction(self) self.saveAsFileButton.setCheckable(False) self.saveAsFileButton.setEnabled(True) self.saveAsFileButton.setIcon( QgsApplication.getThemeIcon("console/iconSaveAsConsole.png")) self.saveAsFileButton.setMenuRole(QAction.PreferencesRole) self.saveAsFileButton.setIconVisibleInMenu(True) self.saveAsFileButton.setToolTip(saveAsFileBt) self.saveAsFileButton.setText(saveAsFileBt) ## Action Cut cutEditorBt = QCoreApplication.translate("PythonConsole", "Cut") self.cutEditorButton = QAction(self) self.cutEditorButton.setCheckable(False) self.cutEditorButton.setEnabled(True) self.cutEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconCutEditorConsole.png")) self.cutEditorButton.setMenuRole(QAction.PreferencesRole) self.cutEditorButton.setIconVisibleInMenu(True) self.cutEditorButton.setToolTip(cutEditorBt) self.cutEditorButton.setText(cutEditorBt) ## Action Copy copyEditorBt = QCoreApplication.translate("PythonConsole", "Copy") self.copyEditorButton = QAction(self) self.copyEditorButton.setCheckable(False) self.copyEditorButton.setEnabled(True) self.copyEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconCopyEditorConsole.png")) self.copyEditorButton.setMenuRole(QAction.PreferencesRole) self.copyEditorButton.setIconVisibleInMenu(True) self.copyEditorButton.setToolTip(copyEditorBt) self.copyEditorButton.setText(copyEditorBt) ## Action Paste pasteEditorBt = QCoreApplication.translate("PythonConsole", "Paste") self.pasteEditorButton = QAction(self) self.pasteEditorButton.setCheckable(False) self.pasteEditorButton.setEnabled(True) self.pasteEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconPasteEditorConsole.png")) self.pasteEditorButton.setMenuRole(QAction.PreferencesRole) self.pasteEditorButton.setIconVisibleInMenu(True) self.pasteEditorButton.setToolTip(pasteEditorBt) self.pasteEditorButton.setText(pasteEditorBt) ## Action Run Script (subprocess) runScriptEditorBt = QCoreApplication.translate("PythonConsole", "Run script") self.runScriptEditorButton = QAction(self) self.runScriptEditorButton.setCheckable(False) self.runScriptEditorButton.setEnabled(True) self.runScriptEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconRunScriptConsole.png")) self.runScriptEditorButton.setMenuRole(QAction.PreferencesRole) self.runScriptEditorButton.setIconVisibleInMenu(True) self.runScriptEditorButton.setToolTip(runScriptEditorBt) self.runScriptEditorButton.setText(runScriptEditorBt) ## Action Run Script (subprocess) commentEditorBt = QCoreApplication.translate("PythonConsole", "Comment") self.commentEditorButton = QAction(self) self.commentEditorButton.setCheckable(False) self.commentEditorButton.setEnabled(True) self.commentEditorButton.setIcon( QgsApplication.getThemeIcon( "console/iconCommentEditorConsole.png")) self.commentEditorButton.setMenuRole(QAction.PreferencesRole) self.commentEditorButton.setIconVisibleInMenu(True) self.commentEditorButton.setToolTip(commentEditorBt) self.commentEditorButton.setText(commentEditorBt) ## Action Run Script (subprocess) uncommentEditorBt = QCoreApplication.translate("PythonConsole", "Uncomment") self.uncommentEditorButton = QAction(self) self.uncommentEditorButton.setCheckable(False) self.uncommentEditorButton.setEnabled(True) self.uncommentEditorButton.setIcon( QgsApplication.getThemeIcon( "console/iconUncommentEditorConsole.png")) self.uncommentEditorButton.setMenuRole(QAction.PreferencesRole) self.uncommentEditorButton.setIconVisibleInMenu(True) self.uncommentEditorButton.setToolTip(uncommentEditorBt) self.uncommentEditorButton.setText(uncommentEditorBt) ## Action for Object browser objList = QCoreApplication.translate("PythonConsole", "Object Inspector") self.objectListButton = QAction(self) self.objectListButton.setCheckable(True) self.objectListButton.setEnabled( self.settings.value("pythonConsole/enableObjectInsp", False, type=bool)) self.objectListButton.setIcon( QgsApplication.getThemeIcon("console/iconClassBrowserConsole.png")) self.objectListButton.setMenuRole(QAction.PreferencesRole) self.objectListButton.setIconVisibleInMenu(True) self.objectListButton.setToolTip(objList) self.objectListButton.setText(objList) ## Action for Find text findText = QCoreApplication.translate("PythonConsole", "Find Text") self.findTextButton = QAction(self) self.findTextButton.setCheckable(True) self.findTextButton.setEnabled(True) self.findTextButton.setIcon( QgsApplication.getThemeIcon("console/iconSearchEditorConsole.png")) self.findTextButton.setMenuRole(QAction.PreferencesRole) self.findTextButton.setIconVisibleInMenu(True) self.findTextButton.setToolTip(findText) self.findTextButton.setText(findText) ##----------------Toolbar Console------------------------------------- ## Action Show Editor showEditor = QCoreApplication.translate("PythonConsole", "Show editor") self.showEditorButton = QAction(self) self.showEditorButton.setEnabled(True) self.showEditorButton.setCheckable(True) self.showEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconShowEditorConsole.png")) self.showEditorButton.setMenuRole(QAction.PreferencesRole) self.showEditorButton.setIconVisibleInMenu(True) self.showEditorButton.setToolTip(showEditor) self.showEditorButton.setText(showEditor) ## Action for Clear button clearBt = QCoreApplication.translate("PythonConsole", "Clear console") self.clearButton = QAction(self) self.clearButton.setCheckable(False) self.clearButton.setEnabled(True) self.clearButton.setIcon( QgsApplication.getThemeIcon("console/iconClearConsole.png")) self.clearButton.setMenuRole(QAction.PreferencesRole) self.clearButton.setIconVisibleInMenu(True) self.clearButton.setToolTip(clearBt) self.clearButton.setText(clearBt) ## Action for settings optionsBt = QCoreApplication.translate("PythonConsole", "Settings") self.optionsButton = QAction(self) self.optionsButton.setCheckable(False) self.optionsButton.setEnabled(True) self.optionsButton.setIcon( QgsApplication.getThemeIcon("console/iconSettingsConsole.png")) self.optionsButton.setMenuRole(QAction.PreferencesRole) self.optionsButton.setIconVisibleInMenu(True) self.optionsButton.setToolTip(optionsBt) self.optionsButton.setText(optionsBt) ## Action menu for class actionClassBt = QCoreApplication.translate("PythonConsole", "Import Class") self.actionClass = QAction(self) self.actionClass.setCheckable(False) self.actionClass.setEnabled(True) self.actionClass.setIcon( QgsApplication.getThemeIcon("console/iconClassConsole.png")) self.actionClass.setMenuRole(QAction.PreferencesRole) self.actionClass.setIconVisibleInMenu(True) self.actionClass.setToolTip(actionClassBt) self.actionClass.setText(actionClassBt) ## Import Processing class loadProcessingBt = QCoreApplication.translate( "PythonConsole", "Import Processing class") self.loadProcessingButton = QAction(self) self.loadProcessingButton.setCheckable(False) self.loadProcessingButton.setEnabled(True) self.loadProcessingButton.setIcon( QgsApplication.getThemeIcon("console/iconProcessingConsole.png")) self.loadProcessingButton.setMenuRole(QAction.PreferencesRole) self.loadProcessingButton.setIconVisibleInMenu(True) self.loadProcessingButton.setToolTip(loadProcessingBt) self.loadProcessingButton.setText(loadProcessingBt) ## Import QtCore class loadQtCoreBt = QCoreApplication.translate("PythonConsole", "Import PyQt.QtCore class") self.loadQtCoreButton = QAction(self) self.loadQtCoreButton.setCheckable(False) self.loadQtCoreButton.setEnabled(True) self.loadQtCoreButton.setIcon( QgsApplication.getThemeIcon("console/iconQtCoreConsole.png")) self.loadQtCoreButton.setMenuRole(QAction.PreferencesRole) self.loadQtCoreButton.setIconVisibleInMenu(True) self.loadQtCoreButton.setToolTip(loadQtCoreBt) self.loadQtCoreButton.setText(loadQtCoreBt) ## Import QtGui class loadQtGuiBt = QCoreApplication.translate("PythonConsole", "Import PyQt.QtGui class") self.loadQtGuiButton = QAction(self) self.loadQtGuiButton.setCheckable(False) self.loadQtGuiButton.setEnabled(True) self.loadQtGuiButton.setIcon( QgsApplication.getThemeIcon("console/iconQtGuiConsole.png")) self.loadQtGuiButton.setMenuRole(QAction.PreferencesRole) self.loadQtGuiButton.setIconVisibleInMenu(True) self.loadQtGuiButton.setToolTip(loadQtGuiBt) self.loadQtGuiButton.setText(loadQtGuiBt) ## Action for Run script runBt = QCoreApplication.translate("PythonConsole", "Run command") self.runButton = QAction(self) self.runButton.setCheckable(False) self.runButton.setEnabled(True) self.runButton.setIcon( QgsApplication.getThemeIcon("console/iconRunConsole.png")) self.runButton.setMenuRole(QAction.PreferencesRole) self.runButton.setIconVisibleInMenu(True) self.runButton.setToolTip(runBt) self.runButton.setText(runBt) ## Help action helpBt = QCoreApplication.translate("PythonConsole", "Help") self.helpButton = QAction(self) self.helpButton.setCheckable(False) self.helpButton.setEnabled(True) self.helpButton.setIcon( QgsApplication.getThemeIcon("console/iconHelpConsole.png")) self.helpButton.setMenuRole(QAction.PreferencesRole) self.helpButton.setIconVisibleInMenu(True) self.helpButton.setToolTip(helpBt) self.helpButton.setText(helpBt) self.toolBar = QToolBar() self.toolBar.setEnabled(True) self.toolBar.setFocusPolicy(Qt.NoFocus) self.toolBar.setContextMenuPolicy(Qt.DefaultContextMenu) self.toolBar.setLayoutDirection(Qt.LeftToRight) self.toolBar.setIconSize(QSize(16, 16)) self.toolBar.setMovable(False) self.toolBar.setFloatable(False) self.toolBar.addAction(self.clearButton) self.toolBar.addAction(self.actionClass) self.toolBar.addAction(self.runButton) self.toolBar.addSeparator() self.toolBar.addAction(self.showEditorButton) self.toolBar.addSeparator() self.toolBar.addAction(self.optionsButton) self.toolBar.addAction(self.helpButton) self.toolBarEditor = QToolBar() self.toolBarEditor.setEnabled(False) self.toolBarEditor.setFocusPolicy(Qt.NoFocus) self.toolBarEditor.setContextMenuPolicy(Qt.DefaultContextMenu) self.toolBarEditor.setLayoutDirection(Qt.LeftToRight) self.toolBarEditor.setIconSize(QSize(16, 16)) self.toolBarEditor.setMovable(False) self.toolBarEditor.setFloatable(False) self.toolBarEditor.addAction(self.openFileButton) self.toolBarEditor.addAction(self.openInEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.saveFileButton) self.toolBarEditor.addAction(self.saveAsFileButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.runScriptEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.findTextButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.cutEditorButton) self.toolBarEditor.addAction(self.copyEditorButton) self.toolBarEditor.addAction(self.pasteEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.commentEditorButton) self.toolBarEditor.addAction(self.uncommentEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.objectListButton) ## Menu Import Class self.classMenu = QMenu() self.classMenu.addAction(self.loadProcessingButton) self.classMenu.addAction(self.loadQtCoreButton) self.classMenu.addAction(self.loadQtGuiButton) cM = self.toolBar.widgetForAction(self.actionClass) cM.setMenu(self.classMenu) cM.setPopupMode(QToolButton.InstantPopup) self.widgetButton = QWidget() sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.widgetButton.sizePolicy().hasHeightForWidth()) self.widgetButton.setSizePolicy(sizePolicy) self.widgetButtonEditor = QWidget(self.widgetEditor) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.widgetButtonEditor.sizePolicy().hasHeightForWidth()) self.widgetButtonEditor.setSizePolicy(sizePolicy) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.shellOut.sizePolicy().hasHeightForWidth()) self.shellOut.setSizePolicy(sizePolicy) self.shellOut.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.shell.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) ##------------ Layout ------------------------------- self.mainLayout = QGridLayout(self) self.mainLayout.setMargin(0) self.mainLayout.setSpacing(0) self.mainLayout.addWidget(self.widgetButton, 0, 0, 1, 1) self.mainLayout.addWidget(self.splitterEditor, 0, 1, 1, 1) self.shellOutWidget.layout().insertWidget(0, self.toolBar) self.layoutEditor = QGridLayout(self.widgetEditor) self.layoutEditor.setMargin(0) self.layoutEditor.setSpacing(0) self.layoutEditor.addWidget(self.toolBarEditor, 0, 1, 1, 1) self.layoutEditor.addWidget(self.widgetButtonEditor, 1, 0, 2, 1) self.layoutEditor.addWidget(self.tabEditorWidget, 1, 1, 1, 1) self.layoutEditor.addWidget(self.widgetFind, 2, 1, 1, 1) ## Layout for the find widget self.layoutFind = QGridLayout(self.widgetFind) self.layoutFind.setContentsMargins(0, 0, 0, 0) self.lineEditFind = QgsFilterLineEdit() placeHolderTxt = QCoreApplication.translate("PythonConsole", "Enter text to find...") if pyqtconfig.Configuration().qt_version >= 0x40700: self.lineEditFind.setPlaceholderText(placeHolderTxt) else: self.lineEditFind.setToolTip(placeHolderTxt) self.findNextButton = QToolButton() self.findNextButton.setEnabled(False) toolTipfindNext = QCoreApplication.translate("PythonConsole", "Find Next") self.findNextButton.setToolTip(toolTipfindNext) self.findNextButton.setIcon( QgsApplication.getThemeIcon( "console/iconSearchNextEditorConsole.png")) self.findNextButton.setIconSize(QSize(24, 24)) self.findNextButton.setAutoRaise(True) self.findPrevButton = QToolButton() self.findPrevButton.setEnabled(False) toolTipfindPrev = QCoreApplication.translate("PythonConsole", "Find Previous") self.findPrevButton.setToolTip(toolTipfindPrev) self.findPrevButton.setIcon( QgsApplication.getThemeIcon( "console/iconSearchPrevEditorConsole.png")) self.findPrevButton.setIconSize(QSize(24, 24)) self.findPrevButton.setAutoRaise(True) self.caseSensitive = QCheckBox() caseSensTr = QCoreApplication.translate("PythonConsole", "Case Sensitive") self.caseSensitive.setText(caseSensTr) self.wholeWord = QCheckBox() wholeWordTr = QCoreApplication.translate("PythonConsole", "Whole Word") self.wholeWord.setText(wholeWordTr) self.wrapAround = QCheckBox() self.wrapAround.setChecked(True) wrapAroundTr = QCoreApplication.translate("PythonConsole", "Wrap Around") self.wrapAround.setText(wrapAroundTr) self.layoutFind.addWidget(self.lineEditFind, 0, 1, 1, 1) self.layoutFind.addWidget(self.findPrevButton, 0, 2, 1, 1) self.layoutFind.addWidget(self.findNextButton, 0, 3, 1, 1) self.layoutFind.addWidget(self.caseSensitive, 0, 4, 1, 1) self.layoutFind.addWidget(self.wholeWord, 0, 5, 1, 1) self.layoutFind.addWidget(self.wrapAround, 0, 6, 1, 1) ##------------ Add first Tab in Editor ------------------------------- #self.tabEditorWidget.newTabEditor(tabName='first', filename=None) ##------------ Signal ------------------------------- self.findTextButton.toggled.connect(self.findTextEditor) self.objectListButton.toggled.connect(self.toggleObjectListWidget) self.commentEditorButton.triggered.connect(self.commentCode) self.uncommentEditorButton.triggered.connect(self.uncommentCode) self.runScriptEditorButton.triggered.connect(self.runScriptEditor) self.cutEditorButton.triggered.connect(self.cutEditor) self.copyEditorButton.triggered.connect(self.copyEditor) self.pasteEditorButton.triggered.connect(self.pasteEditor) self.showEditorButton.toggled.connect(self.toggleEditor) self.clearButton.triggered.connect(self.shellOut.clearConsole) self.optionsButton.triggered.connect(self.openSettings) self.loadProcessingButton.triggered.connect(self.processing) self.loadQtCoreButton.triggered.connect(self.qtCore) self.loadQtGuiButton.triggered.connect(self.qtGui) self.runButton.triggered.connect(self.shell.entered) self.openFileButton.triggered.connect(self.openScriptFile) self.openInEditorButton.triggered.connect(self.openScriptFileExtEditor) self.saveFileButton.triggered.connect(self.saveScriptFile) self.saveAsFileButton.triggered.connect(self.saveAsScriptFile) self.helpButton.triggered.connect(self.openHelp) self.connect(self.listClassMethod, SIGNAL('itemClicked(QTreeWidgetItem*, int)'), self.onClickGoToLine) self.lineEditFind.returnPressed.connect(self._findText) self.findNextButton.clicked.connect(self._findNext) self.findPrevButton.clicked.connect(self._findPrev) self.lineEditFind.textChanged.connect(self._textFindChanged) def _findText(self): self.tabEditorWidget.currentWidget().newEditor.findText(True) def _findNext(self): self.tabEditorWidget.currentWidget().newEditor.findText(True) def _findPrev(self): self.tabEditorWidget.currentWidget().newEditor.findText(False) def _textFindChanged(self): if self.lineEditFind.text(): self.findNextButton.setEnabled(True) self.findPrevButton.setEnabled(True) else: self.lineEditFind.setStyleSheet('') self.findNextButton.setEnabled(False) self.findPrevButton.setEnabled(False) def onClickGoToLine(self, item, column): tabEditor = self.tabEditorWidget.currentWidget().newEditor if item.text(1) == 'syntaxError': check = tabEditor.syntaxCheck(fromContextMenu=False) if check and not tabEditor.isReadOnly(): self.tabEditorWidget.currentWidget().save() return linenr = int(item.text(1)) itemName = str(item.text(0)) charPos = itemName.find(' ') if charPos != -1: objName = itemName[0:charPos] else: objName = itemName tabEditor.goToLine(objName, linenr) def processing(self): self.shell.commandConsole('processing') def qtCore(self): self.shell.commandConsole('qtCore') def qtGui(self): self.shell.commandConsole('qtGui') def toggleEditor(self, checked): self.splitterObj.show() if checked else self.splitterObj.hide() if not self.tabEditorWidget: self.tabEditorWidget.enableToolBarEditor(checked) self.tabEditorWidget.restoreTabsOrAddNew() def toggleObjectListWidget(self, checked): self.listClassMethod.show() if checked else self.listClassMethod.hide() def findTextEditor(self, checked): self.widgetFind.show() if checked else self.widgetFind.hide() def pasteEditor(self): self.tabEditorWidget.currentWidget().newEditor.paste() def cutEditor(self): self.tabEditorWidget.currentWidget().newEditor.cut() def copyEditor(self): self.tabEditorWidget.currentWidget().newEditor.copy() def runScriptEditor(self): self.tabEditorWidget.currentWidget().newEditor.runScriptCode() def commentCode(self): self.tabEditorWidget.currentWidget().newEditor.commentEditorCode(True) def uncommentCode(self): self.tabEditorWidget.currentWidget().newEditor.commentEditorCode(False) def openScriptFileExtEditor(self): tabWidget = self.tabEditorWidget.currentWidget() path = tabWidget.path import subprocess try: subprocess.Popen([os.environ['EDITOR'], path]) except KeyError: QDesktopServices.openUrl(QUrl.fromLocalFile(path)) def openScriptFile(self): lastDirPath = self.settings.value("pythonConsole/lastDirPath", QDir.homePath()) openFileTr = QCoreApplication.translate("PythonConsole", "Open File") fileList = QFileDialog.getOpenFileNames(self, openFileTr, lastDirPath, "Script file (*.py)") if fileList: for pyFile in fileList: for i in range(self.tabEditorWidget.count()): tabWidget = self.tabEditorWidget.widget(i) if tabWidget.path == pyFile: self.tabEditorWidget.setCurrentWidget(tabWidget) break else: tabName = QFileInfo(pyFile).fileName() self.tabEditorWidget.newTabEditor(tabName, pyFile) lastDirPath = QFileInfo(pyFile).path() self.settings.setValue("pythonConsole/lastDirPath", pyFile) self.updateTabListScript(pyFile, action='append') def saveScriptFile(self): tabWidget = self.tabEditorWidget.currentWidget() try: tabWidget.save() except (IOError, OSError) as error: msgText = QCoreApplication.translate( 'PythonConsole', 'The file <b>{0}</b> could not be saved. Error: {1}').format( tabWidget.path, error.strerror) self.callWidgetMessageBarEditor(msgText, 2, False) def saveAsScriptFile(self, index=None): tabWidget = self.tabEditorWidget.currentWidget() if not index: index = self.tabEditorWidget.currentIndex() if not tabWidget.path: fileName = self.tabEditorWidget.tabText(index) + '.py' folder = self.settings.value("pythonConsole/lastDirPath", QDir.home()) pathFileName = os.path.join(folder, fileName) fileNone = True else: pathFileName = tabWidget.path fileNone = False saveAsFileTr = QCoreApplication.translate("PythonConsole", "Save File As") filename = QFileDialog.getSaveFileName(self, saveAsFileTr, pathFileName, "Script file (*.py)") if filename: try: tabWidget.save(filename) except (IOError, OSError) as error: msgText = QCoreApplication.translate( 'PythonConsole', 'The file <b>{0}</b> could not be saved. Error: {1}' ).format(tabWidget.path, error.strerror) self.callWidgetMessageBarEditor(msgText, 2, False) if fileNone: tabWidget.path = None else: tabWidget.path = pathFileName return if not fileNone: self.updateTabListScript(pathFileName, action='remove') def openHelp(self): QgsContextHelp.run("PythonConsole") def openSettings(self): if optionsDialog(self).exec_(): self.shell.refreshSettingsShell() self.shellOut.refreshSettingsOutput() self.tabEditorWidget.refreshSettingsEditor() def callWidgetMessageBar(self, text): self.shellOut.widgetMessageBar(iface, text) def callWidgetMessageBarEditor(self, text, level, timed): self.tabEditorWidget.widgetMessageBar(iface, text, level, timed) def updateTabListScript(self, script, action=None): if action == 'remove': self.tabListScript.remove(script) elif action == 'append': if not self.tabListScript: self.tabListScript = [] if script not in self.tabListScript: self.tabListScript.append(script) else: self.tabListScript = [] self.settings.setValue("pythonConsole/tabScripts", self.tabListScript) def saveSettingsConsole(self): self.settings.setValue("pythonConsole/splitterConsole", self.splitter.saveState()) self.settings.setValue("pythonConsole/splitterObj", self.splitterObj.saveState()) self.settings.setValue("pythonConsole/splitterEditor", self.splitterEditor.saveState()) self.shell.writeHistoryFile(True) def restoreSettingsConsole(self): storedTabScripts = self.settings.value("pythonConsole/tabScripts", []) self.tabListScript = storedTabScripts self.splitter.restoreState( self.settings.value("pythonConsole/splitterConsole", QByteArray())) self.splitterEditor.restoreState( self.settings.value("pythonConsole/splitterEditor", QByteArray())) self.splitterObj.restoreState( self.settings.value("pythonConsole/splitterObj", QByteArray()))
class QGISEducation: def __init__(self, iface): # Save reference to the QGIS interface self.iface = iface self.constants = TerreImageConstant() self.constants.iface = self.iface self.constants.canvas = self.iface.mapCanvas() self.constants.legendInterface = self.iface.legendInterface() def initGui(self): """ Initialisation on the widget interface """ # Create action that will start plugin configuration self.action = QAction( QIcon(":/plugins/qgiseducation/img/icon.png"), u"Terre Image", self.iface.mainWindow()) self.action.setWhatsThis("Terre Image") # connect the action to the run method self.action.triggered.connect(self.run) self.aboutAction = QAction(QIcon(":/plugins/DockableMirrorMap/icons/about.png"), "About", self.iface.mainWindow()) QObject.connect(self.aboutAction, SIGNAL("triggered()"), self.about) # Add toolbar button and menu item self.iface.addToolBarIcon(self.action) self.iface.addPluginToMenu(u"&TerreImage", self.action) self.iface.addPluginToMenu("TerreImage", self.aboutAction) self.qgisedudockwidget = None self.dockOpened = False self.educationWidget = None QObject.connect(self.iface, SIGNAL("projectRead()"), self.onProjectLoaded) QObject.connect(QgsProject.instance(), SIGNAL("writeProject(QDomDocument &)"), self.onWriteProject) QObject.connect(self.iface, SIGNAL("newProjectCreated()"), self.newProject) def do_display_one_band(self, who, qgis_layer, working_directory, mirror_tool): logger.debug("who {}".format(who)) # manage_QGIS.display_one_band(self.qgis_education_manager.layer, who, self.iface) if qgis_layer: my_process = TerreImageDisplay(self.iface, working_directory, ProcessingManager().working_layer, mirror_tool, who, None, qgis_layer) else: my_process = TerreImageDisplay(self.iface, working_directory, ProcessingManager().working_layer, mirror_tool, who) # ProcessingManager().add_processing(my_process) self.educationWidget.set_combobox_histograms() def unload(self): """ Defines the unload of the plugin """ self.unload_interface() # Remove the plugin menu item and icon self.iface.removePluginMenu(u"&TerreImage", self.action) self.iface.removeToolBarIcon(self.action) def unload_interface(self): if self.qgisedudockwidget is not None: self.qgisedudockwidget.close() if self.educationWidget is not None: self.educationWidget.disconnectP() # run method that performs all the real work def run(self): """ Defines the behavior of the plugin """ timeBegin = time.time() # self.educationWidget.set_working_message(True) self.iface.newProject(True) # self.qgis_education_manager = TerreImageManager(self.iface) # _, bands = self.qgis_education_manager.set_current_layer( ) _, bands, working_dir = terre_image_utils.set_current_layer(self.iface) timeEnd = time.time() timeExec = timeEnd - timeBegin logger.info("temps de chargement: {}".format(timeExec)) self.show_education_widget(bands, working_dir) # self.educationWidget.set_working_message(False) def show_education_widget(self, bands, working_dir): if ProcessingManager().working_layer and bands: if not self.dockOpened: # create the widget to display information self.educationWidget = QGISEducationWidget(self.iface, working_dir) QObject.connect(self.educationWidget, SIGNAL("terminated()"), self.unload_interface) # self.educationWidget.qgis_education_manager = self.qgis_education_manager # create the dockwidget with the correct parent and add the valuewidget self.qgisedudockwidget = Terre_Image_Main_Dock_widget("Terre Image", self.iface.mainWindow(), self.iface) self.qgisedudockwidget.setObjectName("Terre Image") self.qgisedudockwidget.setWidget(self.educationWidget) QObject.connect(self.qgisedudockwidget, SIGNAL("closed(PyQt_PyObject)"), self.close_dock) # add the dockwidget to iface self.iface.addDockWidget(Qt.RightDockWidgetArea, self.qgisedudockwidget) self.educationWidget.set_comboBox_sprectral_band_display() text = "Plan R <- BS_PIR \nPlan V <- BS_R \nPlan B <- BS_V" self.qgisedudockwidget.show() self.dockOpened = True def about(self): from terre_image_about import DlgAbout DlgAbout(self.iface.mainWindow()).exec_() def close_dock(self, object): self.qgisedudockwidget = None self.dockOpened = False self.educationWidget = None if self.iface.legendInterface().layers() != []: self.iface.newProject() def newProject(self): for item in self.iface.mapCanvas().scene().items(): if isinstance(item, QgsRubberBand): item.reset(QGis.Point) if self.educationWidget is not None: self.educationWidget.disconnect_interface() if self.qgisedudockwidget is not None: self.qgisedudockwidget.close() self.educationWidget.disconnectP() self.dockOpened = False self.qgisedudockwidget = None self.dockOpened = False self.educationWidget = None def onWriteProject(self, domproject): if ProcessingManager().working_layer is None: return # QgsProject.instance().writeEntry( "QGISEducation", "/working_layer", self.qgis_education_manager.layer.source_file ) # # write band orders # QgsProject.instance().writeEntry( "QGISEducation", "/working_layer_bands", str(self.qgis_education_manager.layer.bands) ) # logger.debug( str(self.qgis_education_manager.layer.bands) ) # QgsProject.instance().writeEntry( "QGISEducation", "/working_layer_type", self.qgis_education_manager.layer.type ) # QgsProject.instance().writeEntry( "QGISEducation", "/working_directory", self.qgis_education_manager.working_directory ) QgsProject.instance().writeEntry("QGISEducation", "/working_layer", ProcessingManager().working_layer.source_file) # write band orders QgsProject.instance().writeEntry("QGISEducation", "/working_layer_bands", str(ProcessingManager().working_layer.bands)) logger.debug("{}".format(ProcessingManager().working_layer.bands)) QgsProject.instance().writeEntry("QGISEducation", "/working_layer_type", ProcessingManager().working_layer.type) QgsProject.instance().writeEntry("QGISEducation", "/working_directory", self.educationWidget.qgis_education_manager.working_directory) p = [] for process in ProcessingManager().get_processings(): p.append((process.processing_name, process.output_working_layer.get_source())) # logger.debug("process{}".format(p)) QgsProject.instance().writeEntry("QGISEducation", "/process", str(p)) QgsProject.instance().writeEntry("QGISEducation", "/index_group", self.constants.index_group) if "Angle Spectral" in ProcessingManager().get_processings_name(): # delete rubberband for item in self.iface.mapCanvas().scene().items(): # item is a rubberband if isinstance(item, QgsRubberBand): # get point if item.size() > 0: point = item.getPoint(0) # logger.debug(point) QgsProject.instance().writeEntryDouble("QGISEducation", "/angle_spectral_point_x", point.x()) QgsProject.instance().writeEntryDouble("QGISEducation", "/angle_spectral_point_y", point.y()) p = TerreImageParamaters() if p.is_complete(): QgsProject.instance().writeEntryDouble("QGISEducation", "/red_x_min", p.red_min) QgsProject.instance().writeEntryDouble("QGISEducation", "/red_x_max", p.red_max) QgsProject.instance().writeEntryDouble("QGISEducation", "/green_x_min", p.green_min) QgsProject.instance().writeEntryDouble("QGISEducation", "/green_x_max", p.green_max) QgsProject.instance().writeEntryDouble("QGISEducation", "/blue_x_min", p.blue_min) QgsProject.instance().writeEntryDouble("QGISEducation", "/blue_x_max", p.blue_max) def onProjectLoaded(self): # does not work stops the project reading. # should desactivate all interface and read the project again # self.newProject( True ) # restore mirrors? wl, ok = QgsProject.instance().readEntry("QGISEducation", "/working_layer") if not ok or wl == "": pass if not wl == "": bands, ok = QgsProject.instance().readEntry("QGISEducation", "/working_layer_bands") logger.debug("is ok" + str(ok)) logger.debug(bands) # working_layer = WorkingLayer(wl, None, bands) # TODO interpreter bands type, ok = QgsProject.instance().readEntry("QGISEducation", "/working_layer_type") working_dir, ok = QgsProject.instance().readEntry("QGISEducation", "/working_directory") layer, bands = terre_image_utils.restore_working_layer(wl, eval(bands), type) ProcessingManager().working_layer = layer self.show_education_widget(bands, working_dir) # self.qgis_education_manager = TerreImageManager( self.iface ) # self.qgis_education_manager.restore_processing_manager(wl, eval(bands), type, working_dir) # if self.qgis_education_manager: process, ok = QgsProject.instance().readEntry("QGISEducation", "/process") logger.debug(eval(process)) index_group, ok = QgsProject.instance().readDoubleEntry("QGISEducation", "/index_group") self.constants.index_group = int(float(index_group)) process = eval(process) for qgis_layer in self.iface.legendInterface().layers(): # logger.debug("layer loading {}".format(qgis_layer.name())) if qgis_layer.name() in [ "NDVI", "NDTI", "Indice de brillance", "KMEANS" ]: process = TerreImageProcessing(self.iface, working_dir, ProcessingManager().working_layer, self.educationWidget.qgis_education_manager.mirror_map_tool, qgis_layer.name(), None, qgis_layer) elif "Angle Spectral" in qgis_layer.name(): process = TerreImageProcessing(self.iface, working_dir, ProcessingManager().working_layer, self.educationWidget.qgis_education_manager.mirror_map_tool, qgis_layer.name(), qgis_layer.source(), qgis_layer) # ProcessingManager().add_processing(process) elif "couleur_naturelles" in qgis_layer.name(): try: self.do_display_one_band('nat', qgis_layer, working_dir, self.educationWidget.qgis_education_manager.mirror_map_tool) except AttributeError: QMessageBox.warning(None , "Erreur", u'Le projet ne peut être lu. Essayez de créer un projet vierge, puis de réouvrir le projet souhaité.', QMessageBox.Ok) # self.newProject( ) return None # ProcessingManager().add_display( process ) else: corres = { 'red':"_bande_rouge", 'green':"_bande_verte", 'blue':"_bande_bleue", 'pir':"_bande_pir", 'mir':"_bande_mir", "nat":"_couleurs_naturelles" } result = [x for x in corres if qgis_layer.name().endswith(corres[x])] # logger.debug(result) if result: # logger.debug("the couleur{}".format(result[0])) try: self.do_display_one_band(result[0], qgis_layer, working_dir, self.educationWidget.qgis_education_manager.mirror_map_tool) except AttributeError: QMessageBox.warning(None , "Erreur", u'Le projet ne peut être lu. Essayez de créer un projet vierge, puis de réouvrir le projet souhaité.', QMessageBox.Ok) # self.newProject( ) return None # ProcessingManager().add_display( process ) angle_spectral_point_x, ok_x = QgsProject.instance().readDoubleEntry("QGISEducation", "/angle_spectral_point_x") angle_spectral_point_y, ok_y = QgsProject.instance().readDoubleEntry("QGISEducation", "/angle_spectral_point_y") # logger.debug("angle_spectral_point_x {}, angle_spectral_point_y{}".format(angle_spectral_point_x, angle_spectral_point_y)) if ok_x and ok_y: # logger.debug("angle_spectral_point_x {}, angle_spectral_point_y{}".format(angle_spectral_point_x, angle_spectral_point_y)) p = ProcessingManager().processing_from_name("Angle Spectral") if p: rubberband = p[0].rubberband rubberband.setWidth(10) rubberband.setColor(QColor(Qt.yellow)) rubberband.addPoint(QgsPoint(float(angle_spectral_point_x), float(angle_spectral_point_y))) p = TerreImageParamaters() p.red_min = QgsProject.instance().readDoubleEntry("QGISEducation", "/red_x_min")[0] p.red_max = QgsProject.instance().readDoubleEntry("QGISEducation", "/red_x_max")[0] p.green_min = QgsProject.instance().readDoubleEntry("QGISEducation", "/green_x_min")[0] p.green_max = QgsProject.instance().readDoubleEntry("QGISEducation", "/green_x_max")[0] p.blue_min = QgsProject.instance().readDoubleEntry("QGISEducation", "/blue_x_min")[0] p.blue_max = QgsProject.instance().readDoubleEntry("QGISEducation", "/blue_x_max")[0] self.educationWidget.set_combobox_histograms() self.iface.mapCanvas().refresh() self.iface.mapCanvas().repaint()
class OWPaintData(widget.OWWidget): TOOLS = [ ("Brush", "Create multiple instances", AirBrushTool, _i("brush.svg")), ("Put", "Put individual instances", PutInstanceTool, _i("put.svg")), ("Select", "Select and move instances", SelectTool, _i("select-transparent_42px.png")), ("Jitter", "Jitter instances", JitterTool, _i("jitter.svg")), ("Magnet", "Attract multiple instances", MagnetTool, _i("magnet.svg")), ("Zoom", "Zoom", ZoomTool, _i("Dlg_zoom2.png")) ] name = "Paint Data" description = "Create data by painting data points in the plane." long_description = "" icon = "icons/PaintData.svg" priority = 10 keywords = ["data", "paint", "create"] outputs = [("Data", Orange.data.Table)] autocommit = Setting(False) attr1 = Setting("x") attr2 = Setting("y") brushRadius = Setting(75) density = Setting(7) def __init__(self, parent=None): super().__init__(parent) self.data = None self.current_tool = None self._selected_indices = None self._scatter_item = None self.labels = ["Class-1", "Class-2"] self.undo_stack = QtGui.QUndoStack(self) self.class_model = ColoredListModel( self.labels, self, flags=QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable) self.class_model.dataChanged.connect(self._class_value_changed) self.class_model.rowsInserted.connect(self._class_count_changed) self.class_model.rowsRemoved.connect(self._class_count_changed) self.tools_cache = {} self._init_ui() self.data = numpy.zeros((0, 3)) self.colors = colorpalette.ColorPaletteGenerator(10) def _init_ui(self): namesBox = gui.widgetBox(self.controlArea, "Names") gui.lineEdit(namesBox, self, "attr1", "Variable X ", controlWidth=80, orientation="horizontal", enterPlaceholder=True, callback=self._attr_name_changed) gui.lineEdit(namesBox, self, "attr2", "Variable Y ", controlWidth=80, orientation="horizontal", enterPlaceholder=True, callback=self._attr_name_changed) gui.separator(namesBox) gui.widgetLabel(namesBox, "Class labels") self.classValuesView = listView = QListView( selectionMode=QListView.SingleSelection, sizePolicy=QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Maximum) ) listView.setModel(self.class_model) itemmodels.select_row(listView, 0) namesBox.layout().addWidget(listView) addClassLabel = QAction( "+", self, toolTip="Add new class label", triggered=self.add_new_class_label ) self.removeClassLabel = QAction( unicodedata.lookup("MINUS SIGN"), self, toolTip="Remove selected class label", triggered=self.remove_selected_class_label ) actionsWidget = itemmodels.ModelActionsWidget( [addClassLabel, self.removeClassLabel], self ) actionsWidget.layout().addStretch(10) actionsWidget.layout().setSpacing(1) namesBox.layout().addWidget(actionsWidget) tBox = gui.widgetBox(self.controlArea, "Tools", addSpace=True) buttonBox = gui.widgetBox(tBox, orientation="horizontal") toolsBox = gui.widgetBox(buttonBox, orientation=QtGui.QGridLayout()) self.toolActions = QtGui.QActionGroup(self) self.toolActions.setExclusive(True) for i, (name, tooltip, tool, icon) in enumerate(self.TOOLS): action = QAction( name, self, toolTip=tooltip, checkable=True, icon=QIcon(icon), ) action.triggered.connect(partial(self.set_current_tool, tool)) button = QtGui.QToolButton( iconSize=QSize(24, 24), toolButtonStyle=Qt.ToolButtonTextUnderIcon, sizePolicy=QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) ) button.setDefaultAction(action) toolsBox.layout().addWidget(button, i / 3, i % 3) self.toolActions.addAction(action) for column in range(3): toolsBox.layout().setColumnMinimumWidth(column, 10) toolsBox.layout().setColumnStretch(column, 1) undo = self.undo_stack.createUndoAction(self) redo = self.undo_stack.createRedoAction(self) undo.setShortcut(QtGui.QKeySequence.Undo) redo.setShortcut(QtGui.QKeySequence.Redo) self.addActions([undo, redo]) gui.separator(tBox) indBox = gui.indentedBox(tBox, sep=8) form = QtGui.QFormLayout( formAlignment=Qt.AlignLeft, labelAlignment=Qt.AlignLeft, fieldGrowthPolicy=QtGui.QFormLayout.AllNonFixedFieldsGrow ) indBox.layout().addLayout(form) slider = gui.hSlider( indBox, self, "brushRadius", minValue=1, maxValue=100, createLabel=False ) form.addRow("Radius", slider) slider = gui.hSlider( indBox, self, "density", None, minValue=1, maxValue=100, createLabel=False ) form.addRow("Intensity", slider) gui.rubber(self.controlArea) gui.auto_commit(self.controlArea, self, "autocommit", "Send", "Send on change") # main area GUI viewbox = PaintViewBox() self.plotview = pg.PlotWidget(background="w", viewBox=viewbox) self.plot = self.plotview.getPlotItem() axis_color = self.palette().color(QtGui.QPalette.Text) axis_pen = QtGui.QPen(axis_color) tickfont = QtGui.QFont(self.font()) tickfont.setPixelSize(max(int(tickfont.pixelSize() * 2 // 3), 11)) axis = self.plot.getAxis("bottom") axis.setLabel(self.attr1) axis.setPen(axis_pen) axis.setTickFont(tickfont) axis = self.plot.getAxis("left") axis.setLabel(self.attr2) axis.setPen(axis_pen) axis.setTickFont(tickfont) self.plot.setRange(xRange=(0.0, 1.0), yRange=(0.0, 1.0), disableAutoRange=True) self.mainArea.layout().addWidget(self.plotview) # enable brush tool self.toolActions.actions()[0].setChecked(True) self.set_current_tool(self.TOOLS[0][2]) def add_new_class_label(self): labels = ("Class-%i" % i for i in count(1)) labels = filter(lambda label: label not in self.class_model, labels) newlabel = next(labels) command = SimpleUndoCommand( lambda: self.class_model.append(newlabel), lambda: self.class_model.__delitem__(-1) ) self.undo_stack.push(command) def remove_selected_class_label(self): index = self.selected_class_label() if index is None: return label = self.class_model[index] mask = self.data[:, 2] == index move_mask = self.data[~mask][:, 2] > index self.undo_stack.beginMacro("Delete class label") self.undo_stack.push(UndoCommand(DeleteIndices(mask), self)) self.undo_stack.push(UndoCommand(Move((move_mask, 2), -1), self)) self.undo_stack.push( SimpleUndoCommand(lambda: self.class_model.__delitem__(index), lambda: self.class_model.insert(index, label))) self.undo_stack.endMacro() newindex = min(max(index - 1, 0), len(self.class_model) - 1) itemmodels.select_row(self.classValuesView, newindex) def _class_count_changed(self): self.labels = list(self.class_model) self.removeClassLabel.setEnabled(len(self.class_model) > 1) if self.selected_class_label() is None: itemmodels.select_row(self.classValuesView, 0) def _class_value_changed(self, index, _): index = index.row() newvalue = self.class_model[index] oldvalue = self.labels[index] if newvalue != oldvalue: self.labels[index] = newvalue # command = Command( # lambda: self.class_model.__setitem__(index, newvalue), # lambda: self.class_model.__setitem__(index, oldvalue), # ) # self.undo_stack.push(command) def selected_class_label(self): rows = self.classValuesView.selectedIndexes() if rows: return rows[0].row() else: return None def set_current_tool(self, tool): if self.current_tool is not None: self.current_tool.deactivate() self.current_tool.editingStarted.disconnect( self._on_editing_started) self.current_tool.editingFinished.disconnect( self._on_editing_finished) self.current_tool = None self.plot.getViewBox().tool = None if tool not in self.tools_cache: newtool = tool(self, self.plot) newtool.editingFinished.connect(self.invalidate) self.tools_cache[tool] = newtool newtool.issueCommand.connect(self._add_command) self._selected_region = QRectF() self.current_tool = tool = self.tools_cache[tool] self.plot.getViewBox().tool = tool tool.editingStarted.connect(self._on_editing_started) tool.editingFinished.connect(self._on_editing_finished) tool.activate() def _on_editing_started(self): self.undo_stack.beginMacro("macro") def _on_editing_finished(self): self.undo_stack.endMacro() def execute(self, command): if isinstance(command, (Append, DeleteIndices, Insert, Move)): if isinstance(command, (DeleteIndices, Insert)): self._selected_indices = None if isinstance(self.current_tool, SelectTool): self.current_tool._reset() self.data, undo = transform(command, self.data) self._replot() return undo else: assert False, "Non normalized command" def _add_command(self, cmd): name = "Name" if isinstance(cmd, Append): cls = self.selected_class_label() points = numpy.array([[p.x(), p.y(), cls] for p in cmd.points]) self.undo_stack.push(UndoCommand(Append(points), self, text=name)) elif isinstance(cmd, Move): self.undo_stack.push(UndoCommand(cmd, self, text=name)) elif isinstance(cmd, SelectRegion): indices = [i for i, (x, y) in enumerate(self.data[:, :2]) if cmd.region.contains(QPointF(x, y))] indices = numpy.array(indices, dtype=int) self._selected_indices = indices elif isinstance(cmd, DeleteSelection): indices = self._selected_indices if indices is not None and indices.size: self.undo_stack.push( UndoCommand(DeleteIndices(indices), self, text="Delete") ) elif isinstance(cmd, MoveSelection): indices = self._selected_indices if indices is not None and indices.size: self.undo_stack.push( UndoCommand( Move((self._selected_indices, slice(0, 2)), numpy.array([cmd.delta.x(), cmd.delta.y()])), self, text="Move") ) elif isinstance(cmd, DeleteIndices): self.undo_stack.push(UndoCommand(cmd, self, text="Delete")) elif isinstance(cmd, Insert): self.undo_stack.push(UndoCommand(cmd, self)) elif isinstance(cmd, AirBrush): data = create_data(cmd.pos.x(), cmd.pos.y(), self.brushRadius / 1000, 1 + self.density / 20, cmd.rstate) self._add_command(Append([QPointF(*p) for p in zip(*data.T)])) elif isinstance(cmd, Jitter): point = numpy.array([cmd.pos.x(), cmd.pos.y()]) delta = - apply_jitter(self.data[:, :2], point, self.density / 100.0, 0, cmd.rstate) self._add_command(Move((..., slice(0, 2)), delta)) elif isinstance(cmd, Magnet): point = numpy.array([cmd.pos.x(), cmd.pos.y()]) delta = - apply_attractor(self.data[:, :2], point, self.density / 100.0, 0) self._add_command(Move((..., slice(0, 2)), delta)) else: assert False, "unreachable" def _replot(self): def pen(color): pen = QPen(color, 1) pen.setCosmetic(True) return pen if self._scatter_item is not None: self.plot.removeItem(self._scatter_item) self._scatter_item = None nclasses = len(self.class_model) pens = [pen(self.colors[i]) for i in range(nclasses)] self._scatter_item = pg.ScatterPlotItem( self.data[:, 0], self.data[:, 1], symbol="+", pen=[pens[int(ci)] for ci in self.data[:, 2]] ) self.plot.addItem(self._scatter_item) def _attr_name_changed(self): self.plot.getAxis("bottom").setLabel(self.attr1) self.plot.getAxis("left").setLabel(self.attr2) self.invalidate() def invalidate(self): self.commit() def commit(self): X, Y = self.data[:, :2], self.data[:, 2] attrs = (Orange.data.ContinuousVariable(self.attr1), Orange.data.ContinuousVariable(self.attr2)) if len(self.class_model) > 1: domain = Orange.data.Domain( attrs, Orange.data.DiscreteVariable( "Class", values=list(self.class_model)) ) data = Orange.data.Table.from_numpy(domain, X, Y) else: domain = Orange.data.Domain(attrs) data = Orange.data.Table.from_numpy(domain, X) self.send("Data", data) def sizeHint(self): sh = super().sizeHint() return sh.expandedTo(QSize(1200, 800)) def onDeleteWidget(self): self.plot.clear()
def __init__(self, parent=None): QWidget.__init__(self, parent) self.setWindowTitle( QCoreApplication.translate("PythonConsole", "Python Console")) self.settings = QSettings() self.shell = ShellScintilla(self) self.setFocusProxy(self.shell) self.shellOut = ShellOutputScintilla(self) self.tabEditorWidget = EditorTabWidget(self) ##------------ UI ------------------------------- self.splitterEditor = QSplitter(self) self.splitterEditor.setOrientation(Qt.Horizontal) self.splitterEditor.setHandleWidth(6) self.splitterEditor.setChildrenCollapsible(True) self.shellOutWidget = QWidget(self) self.shellOutWidget.setLayout(QVBoxLayout()) self.shellOutWidget.layout().setContentsMargins(0, 0, 0, 0) self.shellOutWidget.layout().addWidget(self.shellOut) self.splitter = QSplitter(self.splitterEditor) self.splitter.setOrientation(Qt.Vertical) self.splitter.setHandleWidth(3) self.splitter.setChildrenCollapsible(False) self.splitter.addWidget(self.shellOutWidget) self.splitter.addWidget(self.shell) #self.splitterEditor.addWidget(self.tabEditorWidget) self.splitterObj = QSplitter(self.splitterEditor) self.splitterObj.setHandleWidth(3) self.splitterObj.setOrientation(Qt.Horizontal) #self.splitterObj.setSizes([0, 0]) #self.splitterObj.setStretchFactor(0, 1) self.widgetEditor = QWidget(self.splitterObj) self.widgetFind = QWidget(self) self.listClassMethod = QTreeWidget(self.splitterObj) self.listClassMethod.setColumnCount(2) objInspLabel = QCoreApplication.translate("PythonConsole", "Object Inspector") self.listClassMethod.setHeaderLabels([objInspLabel, '']) self.listClassMethod.setColumnHidden(1, True) self.listClassMethod.setAlternatingRowColors(True) #self.splitterEditor.addWidget(self.widgetEditor) #self.splitterObj.addWidget(self.listClassMethod) #self.splitterObj.addWidget(self.widgetEditor) # Hide side editor on start up self.splitterObj.hide() self.listClassMethod.hide() # Hide search widget on start up self.widgetFind.hide() sizes = self.splitter.sizes() self.splitter.setSizes(sizes) ##----------------Restore Settings------------------------------------ self.restoreSettingsConsole() ##------------------Toolbar Editor------------------------------------- ## Action for Open File openFileBt = QCoreApplication.translate("PythonConsole", "Open file") self.openFileButton = QAction(self) self.openFileButton.setCheckable(False) self.openFileButton.setEnabled(True) self.openFileButton.setIcon( QgsApplication.getThemeIcon("console/iconOpenConsole.png")) self.openFileButton.setMenuRole(QAction.PreferencesRole) self.openFileButton.setIconVisibleInMenu(True) self.openFileButton.setToolTip(openFileBt) self.openFileButton.setText(openFileBt) openExtEditorBt = QCoreApplication.translate( "PythonConsole", "Open in external editor") self.openInEditorButton = QAction(self) self.openInEditorButton.setCheckable(False) self.openInEditorButton.setEnabled(True) self.openInEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconShowEditorConsole.png")) self.openInEditorButton.setMenuRole(QAction.PreferencesRole) self.openInEditorButton.setIconVisibleInMenu(True) self.openInEditorButton.setToolTip(openExtEditorBt) self.openInEditorButton.setText(openExtEditorBt) ## Action for Save File saveFileBt = QCoreApplication.translate("PythonConsole", "Save") self.saveFileButton = QAction(self) self.saveFileButton.setCheckable(False) self.saveFileButton.setEnabled(False) self.saveFileButton.setIcon( QgsApplication.getThemeIcon("console/iconSaveConsole.png")) self.saveFileButton.setMenuRole(QAction.PreferencesRole) self.saveFileButton.setIconVisibleInMenu(True) self.saveFileButton.setToolTip(saveFileBt) self.saveFileButton.setText(saveFileBt) ## Action for Save File As saveAsFileBt = QCoreApplication.translate("PythonConsole", "Save As...") self.saveAsFileButton = QAction(self) self.saveAsFileButton.setCheckable(False) self.saveAsFileButton.setEnabled(True) self.saveAsFileButton.setIcon( QgsApplication.getThemeIcon("console/iconSaveAsConsole.png")) self.saveAsFileButton.setMenuRole(QAction.PreferencesRole) self.saveAsFileButton.setIconVisibleInMenu(True) self.saveAsFileButton.setToolTip(saveAsFileBt) self.saveAsFileButton.setText(saveAsFileBt) ## Action Cut cutEditorBt = QCoreApplication.translate("PythonConsole", "Cut") self.cutEditorButton = QAction(self) self.cutEditorButton.setCheckable(False) self.cutEditorButton.setEnabled(True) self.cutEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconCutEditorConsole.png")) self.cutEditorButton.setMenuRole(QAction.PreferencesRole) self.cutEditorButton.setIconVisibleInMenu(True) self.cutEditorButton.setToolTip(cutEditorBt) self.cutEditorButton.setText(cutEditorBt) ## Action Copy copyEditorBt = QCoreApplication.translate("PythonConsole", "Copy") self.copyEditorButton = QAction(self) self.copyEditorButton.setCheckable(False) self.copyEditorButton.setEnabled(True) self.copyEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconCopyEditorConsole.png")) self.copyEditorButton.setMenuRole(QAction.PreferencesRole) self.copyEditorButton.setIconVisibleInMenu(True) self.copyEditorButton.setToolTip(copyEditorBt) self.copyEditorButton.setText(copyEditorBt) ## Action Paste pasteEditorBt = QCoreApplication.translate("PythonConsole", "Paste") self.pasteEditorButton = QAction(self) self.pasteEditorButton.setCheckable(False) self.pasteEditorButton.setEnabled(True) self.pasteEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconPasteEditorConsole.png")) self.pasteEditorButton.setMenuRole(QAction.PreferencesRole) self.pasteEditorButton.setIconVisibleInMenu(True) self.pasteEditorButton.setToolTip(pasteEditorBt) self.pasteEditorButton.setText(pasteEditorBt) ## Action Run Script (subprocess) runScriptEditorBt = QCoreApplication.translate("PythonConsole", "Run script") self.runScriptEditorButton = QAction(self) self.runScriptEditorButton.setCheckable(False) self.runScriptEditorButton.setEnabled(True) self.runScriptEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconRunScriptConsole.png")) self.runScriptEditorButton.setMenuRole(QAction.PreferencesRole) self.runScriptEditorButton.setIconVisibleInMenu(True) self.runScriptEditorButton.setToolTip(runScriptEditorBt) self.runScriptEditorButton.setText(runScriptEditorBt) ## Action Run Script (subprocess) commentEditorBt = QCoreApplication.translate("PythonConsole", "Comment") self.commentEditorButton = QAction(self) self.commentEditorButton.setCheckable(False) self.commentEditorButton.setEnabled(True) self.commentEditorButton.setIcon( QgsApplication.getThemeIcon( "console/iconCommentEditorConsole.png")) self.commentEditorButton.setMenuRole(QAction.PreferencesRole) self.commentEditorButton.setIconVisibleInMenu(True) self.commentEditorButton.setToolTip(commentEditorBt) self.commentEditorButton.setText(commentEditorBt) ## Action Run Script (subprocess) uncommentEditorBt = QCoreApplication.translate("PythonConsole", "Uncomment") self.uncommentEditorButton = QAction(self) self.uncommentEditorButton.setCheckable(False) self.uncommentEditorButton.setEnabled(True) self.uncommentEditorButton.setIcon( QgsApplication.getThemeIcon( "console/iconUncommentEditorConsole.png")) self.uncommentEditorButton.setMenuRole(QAction.PreferencesRole) self.uncommentEditorButton.setIconVisibleInMenu(True) self.uncommentEditorButton.setToolTip(uncommentEditorBt) self.uncommentEditorButton.setText(uncommentEditorBt) ## Action for Object browser objList = QCoreApplication.translate("PythonConsole", "Object Inspector") self.objectListButton = QAction(self) self.objectListButton.setCheckable(True) self.objectListButton.setEnabled( self.settings.value("pythonConsole/enableObjectInsp", False, type=bool)) self.objectListButton.setIcon( QgsApplication.getThemeIcon("console/iconClassBrowserConsole.png")) self.objectListButton.setMenuRole(QAction.PreferencesRole) self.objectListButton.setIconVisibleInMenu(True) self.objectListButton.setToolTip(objList) self.objectListButton.setText(objList) ## Action for Find text findText = QCoreApplication.translate("PythonConsole", "Find Text") self.findTextButton = QAction(self) self.findTextButton.setCheckable(True) self.findTextButton.setEnabled(True) self.findTextButton.setIcon( QgsApplication.getThemeIcon("console/iconSearchEditorConsole.png")) self.findTextButton.setMenuRole(QAction.PreferencesRole) self.findTextButton.setIconVisibleInMenu(True) self.findTextButton.setToolTip(findText) self.findTextButton.setText(findText) ##----------------Toolbar Console------------------------------------- ## Action Show Editor showEditor = QCoreApplication.translate("PythonConsole", "Show editor") self.showEditorButton = QAction(self) self.showEditorButton.setEnabled(True) self.showEditorButton.setCheckable(True) self.showEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconShowEditorConsole.png")) self.showEditorButton.setMenuRole(QAction.PreferencesRole) self.showEditorButton.setIconVisibleInMenu(True) self.showEditorButton.setToolTip(showEditor) self.showEditorButton.setText(showEditor) ## Action for Clear button clearBt = QCoreApplication.translate("PythonConsole", "Clear console") self.clearButton = QAction(self) self.clearButton.setCheckable(False) self.clearButton.setEnabled(True) self.clearButton.setIcon( QgsApplication.getThemeIcon("console/iconClearConsole.png")) self.clearButton.setMenuRole(QAction.PreferencesRole) self.clearButton.setIconVisibleInMenu(True) self.clearButton.setToolTip(clearBt) self.clearButton.setText(clearBt) ## Action for settings optionsBt = QCoreApplication.translate("PythonConsole", "Settings") self.optionsButton = QAction(self) self.optionsButton.setCheckable(False) self.optionsButton.setEnabled(True) self.optionsButton.setIcon( QgsApplication.getThemeIcon("console/iconSettingsConsole.png")) self.optionsButton.setMenuRole(QAction.PreferencesRole) self.optionsButton.setIconVisibleInMenu(True) self.optionsButton.setToolTip(optionsBt) self.optionsButton.setText(optionsBt) ## Action menu for class actionClassBt = QCoreApplication.translate("PythonConsole", "Import Class") self.actionClass = QAction(self) self.actionClass.setCheckable(False) self.actionClass.setEnabled(True) self.actionClass.setIcon( QgsApplication.getThemeIcon("console/iconClassConsole.png")) self.actionClass.setMenuRole(QAction.PreferencesRole) self.actionClass.setIconVisibleInMenu(True) self.actionClass.setToolTip(actionClassBt) self.actionClass.setText(actionClassBt) ## Import Processing class loadProcessingBt = QCoreApplication.translate( "PythonConsole", "Import Processing class") self.loadProcessingButton = QAction(self) self.loadProcessingButton.setCheckable(False) self.loadProcessingButton.setEnabled(True) self.loadProcessingButton.setIcon( QgsApplication.getThemeIcon("console/iconProcessingConsole.png")) self.loadProcessingButton.setMenuRole(QAction.PreferencesRole) self.loadProcessingButton.setIconVisibleInMenu(True) self.loadProcessingButton.setToolTip(loadProcessingBt) self.loadProcessingButton.setText(loadProcessingBt) ## Import QtCore class loadQtCoreBt = QCoreApplication.translate("PythonConsole", "Import PyQt.QtCore class") self.loadQtCoreButton = QAction(self) self.loadQtCoreButton.setCheckable(False) self.loadQtCoreButton.setEnabled(True) self.loadQtCoreButton.setIcon( QgsApplication.getThemeIcon("console/iconQtCoreConsole.png")) self.loadQtCoreButton.setMenuRole(QAction.PreferencesRole) self.loadQtCoreButton.setIconVisibleInMenu(True) self.loadQtCoreButton.setToolTip(loadQtCoreBt) self.loadQtCoreButton.setText(loadQtCoreBt) ## Import QtGui class loadQtGuiBt = QCoreApplication.translate("PythonConsole", "Import PyQt.QtGui class") self.loadQtGuiButton = QAction(self) self.loadQtGuiButton.setCheckable(False) self.loadQtGuiButton.setEnabled(True) self.loadQtGuiButton.setIcon( QgsApplication.getThemeIcon("console/iconQtGuiConsole.png")) self.loadQtGuiButton.setMenuRole(QAction.PreferencesRole) self.loadQtGuiButton.setIconVisibleInMenu(True) self.loadQtGuiButton.setToolTip(loadQtGuiBt) self.loadQtGuiButton.setText(loadQtGuiBt) ## Action for Run script runBt = QCoreApplication.translate("PythonConsole", "Run command") self.runButton = QAction(self) self.runButton.setCheckable(False) self.runButton.setEnabled(True) self.runButton.setIcon( QgsApplication.getThemeIcon("console/iconRunConsole.png")) self.runButton.setMenuRole(QAction.PreferencesRole) self.runButton.setIconVisibleInMenu(True) self.runButton.setToolTip(runBt) self.runButton.setText(runBt) ## Help action helpBt = QCoreApplication.translate("PythonConsole", "Help") self.helpButton = QAction(self) self.helpButton.setCheckable(False) self.helpButton.setEnabled(True) self.helpButton.setIcon( QgsApplication.getThemeIcon("console/iconHelpConsole.png")) self.helpButton.setMenuRole(QAction.PreferencesRole) self.helpButton.setIconVisibleInMenu(True) self.helpButton.setToolTip(helpBt) self.helpButton.setText(helpBt) self.toolBar = QToolBar() self.toolBar.setEnabled(True) self.toolBar.setFocusPolicy(Qt.NoFocus) self.toolBar.setContextMenuPolicy(Qt.DefaultContextMenu) self.toolBar.setLayoutDirection(Qt.LeftToRight) self.toolBar.setIconSize(QSize(16, 16)) self.toolBar.setMovable(False) self.toolBar.setFloatable(False) self.toolBar.addAction(self.clearButton) self.toolBar.addAction(self.actionClass) self.toolBar.addAction(self.runButton) self.toolBar.addSeparator() self.toolBar.addAction(self.showEditorButton) self.toolBar.addSeparator() self.toolBar.addAction(self.optionsButton) self.toolBar.addAction(self.helpButton) self.toolBarEditor = QToolBar() self.toolBarEditor.setEnabled(False) self.toolBarEditor.setFocusPolicy(Qt.NoFocus) self.toolBarEditor.setContextMenuPolicy(Qt.DefaultContextMenu) self.toolBarEditor.setLayoutDirection(Qt.LeftToRight) self.toolBarEditor.setIconSize(QSize(16, 16)) self.toolBarEditor.setMovable(False) self.toolBarEditor.setFloatable(False) self.toolBarEditor.addAction(self.openFileButton) self.toolBarEditor.addAction(self.openInEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.saveFileButton) self.toolBarEditor.addAction(self.saveAsFileButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.runScriptEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.findTextButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.cutEditorButton) self.toolBarEditor.addAction(self.copyEditorButton) self.toolBarEditor.addAction(self.pasteEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.commentEditorButton) self.toolBarEditor.addAction(self.uncommentEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.objectListButton) ## Menu Import Class self.classMenu = QMenu() self.classMenu.addAction(self.loadProcessingButton) self.classMenu.addAction(self.loadQtCoreButton) self.classMenu.addAction(self.loadQtGuiButton) cM = self.toolBar.widgetForAction(self.actionClass) cM.setMenu(self.classMenu) cM.setPopupMode(QToolButton.InstantPopup) self.widgetButton = QWidget() sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.widgetButton.sizePolicy().hasHeightForWidth()) self.widgetButton.setSizePolicy(sizePolicy) self.widgetButtonEditor = QWidget(self.widgetEditor) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.widgetButtonEditor.sizePolicy().hasHeightForWidth()) self.widgetButtonEditor.setSizePolicy(sizePolicy) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.shellOut.sizePolicy().hasHeightForWidth()) self.shellOut.setSizePolicy(sizePolicy) self.shellOut.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.shell.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) ##------------ Layout ------------------------------- self.mainLayout = QGridLayout(self) self.mainLayout.setMargin(0) self.mainLayout.setSpacing(0) self.mainLayout.addWidget(self.widgetButton, 0, 0, 1, 1) self.mainLayout.addWidget(self.splitterEditor, 0, 1, 1, 1) self.shellOutWidget.layout().insertWidget(0, self.toolBar) self.layoutEditor = QGridLayout(self.widgetEditor) self.layoutEditor.setMargin(0) self.layoutEditor.setSpacing(0) self.layoutEditor.addWidget(self.toolBarEditor, 0, 1, 1, 1) self.layoutEditor.addWidget(self.widgetButtonEditor, 1, 0, 2, 1) self.layoutEditor.addWidget(self.tabEditorWidget, 1, 1, 1, 1) self.layoutEditor.addWidget(self.widgetFind, 2, 1, 1, 1) ## Layout for the find widget self.layoutFind = QGridLayout(self.widgetFind) self.layoutFind.setContentsMargins(0, 0, 0, 0) self.lineEditFind = QgsFilterLineEdit() placeHolderTxt = QCoreApplication.translate("PythonConsole", "Enter text to find...") if pyqtconfig.Configuration().qt_version >= 0x40700: self.lineEditFind.setPlaceholderText(placeHolderTxt) else: self.lineEditFind.setToolTip(placeHolderTxt) self.findNextButton = QToolButton() self.findNextButton.setEnabled(False) toolTipfindNext = QCoreApplication.translate("PythonConsole", "Find Next") self.findNextButton.setToolTip(toolTipfindNext) self.findNextButton.setIcon( QgsApplication.getThemeIcon( "console/iconSearchNextEditorConsole.png")) self.findNextButton.setIconSize(QSize(24, 24)) self.findNextButton.setAutoRaise(True) self.findPrevButton = QToolButton() self.findPrevButton.setEnabled(False) toolTipfindPrev = QCoreApplication.translate("PythonConsole", "Find Previous") self.findPrevButton.setToolTip(toolTipfindPrev) self.findPrevButton.setIcon( QgsApplication.getThemeIcon( "console/iconSearchPrevEditorConsole.png")) self.findPrevButton.setIconSize(QSize(24, 24)) self.findPrevButton.setAutoRaise(True) self.caseSensitive = QCheckBox() caseSensTr = QCoreApplication.translate("PythonConsole", "Case Sensitive") self.caseSensitive.setText(caseSensTr) self.wholeWord = QCheckBox() wholeWordTr = QCoreApplication.translate("PythonConsole", "Whole Word") self.wholeWord.setText(wholeWordTr) self.wrapAround = QCheckBox() self.wrapAround.setChecked(True) wrapAroundTr = QCoreApplication.translate("PythonConsole", "Wrap Around") self.wrapAround.setText(wrapAroundTr) self.layoutFind.addWidget(self.lineEditFind, 0, 1, 1, 1) self.layoutFind.addWidget(self.findPrevButton, 0, 2, 1, 1) self.layoutFind.addWidget(self.findNextButton, 0, 3, 1, 1) self.layoutFind.addWidget(self.caseSensitive, 0, 4, 1, 1) self.layoutFind.addWidget(self.wholeWord, 0, 5, 1, 1) self.layoutFind.addWidget(self.wrapAround, 0, 6, 1, 1) ##------------ Add first Tab in Editor ------------------------------- #self.tabEditorWidget.newTabEditor(tabName='first', filename=None) ##------------ Signal ------------------------------- self.findTextButton.toggled.connect(self.findTextEditor) self.objectListButton.toggled.connect(self.toggleObjectListWidget) self.commentEditorButton.triggered.connect(self.commentCode) self.uncommentEditorButton.triggered.connect(self.uncommentCode) self.runScriptEditorButton.triggered.connect(self.runScriptEditor) self.cutEditorButton.triggered.connect(self.cutEditor) self.copyEditorButton.triggered.connect(self.copyEditor) self.pasteEditorButton.triggered.connect(self.pasteEditor) self.showEditorButton.toggled.connect(self.toggleEditor) self.clearButton.triggered.connect(self.shellOut.clearConsole) self.optionsButton.triggered.connect(self.openSettings) self.loadProcessingButton.triggered.connect(self.processing) self.loadQtCoreButton.triggered.connect(self.qtCore) self.loadQtGuiButton.triggered.connect(self.qtGui) self.runButton.triggered.connect(self.shell.entered) self.openFileButton.triggered.connect(self.openScriptFile) self.openInEditorButton.triggered.connect(self.openScriptFileExtEditor) self.saveFileButton.triggered.connect(self.saveScriptFile) self.saveAsFileButton.triggered.connect(self.saveAsScriptFile) self.helpButton.triggered.connect(self.openHelp) self.connect(self.listClassMethod, SIGNAL('itemClicked(QTreeWidgetItem*, int)'), self.onClickGoToLine) self.lineEditFind.returnPressed.connect(self._findText) self.findNextButton.clicked.connect(self._findNext) self.findPrevButton.clicked.connect(self._findPrev) self.lineEditFind.textChanged.connect(self._textFindChanged)
# This file belongs with the "jsentencehighlighter" folder: # the README might be inside depending on how you received this! from aqt import mw from PyQt4.QtCore import SIGNAL from PyQt4.QtGui import QAction from anki.hooks import addHook def highlightSentences(nids=None): import jsentencehighlighter.run as run reload(run) run.highlightSentences(nids) action = QAction("Highlight sentences", mw) mw.connect(action, SIGNAL("triggered()"), highlightSentences) mw.form.menuTools.addAction(action) def setupMenu(browser): buttonText = "Highlight Japanese Sentences" a = QAction(buttonText, browser) browser.connect(a, SIGNAL("triggered()"), lambda e=browser: onRegenerate(e)) browser.form.menuEdit.addSeparator() browser.form.menuEdit.addAction(a) def onRegenerate(browser):
def _init_ui(self): namesBox = gui.widgetBox(self.controlArea, "Names") gui.lineEdit(namesBox, self, "attr1", "Variable X ", controlWidth=80, orientation="horizontal", enterPlaceholder=True, callback=self._attr_name_changed) gui.lineEdit(namesBox, self, "attr2", "Variable Y ", controlWidth=80, orientation="horizontal", enterPlaceholder=True, callback=self._attr_name_changed) gui.separator(namesBox) gui.widgetLabel(namesBox, "Class labels") self.classValuesView = listView = QListView( selectionMode=QListView.SingleSelection, sizePolicy=QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Maximum) ) listView.setModel(self.class_model) itemmodels.select_row(listView, 0) namesBox.layout().addWidget(listView) addClassLabel = QAction( "+", self, toolTip="Add new class label", triggered=self.add_new_class_label ) self.removeClassLabel = QAction( unicodedata.lookup("MINUS SIGN"), self, toolTip="Remove selected class label", triggered=self.remove_selected_class_label ) actionsWidget = itemmodels.ModelActionsWidget( [addClassLabel, self.removeClassLabel], self ) actionsWidget.layout().addStretch(10) actionsWidget.layout().setSpacing(1) namesBox.layout().addWidget(actionsWidget) tBox = gui.widgetBox(self.controlArea, "Tools", addSpace=True) buttonBox = gui.widgetBox(tBox, orientation="horizontal") toolsBox = gui.widgetBox(buttonBox, orientation=QtGui.QGridLayout()) self.toolActions = QtGui.QActionGroup(self) self.toolActions.setExclusive(True) for i, (name, tooltip, tool, icon) in enumerate(self.TOOLS): action = QAction( name, self, toolTip=tooltip, checkable=True, icon=QIcon(icon), ) action.triggered.connect(partial(self.set_current_tool, tool)) button = QtGui.QToolButton( iconSize=QSize(24, 24), toolButtonStyle=Qt.ToolButtonTextUnderIcon, sizePolicy=QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) ) button.setDefaultAction(action) toolsBox.layout().addWidget(button, i / 3, i % 3) self.toolActions.addAction(action) for column in range(3): toolsBox.layout().setColumnMinimumWidth(column, 10) toolsBox.layout().setColumnStretch(column, 1) undo = self.undo_stack.createUndoAction(self) redo = self.undo_stack.createRedoAction(self) undo.setShortcut(QtGui.QKeySequence.Undo) redo.setShortcut(QtGui.QKeySequence.Redo) self.addActions([undo, redo]) gui.separator(tBox) indBox = gui.indentedBox(tBox, sep=8) form = QtGui.QFormLayout( formAlignment=Qt.AlignLeft, labelAlignment=Qt.AlignLeft, fieldGrowthPolicy=QtGui.QFormLayout.AllNonFixedFieldsGrow ) indBox.layout().addLayout(form) slider = gui.hSlider( indBox, self, "brushRadius", minValue=1, maxValue=100, createLabel=False ) form.addRow("Radius", slider) slider = gui.hSlider( indBox, self, "density", None, minValue=1, maxValue=100, createLabel=False ) form.addRow("Intensity", slider) gui.rubber(self.controlArea) gui.auto_commit(self.controlArea, self, "autocommit", "Send", "Send on change") # main area GUI viewbox = PaintViewBox() self.plotview = pg.PlotWidget(background="w", viewBox=viewbox) self.plot = self.plotview.getPlotItem() axis_color = self.palette().color(QtGui.QPalette.Text) axis_pen = QtGui.QPen(axis_color) tickfont = QtGui.QFont(self.font()) tickfont.setPixelSize(max(int(tickfont.pixelSize() * 2 // 3), 11)) axis = self.plot.getAxis("bottom") axis.setLabel(self.attr1) axis.setPen(axis_pen) axis.setTickFont(tickfont) axis = self.plot.getAxis("left") axis.setLabel(self.attr2) axis.setPen(axis_pen) axis.setTickFont(tickfont) self.plot.setRange(xRange=(0.0, 1.0), yRange=(0.0, 1.0), disableAutoRange=True) self.mainArea.layout().addWidget(self.plotview) # enable brush tool self.toolActions.actions()[0].setChecked(True) self.set_current_tool(self.TOOLS[0][2])
class ReportEditorApp(FreeseerApp): ''' Freeseer report editor main gui class ''' def __init__(self, core=None): FreeseerApp.__init__(self) icon = QIcon() icon.addPixmap(QPixmap(_fromUtf8(":/freeseer/logo.png")), QIcon.Normal, QIcon.Off) self.setWindowIcon(icon) self.resize(960, 400) self.mainWidget = QWidget() self.mainLayout = QHBoxLayout() self.mainWidget.setLayout(self.mainLayout) self.setCentralWidget(self.mainWidget) self.editorWidget = ReportEditorWidget() self.editorWidget.editor.setColumnHidden(5, True) self.mainLayout.addWidget(self.editorWidget) # Initialize geometry, to be used for restoring window positioning. self.geometry = None self.config = Config(settings.configdir) self.db = QtDBConnector(settings.configdir) # # Setup Menubar # self.actionExportCsv = QAction(self) self.actionExportCsv.setObjectName(_fromUtf8("actionExportCsv")) # Actions self.menuFile.insertAction(self.actionExit, self.actionExportCsv) # --- End Menubar # # Report Editor Connections # # Editor Widget self.connect(self.editorWidget.removeButton, SIGNAL('clicked()'), self.remove_talk) self.connect(self.editorWidget.clearButton, SIGNAL('clicked()'), self.confirm_reset) self.connect(self.editorWidget.closeButton, SIGNAL('clicked()'), self.close) # Main Window Connections self.connect(self.actionExportCsv, SIGNAL('triggered()'), self.export_reports_to_csv) self.connect(self.editorWidget.editor, SIGNAL('clicked (const QModelIndex&)'), self.editorSelectionChanged) # Load default language actions = self.menuLanguage.actions() for action in actions: if action.data().toString() == self.config.default_language: action.setChecked(True) self.translate(action) break self.load_failures_model() self.editorWidget.editor.resizeColumnsToContents() self.editorWidget.editor.resizeRowsToContents() ### ### Translation ### def retranslate(self): self.setWindowTitle( self.app.translate("ReportEditorApp", "Freeseer Report Editor")) # # Reusable Strings # self.confirmDBClearTitleString = self.app.translate( "ReportEditorApp", "Clear Database") self.confirmDBClearQuestionString = self.app.translate( "ReportEditorApp", "Are you sure you want to clear the DB?") self.selectFileString = self.app.translate("ReportEditorApp", "Select File") # --- End Reusable Strings # # Menubar # self.actionExportCsv.setText( self.app.translate("ReportEditorApp", "&Export to CSV")) # --- End Menubar # # EditorWidget # self.editorWidget.removeButton.setText( self.app.translate("ReportEditorApp", "Remove")) self.editorWidget.clearButton.setText( self.app.translate("ReportEditorApp", "Clear")) self.editorWidget.closeButton.setText( self.app.translate("ReportEditorApp", "Close")) self.editorWidget.titleLabel.setText( self.app.translate("ReportEditorApp", "Title:")) self.editorWidget.speakerLabel.setText( self.app.translate("ReportEditorApp", "Speaker:")) self.editorWidget.descriptionLabel.setText( self.app.translate("ReportEditorApp", "Description:")) self.editorWidget.levelLabel.setText( self.app.translate("ReportEditorApp", "Level:")) self.editorWidget.eventLabel.setText( self.app.translate("ReportEditorApp", "Event:")) self.editorWidget.roomLabel.setText( self.app.translate("ReportEditorApp", "Room:")) self.editorWidget.timeLabel.setText( self.app.translate("ReportEditorApp", "Time:")) # --- End EditorWidget def load_failures_model(self): # Load Presentation Model self.failureModel = self.db.get_failures_model() editor = self.editorWidget.editor editor.setModel(self.failureModel) editor.horizontalHeader().setResizeMode(QHeaderView.Stretch) def hide_add_talk_widget(self): self.editorWidget.setHidden(False) self.addTalkWidget.setHidden(True) def add_talk(self): date = self.addTalkWidget.dateEdit.date() time = self.addTalkWidget.timeEdit.time() datetime = QDateTime(date, time) presentation = Presentation( unicode(self.addTalkWidget.titleLineEdit.text()), unicode(self.addTalkWidget.presenterLineEdit.text()), "", # description "", # level unicode(self.addTalkWidget.eventLineEdit.text()), unicode(self.addTalkWidget.roomLineEdit.text()), unicode(datetime.toString())) # Do not add talks if they are empty strings if (len(presentation.title) == 0): return self.db.insert_presentation(presentation) # cleanup self.addTalkWidget.titleLineEdit.clear() self.addTalkWidget.presenterLineEdit.clear() self.failureModel.select() self.hide_add_talk_widget() def remove_talk(self): try: row_clicked = self.editorWidget.editor.currentIndex().row() except: return self.failureModel.removeRow(row_clicked) self.failureModel.select() def reset(self): self.db.clear_report_db() self.failureModel.select() def confirm_reset(self): """ Presents a confirmation dialog to ask the user if they are sure they wish to remove the report database. If Yes call the reset() function. """ confirm = QMessageBox.question(self, self.confirmDBClearTitleString, self.confirmDBClearQuestionString, QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if confirm == QMessageBox.Yes: self.reset() def closeEvent(self, event): log.info('Exiting report editor...') self.geometry = self.saveGeometry() event.accept() def editorSelectionChanged(self, index): talkId = self.failureModel.record(index.row()).value(0).toString() self.updatePresentationInfo(talkId) def updatePresentationInfo(self, talkId): p = self.db.get_presentation(talkId) if p is not None: self.editorWidget.titleLabel2.setText(p.title) self.editorWidget.speakerLabel2.setText(p.speaker) self.editorWidget.descriptionLabel2.setText(p.description) self.editorWidget.levelLabel2.setText(p.level) self.editorWidget.eventLabel2.setText(p.event) self.editorWidget.roomLabel2.setText(p.room) self.editorWidget.timeLabel2.setText(p.time) else: self.editorWidget.titleLabel2.setText("Talk not found") self.editorWidget.speakerLabel2.setText("Talk not found") self.editorWidget.descriptionLabel2.setText("Talk not found") self.editorWidget.levelLabel2.setText("Talk not found") self.editorWidget.eventLabel2.setText("Talk not found") self.editorWidget.roomLabel2.setText("Talk not found") self.editorWidget.timeLabel2.setText("Talk not found") def export_reports_to_csv(self): fname = QFileDialog.getSaveFileName(self, self.selectFileString, "", "*.csv") if fname: self.db.export_reports_to_csv(fname)
def createAction(parent, label, callback=None, icon=None, tip=None, shortcut=None, data=None, toggled=False, tooltip=None, cb_arg=None, cb_args=None, iconText=None, checkable=None): """ Create a QAction @param parent: @type parent: @param label: @type label: @param callback: @type callback: @param icon: @type icon: @param tip: @type tip: @param shortcut: @type shortcut: @param data: @type data: @param toggled: @type toggled: @return: @rtype: """ action = QAction(label, parent) if toggled: if callback is not None: action.toggled.connect(callback) action.setCheckable(True) else: if callback is not None: if cb_arg is None: action.triggered.connect(callback) else: if cb_args is None: action.triggered.connect(lambda: callback(cb_arg)) else: action.triggered.connect(lambda: callback(**cb_args)) if icon: action.setIcon(icon) if shortcut: action.setShortcut(shortcut) if tip: action.setStatusTip(tip) if tooltip: action.setToolTip(tooltip) if data is not None: action.setData(data) if iconText is not None: action.setIconText(iconText) if checkable is not None: action.setCheckable(checkable) return action
class StartData: def __init__(self, iface): self.iface = iface self.tableSchema = 'edgv' self.geometryColumn = 'geom' self.keyColumn = 'id' def initGui(self): # cria uma ação que iniciará a configuração do plugin pai = self.iface.mainWindow() icon_path = ':/plugins/StartData/icon.png' self.action = QAction (QIcon (icon_path),u"Acessa banco de dados para revisão", pai) self.action.setObjectName ("Stard database") self.action.setStatusTip(None) self.action.setWhatsThis(None) self.action.triggered.connect(self.run) # Adicionar o botão icone self.iface.addToolBarIcon (self.action) def unload(self): # remove o item de ícone do QGIS GUI. self.iface.removeToolBarIcon (self.action) def run(self): ################################## ###### PEGA A LAYER ATIVA ######## ################################## layer = self.iface.activeLayer() if not layer: self.iface.messageBar().pushMessage("Erro", u"Esperando uma Active Layer!", level=QgsMessageBar.CRITICAL, duration=4) return if layer.featureCount() == 0: self.iface.messageBar().pushMessage("Erro", u"a camada não possui feições!", level=QgsMessageBar.CRITICAL, duration=4) return parametros = layer.source().split(" ") # recebe todos os parametros em uma lista ( senha, porta, password etc..) #################################### ###### INICIANDO CONEXÃO DB ######## #################################### # Outra opção para isso, seria usar ex: self.dbname.. self.host.. etc.. direto dentro do laço for. dbname = "" host = "" port = 0 user = "" password = "" for i in parametros: part = i.split("=") # Recebe os parametros guardados na própria Layer if "dbname" in part[0]: dbname = part[1].replace("'", "") elif "host" in part[0]: host = part[1].replace("'", "") elif "port" in part[0]: port = int(part[1].replace("'", "")) elif "user" in part[0]: user = part[1].replace("'", "") elif "password" in part[0]: password = part[1].split("|")[0].replace("'", "") #print dbname, host, port, user, password # Testa se os parametros receberam os valores pretendidos, caso não, apresenta a mensagem informando.. if len(dbname) == 0 or len(host) == 0 or port == 0 or len(user) == 0 or len(password) == 0: self.iface.messageBar().pushMessage("Erro", u'Um dos parametros não foram devidamente recebidos!', level=QgsMessageBar.CRITICAL, duration=4) return #################################### #### SETA VALORES DE CONEXÃO DB #### #################################### connection = QSqlDatabase.addDatabase('QPSQL') connection.setHostName(host) connection.setPort(port) connection.setUserName(user) connection.setPassword(password) connection.setDatabaseName(dbname) if not connection.isOpen(): # Testa se a conexão esta recebendo os parametros adequadamente. if not connection.open(): print 'Error connecting to database!' self.iface.messageBar().pushMessage("Erro", u'Error connecting to database!', level=QgsMessageBar.CRITICAL, duration=4) print connection.lastError().text() return #################################### ###### CRIAÇÃO DE MEMORY LAYER ##### #################################### layerCrs = layer.crs().authid() # Passa o formato (epsg: numeros) flagsLayerName = layer.name() + "_flags" flagsLayerExists = False for l in QgsMapLayerRegistry.instance().mapLayers().values(): # Recebe todas as camadas que estão abertas if l.name() == flagsLayerName: # ao encontrar o nome pretendido.. self.flagsLayer = l # flagslayer vai receber o nome.. self.flagsLayerProvider = l.dataProvider() flagsLayerExists = True # se encontrado os parametros buscados, recebe True. break if flagsLayerExists == False: # se não encontrado os parametros buscados, recebe False. tempString = "Point?crs=" tempString += str(layerCrs) self.flagsLayer = QgsVectorLayer(tempString, flagsLayerName, "memory") self.flagsLayerProvider = self.flagsLayer.dataProvider() self.flagsLayerProvider.addAttributes([QgsField("id", QVariant.Int), QgsField("motivo", QVariant.String)]) self.flagsLayer.updateFields() self.flagsLayer.startEditing() ids = [feat.id() for feat in self.flagsLayer.getFeatures()] self.flagsLayer.deleteFeatures(ids) self.flagsLayer.commitChanges() lista_fid = [] # Iniciando lista for f in layer.getFeatures(): lista_fid.append(str(f.id())) # Guarda na lista. A lista de Feature ids passa tipo "int", foi convertido e guardado como "str". source = layer.source().split(" ") self.tableName = "" # Inicia vazio layerExistsInDB = False for i in source: if "table=" in i or "layername=" in i: # Se encontrar os atributos pretendidos dentre todos do for self.tableName = source[source.index(i)].split(".")[1] # Faz split em ponto e pega a segunda parte. self.tableName = self.tableName.replace('"', '') layerExistsInDB = True break if layerExistsInDB == False: self.iface.messageBar().pushMessage("Erro", u"Provedor da camada corrente não provem do banco de dados!", level=QgsMessageBar.CRITICAL, duration=4) return # Busca através do SQL query_string = '''select distinct (reason(ST_IsValidDetail(f."{2}",0))) AS motivo, ''' query_string += '''ST_AsText(ST_Multi(ST_SetSrid(location(ST_IsValidDetail(f."{2}",0)), ST_Srid(f.{2})))) as local from ''' query_string += '''(select "{3}", "{2}" from only "{0}"."{1}" where ST_IsValid("{2}") = 'f' and {3} in ({4})) as f''' query_string = query_string.format(self.tableSchema, self.tableName, self.geometryColumn, self.keyColumn, ",".join(lista_fid)) query = QSqlQuery(query_string) self.flagsLayer.startEditing() flagCount = 0 # iniciando contador que será referência para os IDs da camada de memória. listaFeatures = [] while query.next(): motivo = query.value(0) local = query.value(1) flagId = flagCount flagFeat = QgsFeature() flagGeom = QgsGeometry.fromWkt(local) # passa o local onde foi localizado o erro. flagFeat.setGeometry(flagGeom) flagFeat.initAttributes(2) flagFeat.setAttribute(0,flagId) # insere o id definido para a coluna 0 da layer de memória. flagFeat.setAttribute(1, motivo) # insere o motivo/razão pré-definida para a coluna 1 da layer de memória. listaFeatures.append(flagFeat) flagCount += 1 # incrementando o contador a cada iteração self.flagsLayerProvider.addFeatures(listaFeatures) self.flagsLayer.commitChanges() # Aplica as alterações à camada. QgsMapLayerRegistry.instance().addMapLayer(self.flagsLayer) # Adicione a camada no mapa ################################## ##### TROCA MARCADOR DA LAYER #### ################################## # # AQUI PRETENDO PERSONALIZAR O MARCADOR DA MEMORY LAYER, POREM A PRINCIPIO SÓ ESTA ALTERANDO A LAYER ORIGINAL. # for lay in QgsMapLayerRegistry.instance().mapLayers().values(): # if lay == flagsLayerName and not layer.name(): # # Estilo base. # line = QgsLineSymbolV2() # # Crie uma linha de marcadores. # marker_line = QgsMarkerLineSymbolLayerV2() # marker_line.setInterval(10) # # Configure o marcador. # simple_marker = QgsSimpleMarkerSymbolLayerV2() # simple_marker.setShape(QgsSimpleMarkerSymbolLayerBase.HalfSquare) # Formato # simple_marker.setSize(3) # simple_marker.setAngle(180) # simple_marker.setColor(QColor('red')) # cor # simple_marker.setOutlineColor(QColor('red')) # cor # # O marcador tem sua própria camada de símbolo. # marker = QgsMarkerSymbolV2() # marker.changeSymbolLayer(0, simple_marker) # # Adicione a camada à camada do marcador. # marker_line.setSubSymbol(marker) # # Finalmente, substitua a camada de símbolo no estilo base. # line.changeSymbolLayer(0, marker_line) # # Adicione o estilo à camada de linha. # renderer = QgsSingleSymbolRendererV2(line) # layer.setRendererV2(renderer) if flagCount == 0: QgsMapLayerRegistry.instance().removeMapLayer(self.flagsLayer.id()) self.iface.messageBar().pushMessage("Aviso", u"Não foi encontrado Flags em \"" + layer.name() + "\" !", level=QgsMessageBar.CRITICAL, duration=4) return if len(query.lastError().text()) == 1: self.iface.messageBar().pushMessage("Aviso", "foram geradas " + str(flagCount) + " flags para a camada \"" + layer.name() + "\" !", level=QgsMessageBar.INFO, duration=4) else: self.iface.messageBar().pushMessage("Erro", u"a geração de flags falhou!", level=QgsMessageBar.CRITICAL, duration=4) print query.lastError().text()
def __init__(self, core=None): FreeseerApp.__init__(self) icon = QIcon() icon.addPixmap(QPixmap(_fromUtf8(":/freeseer/logo.png")), QIcon.Normal, QIcon.Off) self.setWindowIcon(icon) self.resize(960, 400) self.mainWidget = QWidget() self.mainLayout = QHBoxLayout() self.mainWidget.setLayout(self.mainLayout) self.setCentralWidget(self.mainWidget) self.editorWidget = ReportEditorWidget() self.editorWidget.editor.setColumnHidden(5, True) self.mainLayout.addWidget(self.editorWidget) # Initialize geometry, to be used for restoring window positioning. self.geometry = None self.config = Config(settings.configdir) self.db = QtDBConnector(settings.configdir) # # Setup Menubar # self.actionExportCsv = QAction(self) self.actionExportCsv.setObjectName(_fromUtf8("actionExportCsv")) # Actions self.menuFile.insertAction(self.actionExit, self.actionExportCsv) # --- End Menubar # # Report Editor Connections # # Editor Widget self.connect(self.editorWidget.removeButton, SIGNAL('clicked()'), self.remove_talk) self.connect(self.editorWidget.clearButton, SIGNAL('clicked()'), self.confirm_reset) self.connect(self.editorWidget.closeButton, SIGNAL('clicked()'), self.close) # Main Window Connections self.connect(self.actionExportCsv, SIGNAL('triggered()'), self.export_reports_to_csv) self.connect(self.editorWidget.editor, SIGNAL('clicked (const QModelIndex&)'), self.editorSelectionChanged) # Load default language actions = self.menuLanguage.actions() for action in actions: if action.data().toString() == self.config.default_language: action.setChecked(True) self.translate(action) break self.load_failures_model() self.editorWidget.editor.resizeColumnsToContents() self.editorWidget.editor.resizeRowsToContents()
def registerDatabaseActions(self, mainWindow): action = QAction(self.tr("Run &Vacuum"), self) mainWindow.registerAction(action, self.tr("&Database"), self.runVacuumActionSlot) Database.registerDatabaseActions(self, mainWindow)
def createAdditionalMenus(self): self.editLineWidthAction = QAction(self.tr('Line Width'), self) self.editLineWidthAction.triggered.connect(self.onChangeLineWidth) self.editLineColorAction = QAction(self.tr('Line Color'), self) self.editLineColorAction.triggered.connect(self.onChangeLineColor)