コード例 #1
0
ファイル: plotCurveLegendWidget.py プロジェクト: t20100/silx
    def _contextMenu(self, pos):
        """Create a show the context menu.

        :param QPoint pos: Position in this widget
        """
        curve = self.curveAt(pos)  # Retrieve curve from hovered legend
        if curve is not None:
            menu = qt.QMenu()  # Create the menu

            # Add an action to activate the curve
            activeCurve = curve.getPlot().getActiveCurve()
            menu.addAction('Unselect' if curve == activeCurve else 'Select',
                           functools.partial(self._switchCurveActive, curve))

            # Add an action to switch the Y axis of a curve
            yaxis = 'right' if curve.getYAxis() == 'left' else 'left'
            menu.addAction('Map to %s' % yaxis,
                           functools.partial(self._switchCurveYAxis, curve))

            # Add an action to show/hide the curve
            menu.addAction('Hide' if curve.isVisible() else 'Show',
                           functools.partial(self._switchCurveVisibility, curve))

            globalPosition = self.mapToGlobal(pos)
            menu.exec(globalPosition)
コード例 #2
0
ファイル: PeakPickingTask.py プロジェクト: ronpandolfi/pyFAI
    def __createOptionsWidget(self):
        menu = qt.QMenu(self)

        # Load peak selection as file
        loadPeaksFromFile = qt.QAction(self)
        icon = icons.getQIcon('document-open')
        loadPeaksFromFile.setIcon(icon)
        loadPeaksFromFile.setText("Load peak selection from file")
        loadPeaksFromFile.triggered.connect(self.__loadPeaksFromFile)
        loadPeaksFromFile.setIconVisibleInMenu(True)
        menu.addAction(loadPeaksFromFile)

        # Save peak selection as file
        savePeaksAsFile = qt.QAction(self)
        icon = icons.getQIcon('document-save')
        savePeaksAsFile.setIcon(icon)
        savePeaksAsFile.setText("Save peak selection as file")
        savePeaksAsFile.triggered.connect(self.__savePeaksAsFile)
        savePeaksAsFile.setIconVisibleInMenu(True)
        menu.addAction(savePeaksAsFile)

        options = qt.QToolButton(self)
        icon = icons.getQIcon('pyfai:gui/icons/options')
        options.setIcon(icon)
        options.setPopupMode(qt.QToolButton.InstantPopup)
        options.setMenu(menu)
        return options
コード例 #3
0
    def __popupUnitSelection(self, pos):
        """Display a popup list to allow to select a new unit"""
        currentUnit = self.usedUnit()
        if currentUnit is None:
            return

        unitList = units.Unit.get_units(currentUnit.dimensionality)
        if len(unitList) <= 1:
            return

        menu = qt.QMenu(self)
        menu.addSection("Unit for %s" %
                        currentUnit.dimensionality.fullname.lower())

        for unit in unitList:
            action = qt.QAction(menu)
            text = "%s: %s" % (unit.fullname, unit.symbol)
            if unit is currentUnit:
                text += " (current)"
            action.setText(text)
            action.triggered.connect(
                functools.partial(self.__unitSelected, unit))
            menu.addAction(action)

        menu.popup(pos)
コード例 #4
0
    def getMenu(self):
        """Returns the menu.

        :rtype: qt.QMenu
        """
        button = self.__button
        menu = button.menu()
        if menu is None:
            menu = qt.QMenu(button)
            button.setMenu(menu)
        return menu
コード例 #5
0
ファイル: ViewpointTools.py プロジェクト: strategist922/silx
    def __init__(self, parent=None, plot3D=None):
        super(ViewpointToolButton, self).__init__(parent)

        self._actionGroup = _ViewpointActionGroup(plot3D)

        menu = qt.QMenu(self)
        menu.addActions(self._actionGroup.actions())
        self.setMenu(menu)
        self.setPopupMode(qt.QToolButton.InstantPopup)
        self.setIcon(getQIcon('cube'))
        self.setToolTip('Reset the viewpoint to a defined position')
コード例 #6
0
ファイル: testProfile.py プロジェクト: tifuchs/silx
    def testEditors(self):
        roiClasses = [
            (rois.ProfileImageHorizontalLineROI,
             editors._DefaultImageProfileRoiEditor),
            (rois.ProfileImageVerticalLineROI,
             editors._DefaultImageProfileRoiEditor),
            (rois.ProfileImageLineROI, editors._DefaultImageProfileRoiEditor),
            (rois.ProfileImageCrossROI, editors._DefaultImageProfileRoiEditor),
            (rois.ProfileScatterHorizontalLineROI,
             editors._DefaultScatterProfileRoiEditor),
            (rois.ProfileScatterVerticalLineROI,
             editors._DefaultScatterProfileRoiEditor),
            (rois.ProfileScatterLineROI,
             editors._DefaultScatterProfileRoiEditor),
            (rois.ProfileScatterCrossROI,
             editors._DefaultScatterProfileRoiEditor),
            (rois.ProfileScatterHorizontalSliceROI,
             editors._NoProfileRoiEditor),
            (rois.ProfileScatterVerticalSliceROI, editors._NoProfileRoiEditor),
            (rois.ProfileScatterCrossSliceROI, editors._NoProfileRoiEditor),
            (rois.ProfileImageStackHorizontalLineROI,
             editors._DefaultImageStackProfileRoiEditor),
            (rois.ProfileImageStackVerticalLineROI,
             editors._DefaultImageStackProfileRoiEditor),
            (rois.ProfileImageStackLineROI,
             editors._DefaultImageStackProfileRoiEditor),
            (rois.ProfileImageStackCrossROI,
             editors._DefaultImageStackProfileRoiEditor),
        ]
        with self.defaultPlot() as plot:
            profileManager = manager.ProfileManager(plot, plot)
            editorAction = profileManager.createEditorAction(parent=plot)
            for roiClass, editorClass in roiClasses:
                with self.subTest(roiClass=roiClass):
                    roi = roiClass()
                    roi._setProfileManager(profileManager)
                    try:
                        # Force widget creation
                        menu = qt.QMenu(plot)
                        menu.addAction(editorAction)
                        widgets = editorAction.createdWidgets()
                        self.assertGreater(len(widgets), 0)

                        editorAction.setProfileRoi(roi)
                        editorWidget = editorAction._getEditor(widgets[0])
                        self.assertIsInstance(editorWidget, editorClass)
                        self.genericEditorTest(plot, roi, editorWidget)
                    finally:
                        editorAction.setProfileRoi(None)
                        menu.deleteLater()
                        menu = None
                        self.qapp.processEvents()
