def init(self, pick=True, update=True): if self.fig is None: self.fig, (self.ax, self.axc) = pyplot.subplots( 1, 2, gridspec_kw={"width_ratios": (10, 1)}) self.ax.set_ylabel('y in pixels') self.ax.set_xlabel('x in pixels') # self.axc.yaxis.set_label_position('left') # self.axc.set_ylabel("Colorbar") toolbar = self.fig.canvas.toolbar toolbar.addSeparator() a = toolbar.addAction('Opts', self.on_option_clicked) a.setToolTip('open options window') if pick: label = qt.QLabel("Ring #", toolbar) toolbar.addWidget(label) self.spinbox = qt.QSpinBox(toolbar) self.spinbox.setMinimum(0) self.sb_action = toolbar.addWidget(self.spinbox) a = toolbar.addAction('Refine', self.on_refine_clicked) a.setToolTip('switch to refinement mode') self.ref_action = a self.mpl_connectId = self.fig.canvas.mpl_connect( 'button_press_event', self.onclick) # if update: self.fig.show() elif update: self.update()
def _createPencilSettings(self, parent=None): pencilSetting = qt.QWidget(parent) self.pencilSpinBox = qt.QSpinBox(parent=pencilSetting) self.pencilSpinBox.setRange(1, 1024) pencilToolTip = """Set pencil drawing tool size in pixels of the image on which to make the mask.""" self.pencilSpinBox.setToolTip(pencilToolTip) self.pencilSlider = qt.QSlider(qt.Qt.Horizontal, parent=pencilSetting) self.pencilSlider.setRange(1, 50) self.pencilSlider.setToolTip(pencilToolTip) pencilLabel = qt.QLabel('Pencil size:', parent=pencilSetting) layout = qt.QGridLayout() layout.addWidget(pencilLabel, 0, 0) layout.addWidget(self.pencilSpinBox, 0, 1) layout.addWidget(self.pencilSlider, 1, 1) pencilSetting.setLayout(layout) self.pencilSpinBox.valueChanged.connect(self._pencilWidthChanged) self.pencilSlider.valueChanged.connect(self._pencilWidthChanged) return pencilSetting
def setupUi(self): # form layout for grid scan inputs layout = qt.QFormLayout() self.noChangeBox = qt.QRadioButton() layout.addRow(qt.QLabel("Export flat list of points:"), self.noChangeBox) self.reshapeBox = qt.QRadioButton() self.reshapeBox.setChecked(True) layout.addRow(qt.QLabel("Try reshaping the data:"), self.reshapeBox) self.shapeBox = qt.QLineEdit('auto') layout.addRow(qt.QLabel(" shape:"), self.shapeBox) self.resampleBox = qt.QRadioButton() layout.addRow(qt.QLabel("Resample the data on a grid:"), self.resampleBox) self.oversamplingBox = qt.QSpinBox() self.oversamplingBox.setValue(1) layout.addRow(qt.QLabel(" oversampling relative to typical step size:"), self.oversamplingBox) self.equalBox = qt.QCheckBox() self.equalBox.setChecked(True) layout.addRow(qt.QLabel(" equal horizontal and vertical steps"), self.equalBox) self.formGroupBox = qt.QGroupBox("PyMCA needs data layed out on a regular grid.") self.formGroupBox.setLayout(layout) # ok/cancel buttons buttonBox = qt.QDialogButtonBox(qt.QDialogButtonBox.Ok | qt.QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) # put everything together mainLayout = qt.QVBoxLayout() mainLayout.addWidget(self.formGroupBox) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) self.setWindowTitle("Export for PyMCA...")
def createEditor(self, parent, option, index): if not index.isValid(): return super(_SpinBoxItemDelegate, self).createEditor(parent, option, index) editor = qt.QSpinBox(parent=parent) editor.setMinimum(1) editor.setMaximum(999) editor.valueChanged.connect(lambda x: self.commitData.emit(editor)) editor.setFocusPolicy(qt.Qt.StrongFocus) editor.setValue(index.data()) editor.installEventFilter(self) return editor
def _initLayout(self, layout): self._lineWidth = qt.QSpinBox(self) self._lineWidth.setRange(1, 1000) self._lineWidth.setValue(1) self._lineWidth.valueChanged[int].connect(self._widgetChanged) self._methodsButton = ProfileOptionToolButton(parent=self, plot=None) self._methodsButton.sigMethodChanged.connect(self._widgetChanged) label = qt.QLabel('W:') label.setToolTip("Line width in pixels") layout.addWidget(label) layout.addWidget(self._lineWidth) layout.addWidget(self._methodsButton)
def __init__(self, parent=None): qt.QWidget.__init__(self, parent=parent) self._nPoints = qt.QSpinBox(self) self._nPoints.setRange(1, 9999) self._nPoints.setValue(1024) self._nPoints.valueChanged[int].connect(self.__widgetChanged) layout = qt.QHBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) label = qt.QLabel('Samples:') label.setToolTip("Number of sample points of the profile") layout.addWidget(label) layout.addWidget(self._nPoints)
def createEditor(self, parent, option, index): if not index.isValid(): return super(_SpinBoxItemDelegate, self).createEditor(parent, option, index) editor = qt.QSpinBox(parent=parent) if self.__palette is not None: editor.setPalette(self.__palette) editor.setMinimum(1) editor.setMaximum(999) editor.valueChanged.connect(lambda x: self.commitData.emit(editor)) editor.setFocusPolicy(qt.Qt.StrongFocus) editor.setValue(index.data()) editor.installEventFilter(self) editor.setBackgroundRole(qt.QPalette.Background) editor.setAutoFillBackground(True) return editor
def makeCombineDataGroup(self): self.combineType = qt.QComboBox() self.combineType.addItems(csp.combineNames) self.combineType.currentIndexChanged.connect(self.combineTypeChanged) self.combineNLabel = qt.QLabel("N=") self.combineN = qt.QSpinBox() self.combineN.setMinimum(1) self.combineStopCB = qt.QCheckBox( u"stop propagation of\ncontributing data at:") self.combineStopCB.stateChanged.connect(self.combineStopCBChanged) self.combineStop = qt.QComboBox() self.combineStop.addItems(csi.nodes.keys()) self.combineMoveToGroupCB = qt.QCheckBox( u"move selected data to a new group") self.combineDo = qt.QPushButton("Combine") self.combineDo.clicked.connect(self.createCombined) # layout = qt.QVBoxLayout() # layout.addWidget(self.combineType) # layout.addWidget(self.combineStopCB) # layout.addWidget(self.combineStop) # layout.addWidget(self.combineDo) # layout.addStretch() layout = qt.QGridLayout() layout.setContentsMargins(2, 0, 2, 2) layout.addWidget(self.combineType, 0, 0) layoutN = qt.QHBoxLayout() layoutN.addStretch() layoutN.addWidget(self.combineNLabel) layoutN.addWidget(self.combineN) layout.addLayout(layoutN, 0, 1) layout.addWidget(self.combineStopCB, 1, 0) layout.addWidget(self.combineStop, 1, 1) layout.addWidget(self.combineMoveToGroupCB, 2, 0, 1, 2) layout.addWidget(self.combineDo, 3, 0, 1, 2) group = qt.QGroupBox('combine selected data') group.setLayout(layout) # group.setSizePolicy(qt.QSizePolicy.Fixed, qt.QSizePolicy.Fixed) return group
def __init__(self, parent=None): qt.QDialog.__init__(self, parent) self.setWindowTitle("Median filter options") self.mainLayout = qt.QHBoxLayout(self) self.setLayout(self.mainLayout) # filter width GUI self.mainLayout.addWidget(qt.QLabel('filter width:', parent=self)) self._filterWidth = qt.QSpinBox(parent=self) self._filterWidth.setMinimum(1) self._filterWidth.setValue(1) self._filterWidth.setSingleStep(2) widthTooltip = """radius width of the pixel including in the filter for each pixel""" self._filterWidth.setToolTip(widthTooltip) self._filterWidth.valueChanged.connect(self._filterOptionChanged) self.mainLayout.addWidget(self._filterWidth) # filter option GUI self._filterOption = qt.QCheckBox('conditional', parent=self) conditionalTooltip = """if check, implement a conditional filter""" self._filterOption.stateChanged.connect(self._filterOptionChanged) self.mainLayout.addWidget(self._filterOption)
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_()
def __init__(self, qspaceFile, **kwargs): super(FitWidget, self).__init__(**kwargs) self.__qspaceH5 = qspaceH5 = QSpaceH5(qspaceFile) self.__progTimer = None self.__outputFile = None self.__nPeaks = 1 layout = Qt.QGridLayout(self) self.__roiWidget = roiWidget = Roi3DSelectorWidget() layout.addWidget(roiWidget) fileLayout = Qt.QHBoxLayout() self.__fileEdit = fileEdit = StyledLineEdit(nChar=20, readOnly=True) fileLayout.addWidget(Qt.QLabel('File :')) fileLayout.addWidget(fileEdit) layout.addLayout(fileLayout, 1, 0) fitLayout = Qt.QHBoxLayout() self.__fitTypeCb = fitTypeCb = Qt.QComboBox() fitTypeCb.addItems(list(FitWidget.FitTypes.keys())) fitTypeCb.setCurrentIndex(0) fitLayout.addWidget(Qt.QLabel('Fit :')) fitLayout.addWidget(fitTypeCb) fitTypeCb.currentIndexChanged[str].connect( self.__slotCurrentTextChanged) layout.addLayout(fitLayout, 2, 0, alignment=Qt.Qt.AlignLeft) self.__nPeaksSpinBox = spinbox = Qt.QSpinBox() # spinbox.setMinimum(1) # spinbox.setMaximum(20) # spinbox.setValue(self.__nPeaks) # spinbox.setToolTip('Max. number of expected peaks.') # spinbox.valueChanged.connect(self.__slotValueChanged) # fitLayout.addWidget(spinbox) # fitLayout.addWidget(Qt.QLabel('peak(s)')) runLayout = Qt.QHBoxLayout() self.__runButton = runButton = Qt.QPushButton('Run') runButton.setEnabled(False) runButton.clicked.connect(self.__slotRunClicked) runLayout.addWidget(runButton) self.__progBar = progBar = Qt.QProgressBar() runLayout.addWidget(progBar) layout.addLayout(runLayout, 3, 0, alignment=Qt.Qt.AlignCenter) self.__statusLabel = statusLabel = Qt.QLabel('Ready') statusLabel.setFrameStyle(Qt.QFrame.Panel | Qt.QFrame.Sunken) layout.addWidget(statusLabel, 4, 0) with qspaceH5: qx = qspaceH5.qx qy = qspaceH5.qy qz = qspaceH5.qz roiWidget.xSlider().setRange([qx[0], qx[-1]]) roiWidget.ySlider().setRange([qy[0], qy[-1]]) roiWidget.zSlider().setRange([qz[0], qz[-1]]) self.__sigFitDone.connect(self.__slotFitDone) layout.setRowStretch(layout.rowCount(), 1) layout.setColumnStretch(layout.columnCount(), 1)
def _initMaskGroupBox(self): """Init general mask operation widgets""" # Mask level self.levelSpinBox = qt.QSpinBox() self.levelSpinBox.setRange(1, self._maxLevelNumber) self.levelSpinBox.setToolTip( 'Choose which mask level is edited.\n' 'A mask can have up to 255 non-overlapping levels.') self.levelSpinBox.valueChanged[int].connect(self._updateColors) self.levelWidget = self._hboxWidget(qt.QLabel('Mask level:'), self.levelSpinBox) # Transparency self.transparencyWidget = self._initTransparencyWidget() # Buttons group invertBtn = qt.QPushButton('Invert') invertBtn.setShortcut(qt.Qt.CTRL + qt.Qt.Key_I) invertBtn.setToolTip('Invert current mask <b>%s</b>' % invertBtn.shortcut().toString()) invertBtn.clicked.connect(self._handleInvertMask) clearBtn = qt.QPushButton('Clear') clearBtn.setShortcut(qt.QKeySequence.Delete) clearBtn.setToolTip('Clear current mask level <b>%s</b>' % clearBtn.shortcut().toString()) clearBtn.clicked.connect(self._handleClearMask) invertClearWidget = self._hboxWidget(invertBtn, clearBtn, stretch=False) undoBtn = qt.QPushButton('Undo') undoBtn.setShortcut(qt.QKeySequence.Undo) undoBtn.setToolTip('Undo last mask change <b>%s</b>' % undoBtn.shortcut().toString()) self._mask.sigUndoable.connect(undoBtn.setEnabled) undoBtn.clicked.connect(self._mask.undo) redoBtn = qt.QPushButton('Redo') redoBtn.setShortcut(qt.QKeySequence.Redo) redoBtn.setToolTip('Redo last undone mask change <b>%s</b>' % redoBtn.shortcut().toString()) self._mask.sigRedoable.connect(redoBtn.setEnabled) redoBtn.clicked.connect(self._mask.redo) undoRedoWidget = self._hboxWidget(undoBtn, redoBtn, stretch=False) self.clearAllBtn = qt.QPushButton('Clear all') self.clearAllBtn.setToolTip('Clear all mask levels') self.clearAllBtn.clicked.connect(self.resetSelectionMask) loadBtn = qt.QPushButton('Load...') loadBtn.clicked.connect(self._loadMask) saveBtn = qt.QPushButton('Save...') saveBtn.clicked.connect(self._saveMask) self.loadSaveWidget = self._hboxWidget(loadBtn, saveBtn, stretch=False) layout = qt.QVBoxLayout() layout.addWidget(self.levelWidget) layout.addWidget(self.transparencyWidget) layout.addWidget(invertClearWidget) layout.addWidget(undoRedoWidget) layout.addWidget(self.clearAllBtn) layout.addWidget(self.loadSaveWidget) layout.addStretch(1) maskGroup = qt.QGroupBox('Mask') maskGroup.setLayout(layout) return maskGroup
def populateOptions(self): grid = self.ui.optionsGrid # remove all old options for i in reversed(range(grid.count())): grid.itemAt(i).widget().setParent(None) # add new ones opts = self._current_subclass_opts() self.formWidgets = {} i = 0 for name, opt in opts.items(): # special: the options scanNr and fileName (or path) have their input # widgets at the top of the GUI for convenience, while dataSource is # handled per tab. if name in ('dataSource', 'scanNr', 'path', 'fileName'): continue grid.addWidget(qt.QLabel(name), i, 0) grid.addWidget(qt.QLabel(opt['doc']), i, 2) if opt['type'] == int: w = qt.QSpinBox() w.setMaximum(9999) w.setValue(opt['value']) elif opt['type'] == float: w = qt.QDoubleSpinBox() w.setValue(opt['value']) elif opt['type'] == bool: w = qt.QCheckBox() w.setChecked(opt['value']) elif opt['type'] in (list, tuple): w = qt.QLineEdit() w.setText(str(opt['value'])) w.evaluate_me = True elif type(opt['type']) in (list, tuple): w = qt.QComboBox() defaultindex = 0 for j, item in enumerate(opt['type']): w.addItem(item) if item == opt['value']: defaultindex = j w.setCurrentIndex(defaultindex) else: w = qt.QLineEdit() w.setText(opt['value']) w.evaluate_me = False grid.addWidget(w, i, 1) # save a dict of the options widgets, to parse when loading self.formWidgets[name] = w i += 1 # add a vertical spacer on the last line to make the table more compact grid.setRowStretch(i, 1) # special treatment oldtext = str(self.ui.filenameBox.text()) if 'path' in opts.keys() and oldtext.startswith('<'): self.ui.filenameBox.setText('<data path>') elif 'fileName' in opts.keys() and oldtext.startswith('<'): self.ui.filenameBox.setText('<input file>') self.ui.filenameBox.setDisabled(not ( 'path' in opts.keys() or 'fileName' in opts.keys())) self.ui.browseButton.setDisabled(not ( 'path' in opts.keys() or 'fileName' in opts.keys())) self.ui.scanNumberBox.setDisabled('scanNr' not in opts.keys()) # per-tab dataSource option boxes = { self.ui.dataSource2dBox: 2, self.ui.dataSource1dBox: 1, self.ui.dataSource0dBox: 0 } subclass_ = str(self.ui.scanClassBox.currentText()) try: subclass = getattr(nmutils.core, subclass_) except AttributeError: subclass = None for box, dim in boxes.items(): box.clear() if subclass is not None: for name in opts['dataSource']['type']: if hasattr(subclass, 'sourceDims' ) and not subclass.sourceDims[name] == dim: continue box.addItem(name) box.addItem('')
def _initMaskGroupBox(self): """Init general mask operation widgets""" # Mask level self.levelSpinBox = qt.QSpinBox() self.levelSpinBox.setRange(1, self._maxLevelNumber) self.levelSpinBox.setToolTip( 'Choose which mask level is edited.\n' 'A mask can have up to 255 non-overlapping levels.') self.levelSpinBox.valueChanged[int].connect(self._updateColors) self._levelWidget = self._hboxWidget(qt.QLabel('Mask level:'), self.levelSpinBox) # Transparency self._transparencyWidget = self._initTransparencyWidget() style = qt.QApplication.style() def getIcon(*identifiyers): for i in identifiyers: if isinstance(i, str): if qt.QIcon.hasThemeIcon(i): return qt.QIcon.fromTheme(i) elif isinstance(i, qt.QIcon): return i else: return style.standardIcon(i) return qt.QIcon() undoAction = qt.QAction(self) undoAction.setText('Undo') icon = getIcon("edit-undo", qt.QStyle.SP_ArrowBack) undoAction.setIcon(icon) undoAction.setShortcut(qt.QKeySequence.Undo) undoAction.setToolTip('Undo last mask change <b>%s</b>' % undoAction.shortcut().toString()) self._mask.sigUndoable.connect(undoAction.setEnabled) undoAction.triggered.connect(self._mask.undo) redoAction = qt.QAction(self) redoAction.setText('Redo') icon = getIcon("edit-redo", qt.QStyle.SP_ArrowForward) redoAction.setIcon(icon) redoAction.setShortcut(qt.QKeySequence.Redo) redoAction.setToolTip('Redo last undone mask change <b>%s</b>' % redoAction.shortcut().toString()) self._mask.sigRedoable.connect(redoAction.setEnabled) redoAction.triggered.connect(self._mask.redo) loadAction = qt.QAction(self) loadAction.setText('Load...') icon = icons.getQIcon("document-open") loadAction.setIcon(icon) loadAction.setToolTip('Load mask from file') loadAction.triggered.connect(self._loadMask) saveAction = qt.QAction(self) saveAction.setText('Save...') icon = icons.getQIcon("document-save") saveAction.setIcon(icon) saveAction.setToolTip('Save mask to file') saveAction.triggered.connect(self._saveMask) invertAction = qt.QAction(self) invertAction.setText('Invert') icon = icons.getQIcon("mask-invert") invertAction.setIcon(icon) invertAction.setShortcut(qt.Qt.CTRL + qt.Qt.Key_I) invertAction.setToolTip('Invert current mask <b>%s</b>' % invertAction.shortcut().toString()) invertAction.triggered.connect(self._handleInvertMask) clearAction = qt.QAction(self) clearAction.setText('Clear') icon = icons.getQIcon("mask-clear") clearAction.setIcon(icon) clearAction.setShortcut(qt.QKeySequence.Delete) clearAction.setToolTip('Clear current mask level <b>%s</b>' % clearAction.shortcut().toString()) clearAction.triggered.connect(self._handleClearMask) clearAllAction = qt.QAction(self) clearAllAction.setText('Clear all') icon = icons.getQIcon("mask-clear-all") clearAllAction.setIcon(icon) clearAllAction.setToolTip('Clear all mask levels') clearAllAction.triggered.connect(self.resetSelectionMask) # Buttons group margin1 = qt.QWidget(self) margin1.setMinimumWidth(6) margin2 = qt.QWidget(self) margin2.setMinimumWidth(6) actions = (loadAction, saveAction, margin1, undoAction, redoAction, margin2, invertAction, clearAction, clearAllAction) widgets = [] for action in actions: if isinstance(action, qt.QWidget): widgets.append(action) continue btn = qt.QToolButton() btn.setDefaultAction(action) widgets.append(btn) if action is clearAllAction: self._clearAllBtn = btn container = self._hboxWidget(*widgets) container.layout().setSpacing(1) layout = qt.QVBoxLayout() layout.addWidget(container) layout.addWidget(self._levelWidget) layout.addWidget(self._transparencyWidget) layout.addStretch(1) maskGroup = qt.QGroupBox('Mask') maskGroup.setLayout(layout) return maskGroup
def gui(self, log=False, maximize=False, pick=True): """ :param log: show z in log scale """ if self.fig is None: self.fig = pyplot.figure() self.fig.subplots_adjust(right=0.75) # add 3 subplots at the same position for debye-sherrer image, contour-plot and massif contour self.ax = self.fig.add_subplot(111) self.ct = self.fig.add_subplot(111) self.msp = self.fig.add_subplot(111) toolbar = self.fig.canvas.toolbar toolbar.addSeparator() a = toolbar.addAction('Opts', self.on_option_clicked) a.setToolTip('open options window') if pick: label = qt.QLabel("Ring #", toolbar) toolbar.addWidget(label) self.spinbox = qt.QSpinBox(toolbar) self.spinbox.setMinimum(0) self.sb_action = toolbar.addWidget(self.spinbox) a = toolbar.addAction('Refine', self.on_refine_clicked) a.setToolTip('switch to refinement mode') self.ref_action = a self.mpl_connectId = self.fig.canvas.mpl_connect( 'button_press_event', self.onclick) if log: data_disp = numpy.log1p(self.data - self.data.min()) txt = 'Log colour scale (skipping lowest/highest per mille)' else: data_disp = self.data txt = 'Linear colour scale (skipping lowest/highest per mille)' # skip lowest and highest per mille of image values via vmin/vmax sorted_list = data_disp.flatten() # explicit copy sorted_list.sort() show_min = sorted_list[int(round(1e-3 * (sorted_list.size - 1)))] show_max = sorted_list[int(round(0.999 * (sorted_list.size - 1)))] im = self.ax.imshow( data_disp, vmin=show_min, vmax=show_max, origin="lower", interpolation="nearest", ) self.ax.set_ylabel('y in pixels') self.ax.set_xlabel('x in pixels') if self.detector: s1, s2 = self.data.shape s1 -= 1 s2 -= 1 self.ax.set_xlim(0, s2) self.ax.set_ylim(0, s1) d1 = numpy.array([0, s1, s1, 0]) d2 = numpy.array([0, 0, s2, s2]) p1, p2, _ = self.detector.calc_cartesian_positions(d1=d1, d2=d2) ax = self.fig.add_subplot(1, 1, 1, xbound=False, ybound=False, xlabel=r'dim2 ($\approx m$)', ylabel=r'dim1 ($\approx m$)', xlim=(p2.min(), p2.max()), ylim=(p1.min(), p1.max()), aspect='equal', zorder=-1) ax.xaxis.set_label_position('top') ax.yaxis.set_label_position('right') ax.yaxis.label.set_color('blue') ax.xaxis.label.set_color('blue') ax.tick_params(colors="blue", labelbottom='off', labeltop='on', labelleft='off', labelright='on') # ax.autoscale_view(False, False, False) else: _cbar = self.fig.colorbar(im, label=txt) # self.ax.autoscale_view(False, False, False) update_fig(self.fig) if maximize: maximize_fig(self.fig) if not gui_utils.main_loop: self.fig.show()
def __init__(self, parent=None): super(SearchPage, self).__init__(parent) layout = qt.QVBoxLayout(self) self.manualFwhmGB = qt.QGroupBox("Define FWHM manually", self) self.manualFwhmGB.setCheckable(True) self.manualFwhmGB.setToolTip( "If disabled, the FWHM parameter used for peak search is " + "estimated based on the highest peak in the data") layout.addWidget(self.manualFwhmGB) # ------------ GroupBox fwhm-------------------------- layout2 = qt.QHBoxLayout(self.manualFwhmGB) self.manualFwhmGB.setLayout(layout2) label = qt.QLabel("Fwhm Points", self.manualFwhmGB) layout2.addWidget(label) self.fwhmPointsSpin = qt.QSpinBox(self.manualFwhmGB) self.fwhmPointsSpin.setRange(0, 999999) self.fwhmPointsSpin.setToolTip( "Typical peak fwhm (number of data points)") layout2.addWidget(self.fwhmPointsSpin) # ---------------------------------------------------- self.manualScalingGB = qt.QGroupBox("Define scaling manually", self) self.manualScalingGB.setCheckable(True) self.manualScalingGB.setToolTip( "If disabled, the Y scaling used for peak search is " + "estimated automatically") layout.addWidget(self.manualScalingGB) # ------------ GroupBox scaling----------------------- layout3 = qt.QHBoxLayout(self.manualScalingGB) self.manualScalingGB.setLayout(layout3) label = qt.QLabel("Y Scaling", self.manualScalingGB) layout3.addWidget(label) self.yScalingEntry = qt.QLineEdit(self.manualScalingGB) self.yScalingEntry.setToolTip( "Data values will be multiplied by this value prior to peak" + " search") self.yScalingEntry.setValidator(qt.QDoubleValidator(self)) layout3.addWidget(self.yScalingEntry) # ---------------------------------------------------- # ------------------- grid layout -------------------- containerWidget = qt.QWidget(self) layout4 = qt.QHBoxLayout(containerWidget) containerWidget.setLayout(layout4) label = qt.QLabel("Sensitivity", containerWidget) layout4.addWidget(label) self.sensitivityEntry = qt.QLineEdit(containerWidget) self.sensitivityEntry.setToolTip( "Peak search sensitivity threshold, expressed as a multiple " + "of the standard deviation of the noise.\nMinimum value is 1 " + "(to be detected, peak must be higher than the estimated noise)") sensivalidator = qt.QDoubleValidator(self) sensivalidator.setBottom(1.0) self.sensitivityEntry.setValidator(sensivalidator) layout4.addWidget(self.sensitivityEntry) # ---------------------------------------------------- layout.addWidget(containerWidget) self.forcePeakPresenceCB = qt.QCheckBox("Force peak presence", self) self.forcePeakPresenceCB.setToolTip( "If peak search algorithm is unsuccessful, place one peak " + "at the maximum of the curve") layout.addWidget(self.forcePeakPresenceCB) layout.addStretch() self.setDefault()
def __init__(self, parent=None, title="Subtract strip background prior to estimation"): super(BackgroundPage, self).__init__(parent) self.setTitle(title) self.setCheckable(True) self.setToolTip( "The strip algorithm strips away peaks to compute the " + "background signal.\nAt each iteration, a sample is compared " + "to the average of the two samples at a given distance in both" + " directions,\n and if its value is higher than the average," "it is replaced by the average.") layout = qt.QGridLayout(self) self.setLayout(layout) for i, label_text in enumerate([ "Strip width (in samples)", "Number of iterations", "Strip threshold factor" ]): label = qt.QLabel(label_text) layout.addWidget(label, i, 0) self.stripWidthSpin = qt.QSpinBox(self) self.stripWidthSpin.setToolTip( "Width, in number of samples, of the strip operator") self.stripWidthSpin.setRange(1, 999999) layout.addWidget(self.stripWidthSpin, 0, 1) self.numIterationsSpin = qt.QSpinBox(self) self.numIterationsSpin.setToolTip( "Number of iterations of the strip algorithm") self.numIterationsSpin.setRange(1, 999999) layout.addWidget(self.numIterationsSpin, 1, 1) self.thresholdFactorEntry = qt.QLineEdit(self) self.thresholdFactorEntry.setToolTip( "Factor used by the strip algorithm to decide whether a sample" + "value should be stripped.\nThe value must be higher than the " + "average of the 2 samples at +- w times this factor.\n") self.thresholdFactorEntry.setValidator(qt.QDoubleValidator(self)) layout.addWidget(self.thresholdFactorEntry, 2, 1) self.smoothStripGB = qt.QGroupBox("Apply smoothing prior to strip", self) self.smoothStripGB.setCheckable(True) self.smoothStripGB.setToolTip( "Apply a smoothing before subtracting strip background" + " in fit and estimate processes") smoothlayout = qt.QHBoxLayout(self.smoothStripGB) label = qt.QLabel("Smoothing width (Savitsky-Golay)") smoothlayout.addWidget(label) self.smoothingWidthSpin = qt.QSpinBox(self) self.smoothingWidthSpin.setToolTip( "Width parameter for Savitsky-Golay smoothing (number of samples, must be odd)" ) self.smoothingWidthSpin.setRange(3, 101) self.smoothingWidthSpin.setSingleStep(2) smoothlayout.addWidget(self.smoothingWidthSpin) layout.addWidget(self.smoothStripGB, 3, 0, 1, 2) layout.setRowStretch(4, 1) self.setDefault()
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' })
def __init__(self, spec_file=None, img_dir=None, spec_version=1, output_dir=None, tmp_dir=None, **kwargs): super(MergeWidget, self).__init__(**kwargs) Qt.QGridLayout(self) # ################ # input QGroupBox # ################ if spec_file is not None: specFile = spec_file else: specFile = '' if img_dir is not None: imgDir = img_dir else: imgDir = '' if spec_version is not None: specVersion = spec_version else: specVersion = self._defaultVersion if output_dir is not None: outputDir = output_dir else: outputDir = '' # parameters self.__input = { 'specfile': specFile, 'imgdir': imgDir, 'version': specVersion, 'padding': None, 'offset': None } self.__output = {'outdir': outputDir, 'prefix': ''} inputGbx = GroupBox("Input") layout = Qt.QGridLayout(inputGbx) self.layout().addWidget(inputGbx, 0, 0, Qt.Qt.AlignTop) first_col = 0 file_bn_col = 4 last_col = file_bn_col + 1 spec_row = 0 img_path_row = 1 version_row = 2 apply_bn_row = 3 # spec file input specFileChooser = FileChooser(fileMode=Qt.QFileDialog.ExistingFile, noLabel=True) specFileChooser.lineEdit.setText(specFile) specFileChooser.sigSelectionChanged.connect(self.__slotSpecFileChanged) layout.addWidget(Qt.QLabel('Spec file :'), spec_row, 0) layout.addWidget(specFileChooser, spec_row, 1) # image folder input imgDirChooser = FileChooser(fileMode=Qt.QFileDialog.Directory, noLabel=True) imgDirChooser.lineEdit.setText(imgDir) imgDirChooser.sigSelectionChanged.connect(self.__slotImgDirChanged) layout.addWidget(Qt.QLabel('Img dir. :'), img_path_row, 0) layout.addWidget(imgDirChooser, img_path_row, 1) # version selection optionLayout = Qt.QHBoxLayout() optionLayout.addStretch(1) lab = Qt.QLabel('Version :') self.__versionCBx = versionCBx = Qt.QComboBox() for version in range(len(self._versions)): versionCBx.addItem(str(version)) versionCBx.addItem('') optionLayout.addWidget(lab, Qt.Qt.AlignLeft) optionLayout.addWidget(versionCBx, Qt.Qt.AlignLeft) # filename padding for the nextNr counter self.__padSpinBox = padSpinBox = Qt.QSpinBox() optionLayout.addWidget(_vLine()) optionLayout.addWidget(Qt.QLabel('nextNr padding:')) optionLayout.addWidget(padSpinBox, Qt.Qt.AlignLeft) padSpinBox.valueChanged[int].connect(self.__slotPaddingValueChanged) # filename offset for the nextNr counter self.__nextNrSpinBox = nextNrSpinBox = Qt.QSpinBox() nextNrSpinBox.setMinimum(-100) nextNrSpinBox.setMaximum(100) optionLayout.addWidget(_vLine()) optionLayout.addWidget(Qt.QLabel('nextNr offset:')) optionLayout.addWidget(nextNrSpinBox, Qt.Qt.AlignLeft) nextNrSpinBox.valueChanged[int].connect(self.__slotNextNrValueChanged) optionLayout.addStretch(100) layout.addLayout(optionLayout, version_row, 0, 1, layout.columnCount(), Qt.Qt.AlignLeft) # last row : apply button self.__parseBn = parseBn = FixedSizePushButon('Parse file') parseBn.clicked.connect(self.__slotParseBnClicked, Qt.Qt.QueuedConnection) layout.addWidget(parseBn, apply_bn_row, 0, 1, last_col - first_col, Qt.Qt.AlignHCenter) # ################ # scans + edf QGroupBox # ################ self.__scansGbx = scansGbx = GroupBox("Spec + EDF") grpLayout = Qt.QHBoxLayout(scansGbx) self.layout().addWidget(scansGbx, 1, 0, Qt.Qt.AlignLeft | Qt.Qt.AlignTop) # =========== # valid scans # =========== scanLayout = Qt.QGridLayout() grpLayout.addLayout(scanLayout) hLayout = Qt.QHBoxLayout() label = Qt.QLabel('<span style=" font-weight:600; color:#00916a;">' 'Matched scans</span>') label.setTextFormat(Qt.Qt.RichText) editScansBn = FixedSizePushButon('Edit') editScansBn.clicked.connect(self.__slotEditScansClicked) hLayout.addWidget(label) hLayout.addWidget(editScansBn) scanLayout.addLayout(hLayout, 0, 0, 1, 2) label = Qt.QLabel('Total :') self.__totalScansEdit = totalScansEdit = Qt.QLineEdit('0') totalScansEdit.setReadOnly(True) fm = totalScansEdit.fontMetrics() width = (fm.boundingRect('0123456').width() + fm.boundingRect('00').width()) totalScansEdit.setMaximumWidth(width) totalScansEdit.setAlignment(Qt.Qt.AlignRight) scanLayout.addWidget(label, 1, 0, Qt.Qt.AlignLeft) scanLayout.addWidget(totalScansEdit, 1, 1, Qt.Qt.AlignLeft) # ==== label = Qt.QLabel('Selected :') self.__selectedScansEdit = selectedScansEdit = Qt.QLineEdit('0') selectedScansEdit.setReadOnly(True) fm = selectedScansEdit.fontMetrics() width = (fm.boundingRect('0123456').width() + fm.boundingRect('00').width()) selectedScansEdit.setMaximumWidth(width) selectedScansEdit.setAlignment(Qt.Qt.AlignRight) scanLayout.addWidget(label, 2, 0, Qt.Qt.AlignLeft) scanLayout.addWidget(selectedScansEdit, 2, 1, Qt.Qt.AlignLeft) # === grpLayout.addWidget(_vLine()) # =========== # "other" scans # =========== scanLayout = Qt.QGridLayout() grpLayout.addLayout(scanLayout) hLayout = Qt.QHBoxLayout() label = Qt.QLabel('<span style=" font-weight:600; color:#ff6600;">' 'Other scans</span>') otherScansBn = FixedSizePushButon('View') otherScansBn.clicked.connect(self.__slotOtherScansClicked) hLayout.addWidget(label) hLayout.addWidget(otherScansBn) scanLayout.addLayout(hLayout, 0, 0, 1, 2) label = Qt.QLabel('No match :') self.__noMatchScansEdit = noMatchScansEdit = Qt.QLineEdit('0') noMatchScansEdit.setReadOnly(True) fm = noMatchScansEdit.fontMetrics() width = (fm.boundingRect('0123456').width() + fm.boundingRect('00').width()) noMatchScansEdit.setMaximumWidth(width) noMatchScansEdit.setAlignment(Qt.Qt.AlignRight) scanLayout.addWidget(label, 1, 0, Qt.Qt.AlignLeft) scanLayout.addWidget(noMatchScansEdit, 1, 1, Qt.Qt.AlignLeft) # ==== label = Qt.QLabel('No img info :') self.__noImgInfoEdit = noImgInfoEdit = Qt.QLineEdit('0') noImgInfoEdit.setReadOnly(True) fm = noImgInfoEdit.fontMetrics() width = (fm.boundingRect('0123456').width() + fm.boundingRect('00').width()) noImgInfoEdit.setMaximumWidth(width) noImgInfoEdit.setAlignment(Qt.Qt.AlignRight) scanLayout.addWidget(label, 2, 0, Qt.Qt.AlignLeft) scanLayout.addWidget(noImgInfoEdit, 2, 1, Qt.Qt.AlignLeft) # === grpLayout.addWidget(_vLine()) # ################ # parameters # ################ self.__acqParamsGbx = acqParamsGbx = GroupBox("Acq. Parameters") grpLayout = Qt.QVBoxLayout(acqParamsGbx) self.__acqParamWid = acqParamWid = AcqParamsWidget() self.layout().addWidget(acqParamsGbx, 2, 0, Qt.Qt.AlignLeft | Qt.Qt.AlignTop) grpLayout.addWidget(acqParamWid) # ################ # output options # ################ self.__outputGbx = outputGbx = GroupBox("Output") layout = Qt.QGridLayout(outputGbx) self.layout().addWidget(outputGbx, 3, 0, Qt.Qt.AlignTop) # =========== # master # =========== lab = Qt.QLabel('Prefix :') self.__prefixEdit = prefixEdit = StyledLineEdit(nChar=20) prefixEdit.textChanged.connect(self.__slotPrefixChanged) hLayout = Qt.QHBoxLayout() layout.addLayout(hLayout, 0, 1, Qt.Qt.AlignLeft) resetPrefixBn = Qt.QToolButton() icon = Qt.qApp.style().standardIcon(Qt.QStyle.SP_BrowserReload) resetPrefixBn.setIcon(icon) resetPrefixBn.clicked.connect(self.__slotResetPrefixClicked) layout.addWidget(lab, 0, 0, Qt.Qt.AlignLeft) sp = prefixEdit.sizePolicy() sp.setHorizontalPolicy(Qt.QSizePolicy.Maximum) prefixEdit.setSizePolicy(sp) hLayout.addWidget(prefixEdit, Qt.Qt.AlignLeft) hLayout.addWidget(resetPrefixBn, Qt.Qt.AlignLeft) # =========== # output folder # =========== outDirChooser = FileChooser(fileMode=Qt.QFileDialog.Directory, noLabel=True) outDirChooser.lineEdit.setText(outputDir) outDirChooser.sigSelectionChanged.connect(self.__slotOutDirChanged) layout.addWidget(Qt.QLabel('Output directory :'), 1, 0) layout.addWidget(outDirChooser, 1, 1) # ################ # merge button # ################ self.__mergeBn = mergeBn = Qt.QPushButton('Merge') cancelBn = Qt.QPushButton('Cancel') hLayout = Qt.QHBoxLayout() self.layout().addLayout(hLayout, 4, 0, 1, 1, Qt.Qt.AlignHCenter | Qt.Qt.AlignTop) hLayout.addWidget(mergeBn) hLayout.addWidget(cancelBn) mergeBn.clicked.connect(self.__slotMergeBnClicked) cancelBn.clicked.connect(self.reject) # ################# # setting initial state # ################# # scansGbx.setEnabled(False) # acqParamsGbx.setEnabled(False) # outputGbx.setEnabled(False) # mergeBn.setEnabled(False) parseBn.setEnabled(False) self.__merger = None self.__parser = None self.info_wid = None if tmp_dir is None: tmp_dir, delete_tmp, q_tmp_dir = _create_tmp_dir() else: delete_tmp = False q_tmp_dir = None self.__tmp_root = tmp_dir self.__delete_tmp_root = delete_tmp self.__q_tmp_dir = q_tmp_dir tmp_dir = os.path.join(self.__tmp_root, 'xsocs_merge') if not os.path.exists(tmp_dir): os.makedirs(tmp_dir) self.__tmp_dir_merge = tmp_dir print('Using temporary folder : {0}.'.format(tmp_dir)) self.__widgetIsSetup = False self.__xsocs_h5 = None versionCBx.setCurrentIndex(spec_version) self.__slotVersionChanged(spec_version) versionCBx.currentIndexChanged[int].connect(self.__slotVersionChanged) self.__resetState() self.__sigParsed.connect(self.__slotParsed, Qt.Qt.QueuedConnection)
def __init__(self, parent=None): qt.QWidget.__init__(self, parent) self.mainLayout = qt.QGridLayout(self) self.mainLayout.setColumnStretch(1, 1) # Algorithm choice --------------------------------------------------- self.algorithmComboLabel = qt.QLabel(self) self.algorithmComboLabel.setText("Background algorithm") self.algorithmCombo = qt.QComboBox(self) self.algorithmCombo.addItem("Strip") self.algorithmCombo.addItem("Snip") self.algorithmCombo.activated[int].connect( self._algorithmComboActivated) # Strip parameters --------------------------------------------------- self.stripWidthLabel = qt.QLabel(self) self.stripWidthLabel.setText("Strip Width") self.stripWidthSpin = qt.QSpinBox(self) self.stripWidthSpin.setMaximum(100) self.stripWidthSpin.setMinimum(1) self.stripWidthSpin.valueChanged[int].connect(self._emitSignal) self.stripIterLabel = qt.QLabel(self) self.stripIterLabel.setText("Strip Iterations") self.stripIterValue = qt.QLineEdit(self) validator = qt.QIntValidator(self.stripIterValue) self.stripIterValue._v = validator self.stripIterValue.setText("0") self.stripIterValue.editingFinished[()].connect(self._emitSignal) self.stripIterValue.setToolTip( "Number of iterations for strip algorithm.\n" + "If greater than 999, an 2nd pass of strip filter is " + "applied to remove artifacts created by first pass.") # Snip parameters ---------------------------------------------------- self.snipWidthLabel = qt.QLabel(self) self.snipWidthLabel.setText("Snip Width") self.snipWidthSpin = qt.QSpinBox(self) self.snipWidthSpin.setMaximum(300) self.snipWidthSpin.setMinimum(0) self.snipWidthSpin.valueChanged[int].connect(self._emitSignal) # Smoothing parameters ----------------------------------------------- self.smoothingFlagCheck = qt.QCheckBox(self) self.smoothingFlagCheck.setText("Smoothing Width (Savitsky-Golay)") self.smoothingFlagCheck.toggled.connect(self._smoothingToggled) self.smoothingSpin = qt.QSpinBox(self) self.smoothingSpin.setMinimum(3) #self.smoothingSpin.setMaximum(40) self.smoothingSpin.setSingleStep(2) self.smoothingSpin.valueChanged[int].connect(self._emitSignal) # Anchors ------------------------------------------------------------ self.anchorsGroup = qt.QWidget(self) anchorsLayout = qt.QHBoxLayout(self.anchorsGroup) anchorsLayout.setSpacing(2) anchorsLayout.setContentsMargins(0, 0, 0, 0) self.anchorsFlagCheck = qt.QCheckBox(self.anchorsGroup) self.anchorsFlagCheck.setText("Use anchors") self.anchorsFlagCheck.setToolTip( "Define X coordinates of points that must remain fixed") self.anchorsFlagCheck.stateChanged[int].connect( self._anchorsToggled) anchorsLayout.addWidget(self.anchorsFlagCheck) maxnchannel = 16384 * 4 # Fixme ? self.anchorsList = [] num_anchors = 4 for i in range(num_anchors): anchorSpin = qt.QSpinBox(self.anchorsGroup) anchorSpin.setMinimum(0) anchorSpin.setMaximum(maxnchannel) anchorSpin.valueChanged[int].connect(self._emitSignal) anchorsLayout.addWidget(anchorSpin) self.anchorsList.append(anchorSpin) # Layout ------------------------------------------------------------ self.mainLayout.addWidget(self.algorithmComboLabel, 0, 0) self.mainLayout.addWidget(self.algorithmCombo, 0, 2) self.mainLayout.addWidget(self.stripWidthLabel, 1, 0) self.mainLayout.addWidget(self.stripWidthSpin, 1, 2) self.mainLayout.addWidget(self.stripIterLabel, 2, 0) self.mainLayout.addWidget(self.stripIterValue, 2, 2) self.mainLayout.addWidget(self.snipWidthLabel, 3, 0) self.mainLayout.addWidget(self.snipWidthSpin, 3, 2) self.mainLayout.addWidget(self.smoothingFlagCheck, 4, 0) self.mainLayout.addWidget(self.smoothingSpin, 4, 2) self.mainLayout.addWidget(self.anchorsGroup, 5, 0, 1, 4) # Initialize interface ----------------------------------------------- self._setAlgorithm("strip") self.smoothingFlagCheck.setChecked(False) self._smoothingToggled(is_checked=False) self.anchorsFlagCheck.setChecked(False) self._anchorsToggled(is_checked=False)
return True def disconnect(self): self.blockSignal = True try: self.signal.disconnect(self.signalReceived) except: pass try: self.sigDelayed.disconnect(self.slot) except: pass if __name__ == '__main__': app = qt.QApplication([]) win = qt.QMainWindow() spin = qt.QSpinBox() win.setCentralWidget(spin) win.show() def fn(*args): print("Raw signal:", args) def fn2(*args): print("Delayed signal:", args) spin.valueChanged.connect(fn) # proxy = proxyConnect(spin, QtCore.SIGNAL('valueChanged(int)'), fn) proxy = SignalProxy(spin.valueChanged, delay=0.5, slot=fn2)