def __init__(self, parent=None, plot=None, stats=None, rois=None): qt.QMainWindow.__init__(self, parent) toolbar = qt.QToolBar(self) icon = icons.getQIcon('add') self._rois = list(rois) if rois is not None else [] self._addAction = qt.QAction(icon, 'add item/roi', toolbar) self._addAction.triggered.connect(self._addRoiStatsItem) icon = icons.getQIcon('rm') self._removeAction = qt.QAction(icon, 'remove item/roi', toolbar) self._removeAction.triggered.connect(self._removeCurrentRow) toolbar.addAction(self._addAction) toolbar.addAction(self._removeAction) self.addToolBar(toolbar) self._plot = plot self._statsROITable = _StatsROITable(parent=self, plot=self._plot) self.setStats(stats=stats) self.setCentralWidget(self._statsROITable) self.setWindowFlags(qt.Qt.Widget) # expose API self._setUpdateMode = self._statsROITable.setUpdateMode self._updateAllStats = self._statsROITable._updateAllStats # setup self._statsROITable.setSelectionBehavior(qt.QTableWidget.SelectRows)
def __createPlot(self, parent): plot = silx.gui.plot.PlotWidget(parent=parent) plot.setKeepDataAspectRatio(True) plot.setDataMargins(0.1, 0.1, 0.1, 0.1) plot.setGraphXLabel("X") plot.setGraphYLabel("Y") colormap = CalibrationContext.instance().getRawColormap() plot.setDefaultColormap(colormap) from silx.gui.plot import tools toolBar = tools.InteractiveModeToolBar(parent=self, plot=plot) plot.addToolBar(toolBar) toolBar = tools.ImageToolBar(parent=self, plot=plot) colormapDialog = CalibrationContext.instance().getColormapDialog() toolBar.getColormapAction().setColorDialog(colormapDialog) plot.addToolBar(toolBar) toolBar = qt.QToolBar(self) plot3dAction = qt.QAction(self) plot3dAction.setIcon(icons.getQIcon("pyfai:gui/icons/3d")) plot3dAction.setText("3D visualization") plot3dAction.setToolTip("Display a 3D visualization of the detector") plot3dAction.triggered.connect(self.__display3dDialog) toolBar.addAction(plot3dAction) plot.addToolBar(toolBar) return plot
def __init__(self, plot, parent=None): assert isinstance( plot, RixsPlot2D), "'plot' should be an instance of RixsPlot2D" _title = f"Plot {plot._index} : cursors infos" super(RixsROIDockWidget, self).__init__(_title, parent=parent) self._roiManager = RixsROIManager(plot) #: Create the table widget displaying infos self._roiTable = RegionOfInterestTableWidget() self._roiTable.setRegionOfInterestManager(self._roiManager) #: Create a toolbar containing buttons for all ROI 'drawing' modes self._roiToolbar = qt.QToolBar() self._roiToolbar.setIconSize(qt.QSize(16, 16)) for roiClass in self._roiManager.getSupportedRoiClasses(): # Create a tool button and associate it with the QAction of each # mode action = self._roiManager.getInteractionModeAction(roiClass) self._roiToolbar.addAction(action) # Add the region of interest table and the buttons to a dock widget self._widget = qt.QWidget() self._layout = qt.QVBoxLayout() self._widget.setLayout(self._layout) self._layout.addWidget(self._roiToolbar) self._layout.addWidget(self._roiTable) self.setWidget(self._widget) self.visibilityChanged.connect(self.roiDockVisibilityChanged)
def __createPlotToolBar(self, plot): toolBar = qt.QToolBar("Plot tools", plot) from silx.gui.plot.actions import control from silx.gui.plot.actions import io from silx.gui.plot.actions import histogram toolBar.addAction(control.ResetZoomAction(plot, toolBar)) toolBar.addAction(control.ZoomInAction(plot, toolBar)) toolBar.addAction(control.ZoomOutAction(plot, toolBar)) toolBar.addSeparator() toolBar.addAction(control.ColormapAction(plot, toolBar)) toolBar.addAction(histogram.PixelIntensitiesHistoAction(plot, toolBar)) toolBar.addSeparator() toolBar.addAction(io.CopyAction(plot, toolBar)) toolBar.addAction(io.SaveAction(plot, toolBar)) toolBar.addAction(io.PrintAction(plot, toolBar)) stretch = qt.QWidget(self) stretch.setSizePolicy(qt.QSizePolicy.Expanding, qt.QSizePolicy.Fixed) toolBar.addWidget(stretch) self.__options = self.__createOptionsWidget() toolBar.addWidget(self.__options) return toolBar
def _createToolBar(self, title, parent): """Create a QToolBar from the QAction of the PlotWindow. :param str title: The title of the QMenu :param qt.QWidget parent: See :class:`QToolBar` """ toolbar = qt.QToolBar(title, parent) # Order widgets with actions objects = self.group.actions() # Add push buttons to list index = objects.index(self.colormapAction) objects.insert(index + 1, self.keepDataAspectRatioButton) objects.insert(index + 2, self.yAxisInvertedButton) for obj in objects: if isinstance(obj, qt.QAction): toolbar.addAction(obj) else: # keep reference to toolbutton's action for changing visibility if obj is self.keepDataAspectRatioButton: self.keepDataAspectRatioAction = toolbar.addWidget(obj) elif obj is self.yAxisInvertedButton: self.yAxisInvertedAction = toolbar.addWidget(obj) else: raise RuntimeError() alpha_slider = ActiveImageAlphaSlider(parent=self, plot=self) alpha_slider.setOrientation(qt.Qt.Horizontal) toolbar.addWidget(alpha_slider) return toolbar
def __createTreeWindow(self, treeView): toolbar = qt.QToolBar(self) toolbar.setIconSize(qt.QSize(16, 16)) toolbar.setStyleSheet("QToolBar { border: 0px }") action = qt.QAction(toolbar) action.setIcon(icons.getQIcon("view-refresh")) action.setText("Refresh") action.setToolTip("Refresh all selected items") action.triggered.connect(self.__refreshSelected) action.setShortcut(qt.QKeySequence(qt.Qt.Key_F5)) toolbar.addAction(action) treeView.addAction(action) self.__refreshAction = action # Another shortcut for refresh action = qt.QAction(toolbar) action.setShortcut(qt.QKeySequence(qt.Qt.ControlModifier + qt.Qt.Key_R)) treeView.addAction(action) action.triggered.connect(self.__refreshSelected) action = qt.QAction(toolbar) # action.setIcon(icons.getQIcon("view-refresh")) action.setText("Close") action.setToolTip("Close selected item") action.triggered.connect(self.__removeSelected) action.setShortcut(qt.QKeySequence(qt.Qt.Key_Delete)) treeView.addAction(action) self.__closeAction = action toolbar.addSeparator() action = qt.QAction(toolbar) action.setIcon(icons.getQIcon("tree-expand-all")) action.setText("Expand all") action.setToolTip("Expand all selected items") action.triggered.connect(self.__expandAllSelected) action.setShortcut(qt.QKeySequence(qt.Qt.ControlModifier + qt.Qt.Key_Plus)) toolbar.addAction(action) treeView.addAction(action) self.__expandAllAction = action action = qt.QAction(toolbar) action.setIcon(icons.getQIcon("tree-collapse-all")) action.setText("Collapse all") action.setToolTip("Collapse all selected items") action.triggered.connect(self.__collapseAllSelected) action.setShortcut(qt.QKeySequence(qt.Qt.ControlModifier + qt.Qt.Key_Minus)) toolbar.addAction(action) treeView.addAction(action) self.__collapseAllAction = action widget = qt.QWidget(self) layout = qt.QVBoxLayout(widget) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) layout.addWidget(toolbar) layout.addWidget(treeView) return widget
def __init__(self, parent=None): super(MyPlotWindow, self).__init__(parent) # Create a PlotWidget self._plot = PlotWidget(parent=self) # Create a colorbar linked with the PlotWidget colorBar = ColorBarWidget(parent=self, plot=self._plot) # Make ColorBarWidget background white by changing its palette colorBar.setAutoFillBackground(True) palette = colorBar.palette() palette.setColor(qt.QPalette.Background, qt.Qt.white) palette.setColor(qt.QPalette.Window, qt.Qt.white) colorBar.setPalette(palette) # Combine the ColorBarWidget and the PlotWidget as # this QMainWindow's central widget gridLayout = qt.QGridLayout() gridLayout.setSpacing(0) gridLayout.setContentsMargins(0, 0, 0, 0) gridLayout.addWidget(self._plot, 0, 0) gridLayout.addWidget(colorBar, 0, 1) gridLayout.setRowStretch(0, 1) gridLayout.setColumnStretch(0, 1) centralWidget = qt.QWidget(self) centralWidget.setLayout(gridLayout) self.setCentralWidget(centralWidget) # Add ready to use toolbar with zoom and pan interaction mode buttons interactionToolBar = tools.InteractiveModeToolBar(parent=self, plot=self._plot) self.addToolBar(interactionToolBar) # Add toolbar actions to activate keyboard shortcuts self.addActions(interactionToolBar.actions()) # Add a new toolbar toolBar = qt.QToolBar("Plot Tools", self) self.addToolBar(toolBar) # Add actions from silx.gui.plot.action to the toolbar resetZoomAction = actions.control.ResetZoomAction(parent=self, plot=self._plot) toolBar.addAction(resetZoomAction) # Add tool buttons from silx.gui.plot.PlotToolButtons aspectRatioButton = PlotToolButtons.AspectToolButton(parent=self, plot=self._plot) toolBar.addWidget(aspectRatioButton) # Add ready to use toolbar with copy, save and print buttons outputToolBar = tools.OutputToolBar(parent=self, plot=self._plot) self.addToolBar(outputToolBar) # Add toolbar actions to activate keyboard shortcuts self.addActions(outputToolBar.actions()) # Add limits tool bar from silx.gui.plot.PlotTools limitsToolBar = tools.LimitsToolBar(parent=self, plot=self._plot) self.addToolBar(qt.Qt.BottomToolBarArea, limitsToolBar)
def _createPreviewToolbar(self, parent, dataPreviewWidget, dataSelectorWidget): plot = dataPreviewWidget.plot() toolbar = qt.QToolBar(parent) toolbar.setIconSize(qt.QSize(16, 16)) toolbar.setStyleSheet("QToolBar { border: 0px }") toolbar.addAction(actions.mode.ZoomModeAction(plot, parent)) toolbar.addAction(actions.mode.PanModeAction(plot, parent)) toolbar.addSeparator() toolbar.addAction(actions.control.ResetZoomAction(plot, parent)) toolbar.addSeparator() toolbar.addAction(actions.control.ColormapAction(plot, parent)) return toolbar
def toolBar(self, options=None, rois=None): """ shapes : list options : list """ roiActions = self._createRoiActions() if rois is not None: # this wont work if shape is a string and not an array diff = set(rois) - set(roiActions.keys()) if len(diff) > 0: raise ValueError('Unknown roi(s) {0}.'.format(diff)) else: rois = roiActions.keys() try: rois.pop('zoom') except: pass try: rois.pop('edit') except: pass rois = ['zoom', 'edit'] + rois optionActions = self._createOptionActions() # TODO : find a better way to ensure that the order of # actions returned is always the same optionNames = sorted(optionActions.keys()) if options is not None: # this wont work if shape is a string and not an array diff = set(options) - set(optionNames) if len(diff) > 0: raise ValueError('Unknown options(s) {0}.'.format(diff)) options = [option for option in optionNames if option in options] else: options = optionNames keepRoiActions = [roiActions[roi] for roi in rois] keepOptionActions = [optionActions[option] for option in options] toolBar = qt.QToolBar('Roi') # toolBar.addWidget(qt.QLabel('Roi')) for action in keepRoiActions: toolBar.addAction(action) toolBar.addSeparator() for action in keepOptionActions: toolBar.addAction(action) return toolBar
def __createPlotToolBar(self, plot): from silx.gui.plot import tools toolBar = tools.InteractiveModeToolBar(parent=self, plot=plot) plot.addToolBar(toolBar) toolBar = tools.ImageToolBar(parent=self, plot=plot) colormapDialog = CalibrationContext.instance().getColormapDialog() toolBar.getColormapAction().setColorDialog(colormapDialog) plot.addToolBar(toolBar) toolBar = qt.QToolBar("Plot tools", plot) self.__options = self.__createOptionsWidget() toolBar.addWidget(self.__options) plot.addToolBar(toolBar)
def __createPlots(self, parent): margin = 0.02 plot1d = silx.gui.plot.PlotWidget(parent) plot1d.setGraphXLabel("Radial unit") plot1d.setGraphYLabel("Intensity") plot1d.setGraphGrid(False) plot1d.setDataMargins(margin, margin, margin, margin) plot2d = silx.gui.plot.PlotWidget(parent) plot2d.setGraphXLabel("Radial unit") plot2d.setGraphYLabel(r"Azimuthal angle $\chi$ (°)") plot2d.sigInteractiveModeChanged.connect(self.__syncModeToPlot1d) plot2d.setDataMargins(margin, margin, margin, margin) handle = plot2d.getWidgetHandle() handle.setContextMenuPolicy(qt.Qt.CustomContextMenu) handle.customContextMenuRequested.connect(self.__plot2dContextMenu) from silx.gui.plot import tools toolBar = tools.InteractiveModeToolBar(parent=self, plot=plot2d) plot2d.addToolBar(toolBar) toolBar = tools.ImageToolBar(parent=self, plot=plot2d) colormapDialog = CalibrationContext.instance().getColormapDialog() toolBar.getColormapAction().setColorDialog(colormapDialog) previousResetZoomAction = toolBar.getResetZoomAction() resetZoomAction = qt.QAction(toolBar) resetZoomAction.triggered.connect(self.resetZoom) resetZoomAction.setIcon(previousResetZoomAction.icon()) resetZoomAction.setText(previousResetZoomAction.text()) resetZoomAction.setToolTip(previousResetZoomAction.toolTip()) toolBar.insertAction(previousResetZoomAction, resetZoomAction) previousResetZoomAction.setVisible(False) self.__resetZoomAction = resetZoomAction plot2d.addToolBar(toolBar) ownToolBar = qt.QToolBar(plot2d) from silx.gui.plot import actions logAction = actions.control.YAxisLogarithmicAction(parent=ownToolBar, plot=plot1d) logAction.setToolTip("Logarithmic y-axis intensity when checked") ownToolBar.addAction(logAction) plot2d.addToolBar(ownToolBar) action = qt.QAction(ownToolBar) action.setIcon(silx.gui.icons.getQIcon("document-save")) action.triggered.connect(self.__saveAsCsv) action.setToolTip("Save 1D integration as CSV file") self.__saveResult1dAction = action ownToolBar.addAction(action) return plot1d, plot2d
def setUp(self): super(TestNamedImageAlphaSlider, self).setUp() self.plot = PlotWidget() self.aslider = AlphaSlider.NamedImageAlphaSlider(plot=self.plot) self.aslider.setOrientation(qt.Qt.Horizontal) toolbar = qt.QToolBar("plot", self.plot) toolbar.addWidget(self.aslider) self.plot.addToolBar(toolbar) self.plot.show() self.qWaitForWindowExposed(self.plot) self.mouseMove(self.plot) # Move to center self.qapp.processEvents()
def __createPlotToolBar(self, plot): from silx.gui.plot import tools toolBar = tools.InteractiveModeToolBar(parent=self, plot=plot) plot.addToolBar(toolBar) toolBar = tools.ImageToolBar(parent=self, plot=plot) colormapDialog = CalibrationContext.instance().getColormapDialog() toolBar.getColormapAction().setColorDialog(colormapDialog) plot.addToolBar(toolBar) toolBar = qt.QToolBar(self) plot3dAction = qt.QAction(self) plot3dAction.setIcon(icons.getQIcon("pyfai:gui/icons/3d")) plot3dAction.setText("3D visualization") plot3dAction.setToolTip("Display a 3D visualization of the sample stage") plot3dAction.triggered.connect(self.__display3dDialog) toolBar.addAction(plot3dAction) plot.addToolBar(toolBar)
def createEditor(self, parent, option, index): if not index.isValid(): return super(_PeakToolItemDelegate, self).createEditor(parent, option, index) editor = qt.QToolBar(parent=parent) editor.setIconSize(qt.QSize(32, 32)) editor.setStyleSheet("QToolBar { border: 0px }") editor.setMinimumSize(32, 32) editor.setMaximumSize(32, 32) editor.setSizePolicy(qt.QSizePolicy.Fixed, qt.QSizePolicy.Fixed) remove = qt.QAction(editor) remove.setIcon(icons.getQIcon("pyfai:gui/icons/remove-peak")) remove._customSignal = None persistantIndex = qt.QPersistentModelIndex(index) remove.triggered.connect(functools.partial(self.__removePeak, persistantIndex)) editor.addAction(remove) return editor
def __createPlotToolBar(self, plot): toolBar = qt.QToolBar("Plot tools", plot) from silx.gui.plot.actions import control from silx.gui.plot.actions import io from silx.gui.plot.actions import histogram toolBar.addAction(control.ResetZoomAction(plot, toolBar)) toolBar.addAction(control.ZoomInAction(plot, toolBar)) toolBar.addAction(control.ZoomOutAction(plot, toolBar)) toolBar.addSeparator() toolBar.addAction(control.ColormapAction(plot, toolBar)) toolBar.addAction(histogram.PixelIntensitiesHistoAction(plot, toolBar)) toolBar.addSeparator() toolBar.addAction(io.CopyAction(plot, toolBar)) toolBar.addAction(io.SaveAction(plot, toolBar)) toolBar.addAction(io.PrintAction(plot, toolBar)) return toolBar
def __init__(self, parent=None): super(MyPlotWidget, self).__init__(parent) # Add a tool bar to PlotWidget toolBar = qt.QToolBar("Plot Tools", self) self.addToolBar(toolBar) # Add actions from silx.gui.plot.action to the toolbar resetZoomAction = actions.control.ResetZoomAction(self, self) toolBar.addAction(resetZoomAction) # Add tool buttons from silx.gui.plot.PlotToolButtons aspectRatioButton = PlotToolButtons.AspectToolButton(parent=self, plot=self) toolBar.addWidget(aspectRatioButton) # Add limits tool bar from silx.gui.plot.PlotTools limitsToolBar = LimitsToolBar(parent=self, plot=self) self.addToolBar(qt.Qt.BottomToolBarArea, limitsToolBar) self._initColorBar()
def _test(self, positionWidget, converterNames, **kwargs): """General test of PositionInfo. - Add it to a toolbar and - Move mouse around the center of the PlotWindow. """ toolBar = qt.QToolBar() self.plot.addToolBar(qt.Qt.BottomToolBarArea, toolBar) toolBar.addWidget(positionWidget) converters = positionWidget.getConverters() self.assertEqual(len(converters), len(converterNames)) for index, name in enumerate(converterNames): self.assertEqual(converters[index][0], name) with TestLogging(tools.__name__, **kwargs): # Move mouse to center center = self.plot.size() / 2 self.mouseMove(self.plot, pos=(center.width(), center.height())) # Move out self.mouseMove(self.plot, pos=(1, 1))
def _test(self, positionWidget, converterNames, **kwargs): """General test of PositionInfo. - Add it to a toolbar and - Move mouse around the center of the PlotWindow. """ toolBar = qt.QToolBar() self.plot.addToolBar(qt.Qt.BottomToolBarArea, toolBar) toolBar.addWidget(positionWidget) converters = positionWidget.getConverters() self.assertEqual(len(converters), len(converterNames)) for index, name in enumerate(converterNames): self.assertEqual(converters[index][0], name) with TestLogging(PlotTools.__name__, **kwargs): # Move mouse to center self.mouseMove(self.plot) self.mouseMove(self.plot, pos=(1, 1)) self.qapp.processEvents() self.qWait(100)
def __init__(self, parent=None): super(Plot3DWindow, self).__init__(parent) if parent is not None: # behave as a widget self.setWindowFlags(qt.Qt.Widget) self._plot3D = Plot3DWidget() self.setCentralWidget(self._plot3D) toolbar = InteractiveModeToolBar(parent=self) toolbar.setPlot3DWidget(self._plot3D) self.addToolBar(toolbar) self.addActions(toolbar.actions()) toolbar = qt.QToolBar(self) toolbar.addWidget(ViewpointToolButton(plot3D=self._plot3D)) toolbar.addAction(RotateViewport(parent=toolbar, plot3d=self._plot3D)) self.addToolBar(toolbar) toolbar = OutputToolBar(parent=self) toolbar.setPlot3DWidget(self._plot3D) self.addToolBar(toolbar) self.addActions(toolbar.actions())
def _initInteractionToolBar(self): self._interactionToolbar = qt.QToolBar() self._interactionToolbar.setEnabled(False) group = qt.QActionGroup(self._interactionToolbar) group.setExclusive(True) self._cameraAction = qt.QAction(None) self._cameraAction.setText('camera') self._cameraAction.setCheckable(True) self._cameraAction.setToolTip('Control camera') self._cameraAction.setChecked(True) group.addAction(self._cameraAction) self._planeAction = qt.QAction(None) self._planeAction.setText('plane') self._planeAction.setCheckable(True) self._planeAction.setToolTip('Control cutting plane') group.addAction(self._planeAction) group.triggered.connect(self._interactionChanged) self._interactionToolbar.addActions(group.actions()) self.addToolBar(self._interactionToolbar)
def __init__(self, parent=None): super(IECwindow, self).__init__(parent) #qt.QMainWindow.__init__(self) #self.setWindowTitle("Plot with synchronized axes") widget = qt.QWidget(self) self.setCentralWidget(widget) self.updateThread = None layout = qt.QGridLayout() widget.setLayout(layout) backend = "mpl" #self.plot2d_cormap = plot.Plot2D(parent=widget, backend=backend) #self.plot2d.setInteractiveMode('pan') self.plot1d_chromo = self.createChromoPLot(widget, backend) self.plot1d_chromo.getYAxis().setLimits(-0.05, 1.05) self.plot1d_chromo.getYAxis().setAutoScale(flag=False) self.plot1d_log = plot.Plot1D(parent=widget, backend=backend) self.plot1d_subchromo = self.createChromoPLot(widget, backend) self.plot1d_ratio = self.createChromoPLot(widget, backend) self.plot1d_log.getYAxis().setScale("log") self.frameSlider = self.createFrameSlider(widget) self.diffSlider = self.createDiffSlider(widget) self.saveButton = self.createSaveButton(widget) self.l1 = QLabel(str(self.plot1d_chromo.getXAxis().getLimits()[0]) + "," + str(self.frameSlider.minimum), parent=widget) self.l1.setAlignment(Qt.AlignCenter) clearAction = ClearButton(self.plot1d_ratio, parent=widget) #actions_menu = self.plot1d_ratio.menuBar().addMenu("Custom actions") toolbar = qt.QToolBar("My toolbar") self.plot1d_ratio.addToolBar(toolbar) #actions_menu.addAction(clearAction) toolbar.addAction(clearAction) self.constraint3 = SyncAxes([ self.plot1d_chromo.getXAxis(), self.plot1d_subchromo.getXAxis(), self.plot1d_ratio.getXAxis() ]) #],self.plot2d_cormap.getXAxis(),self.plot2d_cormap.getYAxis()]) #self.constraint3 = SyncAxes([self.plot1d_chromo.getXAxis(), self.plot1d_ratio.getXAxis()]) #self.constraint1 = SyncAxes([self.plot1d_log.getXAxis(), self.plot1d_loglog.getXAxis(),self.plot1d_kratky.getXAxis(),self.plot1d_holtzer.getXAxis()], syncScale=False) #self.plot1d_kratky.getYAxis().setLimits(0,medfilt(I*self.q*self.q,21).max()) layout.addWidget(self.plot1d_chromo, 0, 0) layout.addWidget(self.plot1d_log, 0, 1, 2, 1) layout.addWidget(self.frameSlider, 1, 0) layout.addWidget(self.diffSlider, 2, 0) layout.addWidget(self.plot1d_subchromo, 3, 0) layout.addWidget(self.plot1d_ratio, 3, 1) layout.addWidget(self.saveButton, 4, 1) #layout.addWidget(self.l1) currentRoi = self.plot1d_log.getCurvesRoiWidget().getRois() print(currentRoi) if len(currentRoi) == 0: currentRoi = OrderedDict( {"low-q range": { "from": 0.1, "to": 1, "type": "X" }}) else: currentRoi.update( {"low-q range": { "from": 0.1, "to": 1, "type": "X" }}) print(currentRoi) self.plot1d_log.getCurvesRoiWidget().setRois(currentRoi)
xv, yv = numpy.meshgrid(x, x) signal = numpy.exp(-(xv**2 / 0.15**2 + yv**2 / 0.25**2)) # add noise signal += 0.3 * numpy.random.random(size=signal.shape) return signal app = qt.QApplication([]) # Start QApplication # Create the plot widget and add an image plot = Plot2D() plot.getDefaultColormap().setName('viridis') plot.setKeepDataAspectRatio(True) plot.addImage(dummy_image()) toolbar = qt.QToolBar() toolbar.addAction(control_actions.OpenGLAction(parent=toolbar, plot=plot)) plot.addToolBar(toolbar) # Create the object controlling the ROIs and set it up roiManager = RegionOfInterestManager(plot) roiManager.setColor('pink') # Set the color of ROI # Set the name of each created region of interest def updateAddedRegionOfInterest(roi): """Called for each added region of interest: set the name""" if roi.getName() == '': roi.setName('ROI %d' % len(roiManager.getRois())) if isinstance(roi, LineMixIn): roi.setLineWidth(1)
def main(argv=None): """Display an image from a file in an :class:`ImageView` widget. :param argv: list of command line arguments or None (the default) to use sys.argv. :type argv: list of str :return: Exit status code :rtype: int :raises IOError: if no image can be loaded from the file """ import argparse import os.path from silx.third_party.EdfFile import EdfFile # Command-line arguments parser = argparse.ArgumentParser( description='Browse the images of an EDF file.') parser.add_argument( '-o', '--origin', nargs=2, type=float, default=(0., 0.), help="""Coordinates of the origin of the image: (x, y). Default: 0., 0.""") parser.add_argument( '-s', '--scale', nargs=2, type=float, default=(1., 1.), help="""Scale factors applied to the image: (sx, sy). Default: 1., 1.""") parser.add_argument( '-l', '--log', action="store_true", help="Use logarithm normalization for colormap, default: Linear.") parser.add_argument( 'filename', nargs='?', help='EDF filename of the image to open') args = parser.parse_args(args=argv) # Open the input file if not args.filename: logger.warning('No image file provided, displaying dummy data') edfFile = None data = numpy.arange(1024 * 1024.).reshape(1024, 1024) nbFrames = 1 else: if not os.path.isfile(args.filename): raise IOError('No input file: %s' % args.filename) else: edfFile = EdfFile(args.filename) data = edfFile.GetData(0) nbFrames = edfFile.GetNumImages() if nbFrames == 0: raise IOError( 'Cannot read image(s) from file: %s' % args.filename) global app # QApplication must be global to avoid seg fault on quit app = qt.QApplication([]) sys.excepthook = qt.exceptionHandler mainWindow = ImageViewMainWindow() mainWindow.setAttribute(qt.Qt.WA_DeleteOnClose) if args.log: # Use log normalization by default colormap = mainWindow.getDefaultColormap() colormap['normalization'] = 'log' mainWindow.setColormap(colormap) mainWindow.setImage(data, origin=args.origin, scale=args.scale) if edfFile is not None and nbFrames > 1: # Add a toolbar for multi-frame EDF support multiFrameToolbar = qt.QToolBar('Multi-frame') multiFrameToolbar.addWidget(qt.QLabel( 'Frame [0-%d]:' % (nbFrames - 1))) spinBox = qt.QSpinBox() spinBox.setRange(0, nbFrames - 1) def updateImage(index): mainWindow.setImage(edfFile.GetData(index), origin=args.origin, scale=args.scale, reset=False) spinBox.valueChanged[int].connect(updateImage) multiFrameToolbar.addWidget(spinBox) mainWindow.addToolBar(multiFrameToolbar) mainWindow.show() mainWindow.setFocus(qt.Qt.OtherFocusReason) return app.exec_()
__date__ = "25/07/2017" import numpy from silx.gui import qt from silx.gui.plot import PlotWidget from silx.gui.plot import PrintPreviewToolButton app = qt.QApplication([]) x = numpy.arange(1000) # first widget has a standalone print preview action pw1 = PlotWidget() pw1.setWindowTitle("Widget 1 with standalone print preview") toolbar1 = qt.QToolBar(pw1) toolbutton1 = PrintPreviewToolButton.PrintPreviewToolButton(parent=toolbar1, plot=pw1) pw1.addToolBar(toolbar1) toolbar1.addWidget(toolbutton1) pw1.show() pw1.addCurve(x, numpy.tan(x * 2 * numpy.pi / 1000)) # next two plots share a common print preview pw2 = PlotWidget() pw2.setWindowTitle("Widget 2 with shared print preview") toolbar2 = qt.QToolBar(pw2) toolbutton2 = PrintPreviewToolButton.SingletonPrintPreviewToolButton( parent=toolbar2, plot=pw2) pw2.addToolBar(toolbar2) toolbar2.addWidget(toolbutton2)
text='Clear', tooltip='Clear the plot', triggered=self._clear, parent=parent) def _clear(self): """Handle action triggered and clear the plot""" self.plot.clear() if __name__ == '__main__': from silx.gui import qt from silx.gui.plot import Plot1D app = qt.QApplication([]) # First create QApplication plot = Plot1D() # Create plotting widget # Create a toolbar and add it to the plot widget toolbar = qt.QToolBar() plot.addToolBar(toolbar) # Create clear action and add it to the toolbar action = ClearPlotAction(plot, parent=plot) toolbar.addAction(action) plot.addCurve((0, 1, 2, 3, 4), (0, 1, 1.5, 1, 0)) # Add a curve to the plot plot.show() # Show the plot widget app.exec() # Start Qt application
y1 = y0 + 1.0 # Re-using the same legend causes the original curve # to be replaced self.plot.addCurve(x0, y1, legend=legend, info=info) # creating QApplication is mandatory in order to use qt widget app = qt.QApplication([]) sys.excepthook = qt.exceptionHandler # create a PlotWindow plotwin = PlotWindow() # Add a new toolbar toolbar = qt.QToolBar("My toolbar") plotwin.addToolBar(toolbar) # Get a reference to the PlotWindow's menu bar, add a menu menubar = plotwin.menuBar() actions_menu = menubar.addMenu("Custom actions") # Initialize our action, give it plotwin as a parameter myaction = ShiftUpAction(plotwin) # Add action to the menubar and toolbar toolbar.addAction(myaction) actions_menu.addAction(myaction) # Plot a couple of curves with synthetic data x = [0, 1, 2, 3, 4, 5, 6] y1 = [0, 1, 0, 1, 0, 1, 0] y2 = [0, 1, 2, 3, 4, 5, 6]
def __createRingToolBar(self): toolBar = qt.QToolBar(self) action = qt.QAction(self) action.setIcon(icons.getQIcon("pyfai:gui/icons/search-full-ring")) action.setText("Ring") action.setCheckable(True) action.setToolTip("Extract peaks, beyond masked values") toolBar.addAction(action) self.__ringSelectionMode = action action = qt.QAction(self) action.setIcon(icons.getQIcon("pyfai:gui/icons/search-ring")) action.setText("Arc") action.setCheckable(True) action.setToolTip("Extract contiguous peaks") toolBar.addAction(action) self.__arcSelectionMode = action action = qt.QAction(self) action.setIcon(icons.getQIcon("pyfai:gui/icons/search-peak")) action.setText("Arc") action.setCheckable(True) action.setToolTip("Extract contiguous peaks") toolBar.addAction(action) self.__peakSelectionMode = action mode = qt.QActionGroup(self) mode.setExclusive(True) mode.addAction(self.__ringSelectionMode) mode.addAction(self.__arcSelectionMode) mode.addAction(self.__peakSelectionMode) self.__arcSelectionMode.setChecked(True) toolBar.addSeparator() # Load peak selection as file loadPeaksFromFile = qt.QAction(self) icon = icons.getQIcon('document-open') self.__icon = icon loadPeaksFromFile.setIcon(icon) loadPeaksFromFile.setText("Load peak selection from file") loadPeaksFromFile.triggered.connect(self.__loadPeaksFromFile) loadPeaksFromFile.setIconVisibleInMenu(True) toolBar.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) toolBar.addAction(savePeaksAsFile) toolBar.addSeparator() style = qt.QApplication.style() action = self.__undoStack.createUndoAction(self, "Undo") icon = style.standardIcon(qt.QStyle.SP_ArrowBack) action.setIcon(icon) toolBar.addAction(action) action = self.__undoStack.createRedoAction(self, "Redo") icon = style.standardIcon(qt.QStyle.SP_ArrowForward) action.setIcon(icon) toolBar.addAction(action) return toolBar
def __init__(self, parent=None): super(MapWidget, self).__init__(parent=parent, backend=None, resetzoom=True, autoScale=False, logScale=False, grid=False, curveStyle=False, colormap=True, aspectRatio=True, yInverted=True, copy=True, save=True, print_=False, control=False, roi=False, mask=True) if parent is None: self.setWindowTitle('comMapWidget') self.setGraphTitle('Scan map') self.setKeepDataAspectRatio(True) self.setYAxisInverted(True) # customize the mask tools for use as ROI selectors # unfortunately, tooltip and icon reset each other, so only changing the icon. self.getMaskToolsDockWidget().setWindowTitle('scan map ROI') roiAction = self.getMaskAction() roiAction.setToolTip('Select a scan map region of interest') roiAction.setIcon(getQIcon('image-select-box')) # Remove the mask action from where it was self.toolBar().removeAction(roiAction) # Rebuild the zoom/pan toolbar and add selection tools tb = self.getInteractiveModeToolBar() for w in tb.actions(): tb.removeAction(w) zoomAction = qt.QAction(getQIcon('zoom'), 'Zoom', parent=self, checkable=True) panAction = qt.QAction(getQIcon('pan'), 'Pan', parent=self, checkable=True) selectAction = qt.QAction(getQIcon('image-select-add'), 'Select single scan point', parent=self, checkable=True) clearAction = qt.QAction(getQIcon('image-select-erase'), 'Clear selections', parent=self, checkable=False) tb.addAction(zoomAction) tb.addAction(panAction) tb.addAction(selectAction) tb.addAction(roiAction) tb.addAction(clearAction) group = qt.QActionGroup(self) group.addAction(zoomAction) group.addAction(panAction) group.addAction(selectAction) group.addAction(roiAction) zoomAction.setChecked(True) def setZoomMode(active): if active: self.setInteractiveMode('zoom') def setPanMode(active): if active: self.setInteractiveMode('pan') def setSelectMode(active): if active: self.setInteractiveMode('select') zoomAction.toggled.connect(setZoomMode) panAction.toggled.connect(setPanMode) selectAction.toggled.connect(setSelectMode) self.selectAction = selectAction self.roiAction = roiAction self.clearAction = clearAction self.sigPlotSignal.connect(self.filterMouseEvents) clearAction.triggered.connect(self.selectionCleared) # Add the index clicker self.indexBox = qt.QSpinBox( toolTip='Select a specific position by index') self.indexBox.setMinimum(0) tb.addWidget(self.indexBox) self.indexBox.valueChanged.connect(self.indexSelectionChanged) # add a button to toggle positions self.positionsAction = qt.QAction('positions', self, checkable=True) self.toolBar().addAction(self.positionsAction) # add the interpolation button self.interpolToolbar = qt.QToolBar('Interpolation options') self.interpolBox = qt.QSpinBox( toolTip='Map oversampling relative to average step size') self.interpolBox.setRange(1, 50) self.interpolBox.setValue(5) self.interpolToolbar.addWidget(qt.QLabel(' N:')) self.interpolToolbar.addWidget(self.interpolBox) self.addToolBar(self.interpolToolbar) self.interpolToolbar.hide() a = self.interpolToolbar.toggleViewAction().setChecked(False) # add a profile tool self.profile = ProfileToolBar(plot=self) self.addToolBar(self.profile) # set default colormap self.setDefaultColormap({ 'name': 'gray', 'autoscale': True, 'normalization': 'linear' })