コード例 #7
0
ファイル: view.py プロジェクト: znarthur/xraylarch
    def showContextMenu(self, position):
        menu = qt.QMenu('Horizontal Header View Menu', self)

        section = self.logicalIndexAt(position)

        action = qt.QAction('Add', self, triggered=self.append)
        menu.addAction(action)

        action = qt.QAction('Remove',
                            self,
                            triggered=lambda: self.remove(section))
        menu.addAction(action)

        menu.exec_(self.mapToGlobal(position))
コード例 #8
0
ファイル: IntegrationTask.py プロジェクト: yugangzhang/pyFAI
    def __plot2dContextMenu(self, pos):
        from silx.gui.plot.actions.control import ZoomBackAction
        zoomBackAction = ZoomBackAction(plot=self.__plot2d, parent=self.__plot2d)

        menu = qt.QMenu(self)

        menu.addAction(zoomBackAction)
        menu.addSeparator()
        menu.addAction(self.__markerManager.createMarkPixelAction(menu, pos))
        menu.addAction(self.__markerManager.createMarkGeometryAction(menu, pos))
        action = self.__markerManager.createRemoveClosestMaskerAction(menu, pos)
        if action is not None:
            menu.addAction(action)

        handle = self.__plot2d.getWidgetHandle()
        menu.exec_(handle.mapToGlobal(pos))
コード例 #9
0
ファイル: view.py プロジェクト: znarthur/xraylarch
    def showContextMenu(self, position):
        menu = qt.QMenu('Tree View Menu', self)

        action = qt.QAction('Add Experiment',
                            self,
                            triggered=self.addExperiment)
        menu.addAction(action)

        # Get the index under the cursor.
        index = self.indexAt(position)
        item = self.model().itemFromIndex(index)

        if isinstance(item, ExperimentItem) or isinstance(item, GroupItem):
            action = qt.QAction('Add Group', self, triggered=self.addGroup)
            menu.addAction(action)

            action = qt.QAction('Load Files', self, triggered=self.loadFiles)
            menu.addAction(action)

        # If there are selected indexes, they can be removed or checked.
        if self.selectedIndexes():
            menu.addSeparator()
            action = qt.QAction('Toggle Selected',
                                self,
                                triggered=self.toggleSelected)
            menu.addAction(action)
            action = qt.QAction('Remove Selected',
                                self,
                                triggered=self.removeSelected)
            menu.addAction(action)

        if isinstance(item, ScanItem) and index.column() > 0:
            menu.addSeparator()
            action = qt.QAction(
                'Copy Value to Selected',
                self,
                triggered=lambda: self.copyValueToSelected(index))
            menu.addAction(action)

            action = qt.QAction(
                'Copy Value to Toggled',
                self,
                triggered=lambda: self.copyValueToToggled(index))
            menu.addAction(action)

        menu.exec_(self.mapToGlobal(position))
コード例 #10
0
ファイル: diffmap_widget.py プロジェクト: kif/pyFAI
    def _menu_file(self):
        # Drop-down file menu
        self.files_menu = qt.QMenu("Files")

        action_more = qt.QAction("add files", self.files)
        self.files_menu.addAction(action_more)
        action_more.triggered.connect(self.input_filer)

        action_sort = qt.QAction("sort files", self.files)
        self.files_menu.addAction(action_sort)
        action_sort.triggered.connect(self.sort_input)

        action_clear = qt.QAction("clear selected files", self.files)
        self.files_menu.addAction(action_clear)
        action_clear.triggered.connect(self.clear_selection)

        self.files.setMenu(self.files_menu)
コード例 #11
0
 def __updateFileMenu(self):
     files = self.__context.getRecentFiles()
     self._openRecentAction.setEnabled(len(files) != 0)
     menu = None
     if len(files) != 0:
         menu = qt.QMenu()
         for filePath in files:
             baseName = os.path.basename(filePath)
             action = qt.QAction(baseName, self)
             action.setToolTip(filePath)
             action.triggered.connect(functools.partial(self.__openRecentFile, filePath))
             menu.addAction(action)
         menu.addSeparator()
         baseName = os.path.basename(filePath)
         action = qt.QAction("Clear history", self)
         action.setToolTip("Clear the history of the recent files")
         action.triggered.connect(self.__clearRecentFile)
         menu.addAction(action)
     self._openRecentAction.setMenu(menu)
コード例 #12
0
    def __init__(self, parent=None, plot=None):
        self._bg_dialog = None
        self._scatter_dialog = None
        super(ColormapToolButton, self).__init__(parent)
        self.plot = plot

        icon = icons.getQIcon('colormap')
        self.setIcon(icon)

        bgImageCmapAction = qt.QAction("Background image colormap", self)
        bgImageCmapAction.triggered.connect(self._setBgCmap)

        scatterCmapAction = qt.QAction("Scatter colormap", self)
        scatterCmapAction.triggered.connect(self._setScatterCmap)

        menu = qt.QMenu(self)
        menu.addAction(bgImageCmapAction)
        menu.addAction(scatterCmapAction)
        self.setMenu(menu)
        self.setPopupMode(qt.QToolButton.InstantPopup)
    def _contextMenu(self, pos):
        """Handle plot area customContextMenuRequested signal.

        :param QPoint pos: Mouse position relative to plot area
        """
        # Create the context menu
        menu = qt.QMenu(self)
        menu.addAction(self._zoomBackAction)
        menu.addSeparator()
        menu.addAction(self._crosshairAction)
        menu.addSeparator()
        menu.addAction(self._saveAction)
        menu.addAction(self._printAction)

        # Displaying the context menu at the mouse position requires
        # a global position.
        # The position received as argument is relative to PlotWidget's
        # plot area, and thus needs to be converted.
        plotArea = self.getWidgetHandle()
        globalPosition = plotArea.mapToGlobal(pos)
        menu.exec_(globalPosition)
コード例 #14
0
    def showContextMenu(self, position):
        menu = qt.QMenu('RixsPlotArea Menu', self)

        action = qt.QAction('Add RixsPlot2D Window',
                            self,
                            triggered=self.addRixsPlot2D)
        menu.addAction(action)

        menu.addSeparator()

        action = qt.QAction('Cascade Windows',
                            self,
                            triggered=self.cascadeSubWindows)
        menu.addAction(action)

        action = qt.QAction('Tile Windows',
                            self,
                            triggered=self.tileSubWindows)
        menu.addAction(action)

        menu.exec_(self.mapToGlobal(position))
コード例 #15
0
    def onCustomContextMenu(self, point):
        menu = qt.QMenu()
        if len(csi.selectedTopItems) == 0:
            return

        menu.addAction(self.actionDND)
        self.actionDND.setChecked(self.isInnerDragNDropAllowed)
        menu.addAction(self.actionMoveUp)
        menu.addAction(self.actionMoveDown)
        menu.addSeparator()

        isGroupSelected = False
        if len(csi.selectedTopItems) > 1:
            menu.addAction(self.actionMakeGroup)
        elif len(csi.selectedTopItems) == 1:
            if csi.selectedTopItems[0].child_count() > 0:
                isGroupSelected = True
                menu.addAction(self.actionUngroup)

        menu.addSeparator()
        menu.addAction(self.actionRemove)

        if self.node is not None:
            if self.node.columnCount > 0:
                menu.addSeparator()
                if isGroupSelected or csi.selectedTopItems == \
                        csi.dataRootItem.get_nongroups():
                    item = csi.selectedTopItems[0]
                    try:
                        if hasattr(item, 'colorAutoUpdate'):
                            cond = item.colorAutoUpdate
                        else:
                            cond = item.parentItem.colorAutoUpdate
                        menu.addAction(self.actionAUCC)
                        self.actionAUCC.setChecked(cond)
                    except AttributeError:
                        pass
                menu.addAction(self.actionLines)

        menu.exec_(self.viewport().mapToGlobal(point))
コード例 #16
0
    def createDefaultContextMenu(self, index):
        """Create a default context menu at this position.

        :param qt.QModelIndex index: Index of the item
        """
        index = self.__model.index(index.row(), 0, parent=index.parent())
        item = self.__model.itemFromIndex(index)

        menu = qt.QMenu()

        weakself = weakref.proxy(self)

        if isinstance(item, _NxDataItem):
            action = qt.QAction("Add a new axis", menu)
            action.triggered.connect(lambda: weakself.model().appendAxisToNxdataItem(item))
            action.setIcon(icons.getQIcon("nxdata-axis-add"))
            action.setIconVisibleInMenu(True)
            menu.addAction(action)
            menu.addSeparator()
            action = qt.QAction("Remove this NXdata", menu)
            action.triggered.connect(lambda: weakself.model().removeNxdataItem(item))
            action.setIcon(icons.getQIcon("remove"))
            action.setIconVisibleInMenu(True)
            menu.addAction(action)
        else:
            if isinstance(item, _DatasetItemRow):
                if item.getDataset() is not None:
                    action = qt.QAction("Remove this dataset", menu)
                    action.triggered.connect(lambda: item.setDataset(None))
                    menu.addAction(action)

            if isinstance(item, _DatasetAxisItemRow):
                menu.addSeparator()
                action = qt.QAction("Remove this axis", menu)
                action.triggered.connect(lambda: weakself.model().removeAxisItem(item))
                action.setIcon(icons.getQIcon("remove"))
                action.setIconVisibleInMenu(True)
                menu.addAction(action)

        return menu
コード例 #17
0
    def _contextMenu(self, pos):
        """Handle plot area customContextMenuRequested signal.

        :param QPoint pos: Mouse position relative to plot area
        """
        # Create the context menu
        menu = qt.QMenu(self)
        menu.addAction(
            actions.mode.PanAction(parent=menu, plot3d=self.getPlot3DWidget()))
        menu.addAction(
            actions.mode.RotateArcballAction(parent=menu,
                                             plot3d=self.getPlot3DWidget()))
        menu.addSeparator()
        menu.addAction(
            actions.io.CopyAction(parent=menu, plot3d=self.getPlot3DWidget()))

        # Displaying the context menu at the mouse position requires
        # a global position.
        # The position received as argument is relative to Plot3DWidget
        # and needs to be converted.
        globalPosition = self.getPlot3DWidget().mapToGlobal(pos)
        menu.exec_(globalPosition)
コード例 #18
0
    def contextMenuEvent(self, event):
        if not self.propWidgets or (len(csi.selectedItems) == 0):
            return
        widgetsOver = self._widgetsAt(event.globalPos())
        out = [
            w in self.propWidgets or w in self.propGroups
            or w in self.exclusivePropGroups for w in widgetsOver
        ]
        if sum(out) == 0:
            return

        menu = qt.QMenu(self)
        hdf5Path = self.fillMenuApply(widgetsOver, menu)
        if self.transform is not None:
            menu.addSeparator()
            self.fillMenuReset(widgetsOver, menu)

        if hdf5Path:
            menu.addSeparator()
            self._addAction(menu, "go to hdf5 location",
                            partial(self.gotoHDF5, hdf5Path))

        menu.exec_(event.globalPos())
コード例 #19
0
    def initToolbar(self):
        self.loadAction = qt.QAction(
            qt.QIcon(os.path.join(self.iconDir, "icon-load-proj.png")),
            "Load project (Ctrl+O)", self)
        self.loadAction.setShortcut('Ctrl+O')
        self.loadAction.triggered.connect(self.slotLoadProject)

        self.saveAction = qt.QAction(
            qt.QIcon(os.path.join(self.iconDir, "icon-save-proj.png")),
            "Save project, data and plots (Ctrl+S)", self)
        self.saveAction.setShortcut('Ctrl+S')
        self.saveAction.triggered.connect(self.slotSaveProject)
        self.saveAction.setEnabled(False)

        self.undoAction = qt.QAction(
            qt.QIcon(os.path.join(self.iconDir, "icon-undo.png")),
            "Undo last action (Ctrl+Z)", self)
        self.undoAction.setShortcut('Ctrl+Z')
        self.undoAction.triggered.connect(partial(self.slotUndo, -1))
        undoMenu = qt.QMenu()
        subAction = qt.QAction('group sequential changes of same parameter',
                               self)
        subAction.setCheckable(True)
        subAction.setChecked(csi.undoGrouping)
        subAction.triggered.connect(self.undoGroup)
        undoMenu.addAction(subAction)
        undoMenu.addSeparator()
        undoMenu.nHeaderActions = len(undoMenu.actions())
        self.undoAction.setMenu(undoMenu)
        menu = self.undoAction.menu()
        menu.aboutToShow.connect(partial(self.populateUndoMenu, menu))

        self.redoAction = qt.QAction(
            qt.QIcon(os.path.join(self.iconDir, "icon-redo.png")),
            "Redo last undone action (Ctrl+Shift+Z)", self)
        self.redoAction.setShortcut('Ctrl+Shift+Z')
        self.redoAction.triggered.connect(partial(self.slotRedo, -1))
        redoMenu = qt.QMenu()
        self.redoAction.setMenu(redoMenu)
        menu = self.redoAction.menu()
        menu.aboutToShow.connect(partial(self.populateRedoMenu, menu))
        self.setEnableUredoRedo()

        infoAction = qt.QAction(
            qt.QIcon(os.path.join(self.iconDir, "icon-info.png")),
            "About ParSeq…", self)
        infoAction.setShortcut('Ctrl+I')
        infoAction.triggered.connect(self.slotAbout)

        helpAction = qt.QAction(
            qt.QIcon(os.path.join(self.iconDir, "icon-help.png")), "Help…",
            self)
        helpAction.setShortcut('Ctrl+?')
        helpAction.triggered.connect(self.slotAbout)

        self.toolbar = self.addToolBar("Toolbar")
        self.toolbar.setIconSize(qt.QSize(32, 32))
        self.toolbar.addAction(self.loadAction)
        self.toolbar.addAction(self.saveAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.undoAction)
        self.toolbar.addAction(self.redoAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(infoAction)
        self.toolbar.addAction(helpAction)
コード例 #20
0
    def createActions(self):
        action = qt.QAction("E&xit", self)
        action.setShortcuts(qt.QKeySequence.Quit)
        action.setStatusTip("Exit the application")
        action.triggered.connect(self.close)
        self._exitAction = action

        action = qt.QAction("&Open...", self)
        action.setStatusTip("Open a file")
        action.triggered.connect(self.open)
        self._openAction = action

        action = qt.QAction("Open Recent", self)
        action.setStatusTip("Open a recently openned file")
        action.triggered.connect(self.open)
        self._openRecentAction = action

        action = qt.QAction("&About", self)
        action.setStatusTip("Show the application's About box")
        action.triggered.connect(self.about)
        self._aboutAction = action

        action = qt.QAction("&Documentation", self)
        action.setStatusTip("Show the Silx library's documentation")
        action.triggered.connect(self.showDocumentation)
        self._documentationAction = action

        # Plot backend

        action = qt.QAction("Plot rendering backend", self)
        action.setStatusTip("Select plot rendering backend")
        self._plotBackendSelection = action

        menu = qt.QMenu()
        action.setMenu(menu)
        group = qt.QActionGroup(self)
        group.setExclusive(True)

        action = qt.QAction("matplotlib", self)
        action.setStatusTip("Plot will be rendered using matplotlib")
        action.setCheckable(True)
        action.triggered.connect(self.__forceMatplotlibBackend)
        group.addAction(action)
        menu.addAction(action)
        self._usePlotWithMatplotlib = action

        action = qt.QAction("OpenGL", self)
        action.setStatusTip("Plot will be rendered using OpenGL")
        action.setCheckable(True)
        action.triggered.connect(self.__forceOpenglBackend)
        group.addAction(action)
        menu.addAction(action)
        self._usePlotWithOpengl = action

        # Plot image orientation

        action = qt.QAction("Default plot image y-axis orientation", self)
        action.setStatusTip("Select the default y-axis orientation used by plot displaying images")
        self._plotImageOrientation = action

        menu = qt.QMenu()
        action.setMenu(menu)
        group = qt.QActionGroup(self)
        group.setExclusive(True)

        action = qt.QAction("Downward, origin on top", self)
        action.setIcon(self._iconDownward)
        action.setStatusTip("Plot images will use a downward Y-axis orientation")
        action.setCheckable(True)
        action.triggered.connect(self.__forcePlotImageDownward)
        group.addAction(action)
        menu.addAction(action)
        self._useYAxisOrientationDownward = action

        action = qt.QAction("Upward, origin on bottom", self)
        action.setIcon(self._iconUpward)
        action.setStatusTip("Plot images will use a upward Y-axis orientation")
        action.setCheckable(True)
        action.triggered.connect(self.__forcePlotImageUpward)
        group.addAction(action)
        menu.addAction(action)
        self._useYAxisOrientationUpward = action

        # Windows

        action = qt.QAction("Show custom NXdata selector", self)
        action.setStatusTip("Show a widget which allow to create plot by selecting data and axes")
        action.setCheckable(True)
        action.setShortcut(qt.QKeySequence(qt.Qt.Key_F5))
        action.toggled.connect(self.__toggleCustomNxdataWindow)
        self._displayCustomNxdataWindow = action
コード例 #21
0
ファイル: CompareImages.py プロジェクト: schooft/silx
    def __init__(self, parent=None):
        qt.QToolBar.__init__(self, parent)

        self.__compareWidget = None

        menu = qt.QMenu(self)
        self.__visualizationAction = qt.QAction(self)
        self.__visualizationAction.setMenu(menu)
        self.__visualizationAction.setCheckable(False)
        self.addAction(self.__visualizationAction)
        self.__visualizationGroup = qt.QActionGroup(self)
        self.__visualizationGroup.setExclusive(True)
        self.__visualizationGroup.triggered.connect(
            self.__visualizationModeChanged)

        icon = icons.getQIcon("compare-mode-a")
        action = qt.QAction(icon, "Display the first image only", self)
        action.setIconVisibleInMenu(True)
        action.setCheckable(True)
        action.setShortcut(qt.QKeySequence(qt.Qt.Key_A))
        action.setProperty("mode", VisualizationMode.ONLY_A)
        menu.addAction(action)
        self.__aModeAction = action
        self.__visualizationGroup.addAction(action)

        icon = icons.getQIcon("compare-mode-b")
        action = qt.QAction(icon, "Display the second image only", self)
        action.setIconVisibleInMenu(True)
        action.setCheckable(True)
        action.setShortcut(qt.QKeySequence(qt.Qt.Key_B))
        action.setProperty("mode", VisualizationMode.ONLY_B)
        menu.addAction(action)
        self.__bModeAction = action
        self.__visualizationGroup.addAction(action)

        icon = icons.getQIcon("compare-mode-vline")
        action = qt.QAction(icon, "Vertical compare mode", self)
        action.setIconVisibleInMenu(True)
        action.setCheckable(True)
        action.setShortcut(qt.QKeySequence(qt.Qt.Key_V))
        action.setProperty("mode", VisualizationMode.VERTICAL_LINE)
        menu.addAction(action)
        self.__vlineModeAction = action
        self.__visualizationGroup.addAction(action)

        icon = icons.getQIcon("compare-mode-hline")
        action = qt.QAction(icon, "Horizontal compare mode", self)
        action.setIconVisibleInMenu(True)
        action.setCheckable(True)
        action.setShortcut(qt.QKeySequence(qt.Qt.Key_H))
        action.setProperty("mode", VisualizationMode.HORIZONTAL_LINE)
        menu.addAction(action)
        self.__hlineModeAction = action
        self.__visualizationGroup.addAction(action)

        icon = icons.getQIcon("compare-mode-rb-channel")
        action = qt.QAction(icon, "Blue/red compare mode (additive mode)",
                            self)
        action.setIconVisibleInMenu(True)
        action.setCheckable(True)
        action.setShortcut(qt.QKeySequence(qt.Qt.Key_C))
        action.setProperty("mode", VisualizationMode.COMPOSITE_RED_BLUE_GRAY)
        menu.addAction(action)
        self.__brChannelModeAction = action
        self.__visualizationGroup.addAction(action)

        icon = icons.getQIcon("compare-mode-rbneg-channel")
        action = qt.QAction(icon,
                            "Yellow/cyan compare mode (subtractive mode)",
                            self)
        action.setIconVisibleInMenu(True)
        action.setCheckable(True)
        action.setShortcut(qt.QKeySequence(qt.Qt.Key_W))
        action.setProperty("mode",
                           VisualizationMode.COMPOSITE_RED_BLUE_GRAY_NEG)
        menu.addAction(action)
        self.__ycChannelModeAction = action
        self.__visualizationGroup.addAction(action)

        icon = icons.getQIcon("compare-mode-a-minus-b")
        action = qt.QAction(icon, "Raw A minus B compare mode", self)
        action.setIconVisibleInMenu(True)
        action.setCheckable(True)
        action.setShortcut(qt.QKeySequence(qt.Qt.Key_W))
        action.setProperty("mode", VisualizationMode.COMPOSITE_A_MINUS_B)
        menu.addAction(action)
        self.__ycChannelModeAction = action
        self.__visualizationGroup.addAction(action)

        menu = qt.QMenu(self)
        self.__alignmentAction = qt.QAction(self)
        self.__alignmentAction.setMenu(menu)
        self.__alignmentAction.setIconVisibleInMenu(True)
        self.addAction(self.__alignmentAction)
        self.__alignmentGroup = qt.QActionGroup(self)
        self.__alignmentGroup.setExclusive(True)
        self.__alignmentGroup.triggered.connect(self.__alignmentModeChanged)

        icon = icons.getQIcon("compare-align-origin")
        action = qt.QAction(icon, "Align images on their upper-left pixel",
                            self)
        action.setProperty("mode", AlignmentMode.ORIGIN)
        action.setIconVisibleInMenu(True)
        action.setCheckable(True)
        self.__originAlignAction = action
        menu.addAction(action)
        self.__alignmentGroup.addAction(action)

        icon = icons.getQIcon("compare-align-center")
        action = qt.QAction(icon, "Center images", self)
        action.setProperty("mode", AlignmentMode.CENTER)
        action.setIconVisibleInMenu(True)
        action.setCheckable(True)
        self.__centerAlignAction = action
        menu.addAction(action)
        self.__alignmentGroup.addAction(action)

        icon = icons.getQIcon("compare-align-stretch")
        action = qt.QAction(icon, "Stretch the second image on the first one",
                            self)
        action.setProperty("mode", AlignmentMode.STRETCH)
        action.setIconVisibleInMenu(True)
        action.setCheckable(True)
        self.__stretchAlignAction = action
        menu.addAction(action)
        self.__alignmentGroup.addAction(action)

        icon = icons.getQIcon("compare-align-auto")
        action = qt.QAction(icon, "Auto-alignment of the second image", self)
        action.setProperty("mode", AlignmentMode.AUTO)
        action.setIconVisibleInMenu(True)
        action.setCheckable(True)
        self.__autoAlignAction = action
        menu.addAction(action)
        if sift is None:
            action.setEnabled(False)
            action.setToolTip("Sift module is not available")
        self.__alignmentGroup.addAction(action)

        icon = icons.getQIcon("compare-keypoints")
        action = qt.QAction(icon, "Display/hide alignment keypoints", self)
        action.setCheckable(True)
        action.triggered.connect(self.__keypointVisibilityChanged)
        self.addAction(action)
        self.__displayKeypoints = action
コード例 #22
0
    def _pluginClicked(self):
        actionNames = []
        menu = qt.QMenu(self)
        menu.addAction("Reload Plugins")
        actionNames.append("Reload Plugins")
        menu.addAction("Set User Plugin Directory")
        actionNames.append("Set User Plugin Directory")

        if _logger.getEffectiveLevel() == logging.DEBUG:
            text = "Toggle DEBUG mode OFF"
        else:
            text = "Toggle DEBUG mode ON"

        menu.addAction(text)
        menu.addSeparator()
        actionNames.append(text)
        callableKeys = ["Dummy0", "Dummy1", "Dummy2"]
        pluginInstances = self.pluginInstanceDict
        for pluginName in self.pluginList:
            if pluginName in ["PyMcaPlugins.Plugin1DBase", "Plugin1DBase"]:
                continue
            module = sys.modules[pluginName]
            if hasattr(module, 'MENU_TEXT'):
                text = module.MENU_TEXT
            else:
                text = os.path.basename(module.__file__)
                if text.endswith('.pyc'):
                    text = text[:-4]
                elif text.endswith('.py'):
                    text = text[:-3]

            methods = pluginInstances[pluginName].getMethods(
                plottype=self.plot._plotType)
            if not len(methods):
                continue
            elif len(methods) == 1:
                pixmap = pluginInstances[pluginName].getMethodPixmap(
                    methods[0])
                tip = pluginInstances[pluginName].getMethodToolTip(methods[0])
                if pixmap is not None:
                    action = qt.QAction(qt.QIcon(qt.QPixmap(pixmap)), text,
                                        self)
                else:
                    action = qt.QAction(text, self)
                if tip is not None:
                    action.setToolTip(tip)
                menu.addAction(action)
            else:
                menu.addAction(text)
            actionNames.append(text)
            callableKeys.append(pluginName)
        menu.hovered.connect(self._actionHovered)
        a = menu.exec_(qt.QCursor.pos())
        if a is None:
            return None

        idx = actionNames.index(a.text())
        if a.text() == "Reload Plugins":
            n, message = self.getPlugins(exceptions=True)
            if n < 1:
                msg = qt.QMessageBox(self)
                msg.setIcon(qt.QMessageBox.Information)
                msg.setWindowTitle("No plugins")
                msg.setInformativeText(" Problem loading plugins ")
                msg.setDetailedText(message)
                msg.exec_()
            return
        if a.text() == "Set User Plugin Directory":
            dirName = qt.QFileDialog.getExistingDirectory(
                self, "Enter user plugins directory", os.getcwd())
            if len(dirName):
                pluginsDir = self.getPluginDirectoryList()
                pluginsDirList = [pluginsDir[0], dirName]
                self.setPluginDirectoryList(pluginsDirList)
            return
        if "Toggle DEBUG mode" in a.text():
            _toggleLogger()
        key = callableKeys[idx]

        methods = pluginInstances[key].getMethods(plottype=self.plot._plotType)
        if len(methods) == 1:
            idx = 0
        else:
            actionNames = []
            # allow the plugin designer to specify the order
            #methods.sort()
            menu = qt.QMenu(self)
            for method in methods:
                text = method
                pixmap = pluginInstances[key].getMethodPixmap(method)
                tip = pluginInstances[key].getMethodToolTip(method)
                if pixmap is not None:
                    action = qt.QAction(qt.QIcon(qt.QPixmap(pixmap)), text,
                                        self)
                else:
                    action = qt.QAction(text, self)
                if tip is not None:
                    action.setToolTip(tip)
                menu.addAction(action)
                actionNames.append((text, pixmap, tip, action))
            #qt.QObject.connect(menu, qt.SIGNAL("hovered(QAction *)"), self._actionHovered)
            menu.hovered.connect(self._actionHovered)
            a = menu.exec_(qt.QCursor.pos())
            if a is None:
                return None
            idx = -1
            for action in actionNames:
                if a.text() == action[0]:
                    idx = actionNames.index(action)
        try:
            pluginInstances[key].applyMethod(methods[idx])
        except:
            msg = qt.QMessageBox(self)
            msg.setIcon(qt.QMessageBox.Critical)
            msg.setWindowTitle("Plugin error")
            msg.setText("An error has occured while executing the plugin:")
            msg.setInformativeText(str(sys.exc_info()[1]))
            msg.setDetailedText(traceback.format_exc())
            msg.exec_()
コード例 #23
0
    def onCustomContextMenu(self, point):
        if self.transformNode is None:
            return
        selectedIndexes = self.selectionModel().selectedRows()
        lenSelectedIndexes = len(selectedIndexes)
        if lenSelectedIndexes == 0:
            return
        menu = qt.QMenu()

        shape = None
        if lenSelectedIndexes >= 1:
            paths, fullPaths = [], []
            for index in selectedIndexes:
                path = index.data(USE_HDF5_ARRAY_ROLE)
                fullPath = index.data(LOAD_ITEM_PATH_ROLE)
                if path is not None:
                    fullPaths.append(fullPath)
                    paths.append(path)
                    shape = self.model().h5Model.nodeFromIndex(index).obj.shape
                else:
                    paths, fullPaths = [], []
                    break

            if len(paths) == 1:
                strSum = ''
                strSumOf = ''
            else:
                strSum = 'the sum '
                strSumOf = 'of the sum '

            if len(paths) > 0:
                yLbls = self.transformNode.getPropList('qLabel')
                ndims = self.transformNode.getPropList('ndim')
                for iLbl, (yLbl, ndim) in enumerate(zip(yLbls, ndims)):
                    if not shape:
                        continue
                    if len(shape) < ndim:
                        continue
                    elif len(shape) == ndim:
                        menu.addAction("Set {0}as {1} array".format(
                            strSum, yLbl),
                            partial(self.setAsArray, iLbl, paths))
                        if len(paths) == 1:
                            menu.addAction("Set full path as {0} array".format(
                                yLbl),
                                partial(self.setAsArray, iLbl, fullPaths))
                    elif len(shape) > ndim:
                        menu.addAction(
                            "Set a {0}D slice {1}as {2} array".format(
                                ndim, strSumOf, yLbl),
                            partial(self.setAsArray, iLbl, paths,
                                    needSlice=(len(shape), ndim)))
                        if len(paths) == 1:
                            menu.addAction(
                                "Set a {0}D slice {1}of full path as {2} array"
                                .format(ndim, strSumOf, yLbl),
                                partial(self.setAsArray, iLbl, fullPaths,
                                        needSlice=(len(shape), ndim)))
                menu.addSeparator()

            if len(paths) > 1:
                for iLbl, yLbl in enumerate(yLbls):
                    menu.addAction("Set as a list of {0} arrays".format(yLbl),
                                   partial(self.setAsArray, iLbl, paths,
                                           isList=True))
                menu.addSeparator()

        isEnabled = False
        for index in selectedIndexes:
            if index.data(LOAD_DATASET_ROLE) is None:
                break
        else:
            isEnabled = True

        menu.addAction(self.actionLoad)
        self.actionLoad.setEnabled(isEnabled)
        if lenSelectedIndexes > 1:
            actionN = menu.addAction(
                "Concatenate {0} datasets and load as one".format(
                    lenSelectedIndexes))
            actionN.setEnabled(isEnabled)

        menu.addSeparator()
        nodeType0 = self.model().nodeType(selectedIndexes[0])
        menu.addAction(self.actionSynchronize)
        self.actionSynchronize.setEnabled(
            nodeType0 in (NODE_HDF5_HEAD, NODE_HDF5))

        if nodeType0 == NODE_FS:
            try:
                fname = self.model().filePath(selectedIndexes[0])
                if not qt.QFileInfo(fname).isDir():
                    menu.addSeparator()
                    menu.addAction(self.actionViewTextFile)
            except Exception:
                pass

        if hasattr(self, 'ModelTest'):
            menu.addSeparator()
            menu.addAction(self.actionTestModel)

        menu.exec_(
            self.transformNode.widget.files.viewport().mapToGlobal(point))
コード例 #24
0
    def __init__(self, **kwargs):
        super(XsocsPlot2D, self).__init__(**kwargs)

        self.setActiveCurveHandling(False)
        self.setKeepDataAspectRatio(True)

        self.__sigPlotConnected = False
        self.__pointSelectionEnabled = False
        self.__showSelectedCoordinates = False
        self.__showMousePosition = False

        self.__logScatter = False
        self.__colormap = cm.jet
        self.__values = {}
        self.__cmapDialog = None

        pointDock = self.__pointWidget = DoublePointDock()

        features = (Qt.QDockWidget.DockWidgetVerticalTitleBar
                    | Qt.QDockWidget.DockWidgetClosable)
        pointDock.setFeatures(features)
        pointDock.sizeHint = lambda: Qt.QSize()
        self.addDockWidget(Qt.Qt.BottomDockWidgetArea, pointDock)
        pointDockAction = pointDock.toggleViewAction()
        pointDockAction.setIcon(getQIcon('crosshair'))
        pointDockAction.setIconVisibleInMenu(True)

        pointDockBn = Qt.QToolButton()
        pointDockBn.setDefaultAction(pointDockAction)
        closeButton = Qt.QToolButton()
        style = Qt.QApplication.style()
        icon = style.standardIcon(Qt.QStyle.SP_TitleBarCloseButton)
        closeButton.setIcon(icon)
        closeButton.setFixedSize(closeButton.iconSize())
        closeButton.clicked.connect(pointDockAction.trigger)
        pointDock.setTitleBarWidget(closeButton)

        toolbars = self.findChildren(Qt.QToolBar)
        for toolbar in toolbars:
            toolbar.hide()

        centralWid = self.centralWidget()

        centralWid.installEventFilter(self)

        self.__optionsBase = optionsBase = Qt.QWidget(centralWid)
        optionsLayout = Qt.QHBoxLayout(optionsBase)
        optionsLayout.setContentsMargins(0, 0, 0, 0)
        optionsLayout.setSpacing(0)

        style = Qt.QApplication.style()
        size = style.pixelMetric(Qt.QStyle.PM_SmallIconSize)
        icon = style.standardIcon(Qt.QStyle.SP_ArrowRight)
        showBarBn = Qt.QToolButton()
        showBarBn.setIcon(icon)
        showBarBn.setFixedWidth(size)
        showBarBn.clicked.connect(self.__showBarBnClicked)
        showBarBn.setAutoFillBackground(True)
        self.__hidden = True
        self.__firstShow = True

        self.__optionsBaseA = optionsBaseA = Qt.QWidget()
        optionsLayoutA = Qt.QHBoxLayout(optionsBaseA)
        optionsLayoutA.setContentsMargins(0, 0, 0, 0)
        optionsLayoutA.setSpacing(0)
        rstZoomAction = self.resetZoomAction
        rstToolBn = Qt.QToolButton()
        rstToolBn.setDefaultAction(rstZoomAction)

        optionsLayoutA.addWidget(rstToolBn)
        optionsLayoutA.addWidget(showBarBn)

        self.__optionsBaseB = optionsBaseB = Qt.QWidget()
        optionsLayoutB = Qt.QHBoxLayout(optionsBaseB)
        optionsLayoutB.setContentsMargins(0, 0, 0, 0)
        optionsLayoutB.setSpacing(0)

        # coordinates dock action
        pointDockBn = Qt.QToolButton()
        pointDockBn.setDefaultAction(pointDockAction)
        optionsLayoutB.addWidget(pointDockBn)

        # colormap dialog action
        self.__colormapBn = colormapBn = Qt.QToolButton()
        colormapBn.setDisabled(True)
        colormapBn.setIcon(getQIcon('colormap'))
        colormapBn.clicked.connect(self.__colormapBnClicked)
        optionsLayoutB.addWidget(colormapBn)

        icon = getKmapIcon('gears')
        options = Qt.QToolButton()

        options.setToolTip('Options')
        options.setIcon(icon)
        options.setPopupMode(Qt.QToolButton.InstantPopup)

        menu = Qt.QMenu()

        # save scatter as 3D
        self.__save2DAction = action = Qt.QAction(
            getKmapIcon('save_2dscatter'), 'Save "2D" scatter', self)
        action.setIconVisibleInMenu(True)
        action.triggered.connect(self.__save2DTriggered)
        action.setEnabled(False)
        menu.addAction(action)

        # save to file action
        try:
            action = self.getSaveAction()
        except AttributeError:
            action = self.saveAction
        action.setIconVisibleInMenu(True)
        menu.addAction(action)

        # print action
        try:
            action = self.getPrintAction()
        except AttributeError:
            action = self.printAction
        action.setIconVisibleInMenu(True)
        menu.addAction(action)

        # screenshot action
        try:
            action = self.getCopyAction()
        except AttributeError:
            action = self.copyAction
        action.setIconVisibleInMenu(True)
        menu.addAction(action)

        # grid action
        try:
            action = self.getGridAction()
        except AttributeError:
            action = self.gridAction
        action.setIconVisibleInMenu(True)
        menu.addAction(action)

        # crosshair action
        try:
            action = self.getCrosshairAction()
        except AttributeError:
            action = self.crosshairAction
        action.setIconVisibleInMenu(True)
        menu.addAction(action)

        # pan action
        try:
            action = self.getPanWithArrowKeysAction()
        except AttributeError:
            action = self.panWithArrowKeysAction
        action.setIconVisibleInMenu(True)
        menu.addAction(action)

        # # x log scale
        # self.xAxisLogarithmicAction.setIconVisibleInMenu(True)
        # menu.addAction(self.xAxisLogarithmicAction)
        #
        # # y log scale
        # self.yAxisLogarithmicAction.setIconVisibleInMenu(True)
        # menu.addAction(self.yAxisLogarithmicAction)

        # x autoscale action
        self.xAxisAutoScaleAction.setIconVisibleInMenu(True)
        menu.addAction(self.xAxisAutoScaleAction)

        # y autoscale action
        self.yAxisAutoScaleAction.setIconVisibleInMenu(True)
        menu.addAction(self.yAxisAutoScaleAction)

        # curvestyle action
        self.curveStyleAction.setIconVisibleInMenu(True)
        menu.addAction(self.curveStyleAction)

        # aspect ratio action
        aspectMenu = self.keepDataAspectRatioButton.menu()
        if aspectMenu is not None:
            action = aspectMenu.menuAction()
            action.setIconVisibleInMenu(True)
            menu.addAction(action)
        else:
            self.keepDataAspectRatioAction.setIconVisibleInMenu(True)
            menu.addAction(self.keepDataAspectRatioAction)

        options.setMenu(menu)

        optionsLayoutB.addWidget(options)

        optionsLayout.addWidget(optionsBaseB)
        optionsLayout.addWidget(optionsBaseA)

        self.setShowMousePosition(self.__showMousePosition)
        self.setShowSelectedCoordinates(self.__showSelectedCoordinates)
        self.setPointSelectionEnabled(self.__pointSelectionEnabled)