Exemplo n.º 1
0
    def __init__(self, delay=0.5, parent=None):
        super(DelayedSpinBox, self).__init__(parent)
        self.log = make_logging_source_adapter(__name__, self)

        def delayed_slt():
            self.log.debug("delayed_slt invoked. value=%d" % self.value())
            self.delayed_valueChanged.emit(self.value())

        self.proxy = SignalProxy(signal=self.valueChanged,
                                 slot=delayed_slt,
                                 delay=delay)
Exemplo n.º 2
0
    def __init__(self,
                 parent=None,
                 name="ImageView",
                 view=None,
                 imageItem=None,
                 *args):
        """
        By default, this class creates an :class:`ImageItem <pyqtgraph.ImageItem>` to display image data
        and a :class:`ViewBox <pyqtgraph.ViewBox>` to contain the ImageItem. 
        
        ============= =========================================================
        **Arguments** 
        parent        (QWidget) Specifies the parent widget to which
                      this ImageView will belong. If None, then the ImageView
                      is created with no parent.
        name          (str) The name used to register both the internal ViewBox
                      and the PlotItem used to display ROI data. See the *name*
                      argument to :func:`ViewBox.__init__() 
                      <pyqtgraph.ViewBox.__init__>`.
        view          (ViewBox or PlotItem) If specified, this will be used
                      as the display area that contains the displayed image. 
                      Any :class:`ViewBox <pyqtgraph.ViewBox>`, 
                      :class:`PlotItem <pyqtgraph.PlotItem>`, or other 
                      compatible object is acceptable.
        imageItem     (ImageItem) If specified, this object will be used to
                      display the image. Must be an instance of ImageItem
                      or other compatible object.
        ============= =========================================================
        
        Note: to display axis ticks inside the ImageView, instantiate it 
        with a PlotItem instance as its view::
                
            pg.ImageView(view=pg.PlotItem())
        """
        QtGui.QWidget.__init__(self, parent, *args)
        self.levelMax = 4096
        self.levelMin = 0
        self.name = name
        self.image = None
        self.axes = {}
        self.imageDisp = None
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.scene = self.ui.graphicsView.scene()

        self.ignoreTimeLine = False

        if view is None:
            self.view = ViewBox()
        else:
            self.view = view
        self.ui.graphicsView.setCentralItem(self.view)
        self.view.setAspectLocked(True)
        self.view.invertY()

        if imageItem is None:
            self.imageItem = ImageItem()
        else:
            self.imageItem = imageItem
        self.view.addItem(self.imageItem)
        self.currentIndex = 0

        self.ui.histogram.setImageItem(self.imageItem)

        self.menu = None

        self.ui.normGroup.hide()

        self.roi = PlotROI(10)
        self.roi.setZValue(20)
        self.view.addItem(self.roi)
        self.roi.hide()
        self.normRoi = PlotROI(10)
        self.normRoi.setPen('y')
        self.normRoi.setZValue(20)
        self.view.addItem(self.normRoi)
        self.normRoi.hide()
        self.roiCurve = self.ui.roiPlot.plot()
        self.timeLine = InfiniteLine(0, movable=True)
        self.timeLine.setPen((255, 255, 0, 200))
        self.timeLine.setZValue(1)
        self.ui.roiPlot.addItem(self.timeLine)
        self.ui.splitter.setSizes([self.height() - 35, 35])
        self.ui.roiPlot.hideAxis('left')

        self.keysPressed = {}
        self.playTimer = QtCore.QTimer()
        self.playRate = 0
        self.lastPlayTime = 0

        self.normRgn = LinearRegionItem()
        self.normRgn.setZValue(0)
        self.ui.roiPlot.addItem(self.normRgn)
        self.normRgn.hide()

        ## wrap functions from view box
        for fn in ['addItem', 'removeItem']:
            setattr(self, fn, getattr(self.view, fn))

        ## wrap functions from histogram
        for fn in [
                'setHistogramRange', 'autoHistogramRange', 'getLookupTable',
                'getLevels'
        ]:
            setattr(self, fn, getattr(self.ui.histogram, fn))

        self.timeLine.sigPositionChanged.connect(self.timeLineChanged)
        self.ui.roiBtn.clicked.connect(self.roiClicked)
        self.roi.sigRegionChanged.connect(self.roiChanged)
        #self.ui.normBtn.toggled.connect(self.normToggled)
        self.ui.menuBtn.clicked.connect(self.menuClicked)
        self.ui.normDivideRadio.clicked.connect(self.normRadioChanged)
        self.ui.normSubtractRadio.clicked.connect(self.normRadioChanged)
        self.ui.normOffRadio.clicked.connect(self.normRadioChanged)
        self.ui.normROICheck.clicked.connect(self.updateNorm)
        self.ui.normFrameCheck.clicked.connect(self.updateNorm)
        self.ui.normTimeRangeCheck.clicked.connect(self.updateNorm)
        self.playTimer.timeout.connect(self.timeout)

        self.normProxy = SignalProxy(self.normRgn.sigRegionChanged,
                                     slot=self.updateNorm)
        self.normRoi.sigRegionChangeFinished.connect(self.updateNorm)

        self.ui.roiPlot.registerPlot(self.name + '_ROI')
        self.view.register(self.name)

        self.noRepeatKeys = [
            QtCore.Qt.Key_Right, QtCore.Qt.Key_Left, QtCore.Qt.Key_Up,
            QtCore.Qt.Key_Down, QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown
        ]

        self.roiClicked()  ## initialize roi plot to correct shape / visibility
Exemplo n.º 3
0
class SpinBox(QtGui.QAbstractSpinBox):
    """
    **Bases:** QtGui.QAbstractSpinBox

    QSpinBox widget on steroids. Allows selection of numerical value, with extra features:

    - SI prefix notation (eg, automatically display "300 mV" instead of "0.003 V")
    - Float values with linear and decimal stepping (1-9, 10-90, 100-900, etc.)
    - Option for unbounded values
    - Delayed signals (allows multiple rapid changes with only one change signal)

    =============================  ==============================================
    **Signals:**
    valueChanged(value)            Same as QSpinBox; emitted every time the value
                                   has changed.
    sigValueChanged(self)          Emitted when value has changed, but also combines
                                   multiple rapid changes into one signal (eg,
                                   when rolling the mouse wheel).
    sigValueChanging(self, value)  Emitted immediately for all value changes.
    =============================  ==============================================
    """

    ## There's a PyQt bug that leaks a reference to the
    ## QLineEdit returned from QAbstractSpinBox.lineEdit()
    ## This makes it possible to crash the entire program
    ## by making accesses to the LineEdit after the spinBox has been deleted.
    ## I have no idea how to get around this..


    valueChanged = QtCore.Signal(object)     # (value)  for compatibility with QSpinBox
    sigValueChanged = QtCore.Signal(object)  # (self)
    sigValueChanging = QtCore.Signal(object, object)  # (self, value)  sent immediately; no delay.

    def __init__(self, parent=None, value=0.0, **kwargs):
        """
        ============== ========================================================================
        **Arguments:**
        parent         Sets the parent widget for this SpinBox (optional). Default is None.
        value          (float/int) initial value. Default is 0.0.
        bounds         (min,max) Minimum and maximum values allowed in the SpinBox.
                       Either may be None to leave the value unbounded. By default, values are unbounded.
        suffix         (str) suffix (units) to display after the numerical value. By default, suffix is an empty str.
        siPrefix       (bool) If True, then an SI prefix is automatically prepended
                       to the units and the value is scaled accordingly. For example,
                       if value=0.003 and suffix='V', then the SpinBox will display
                       "300 mV" (but a call to SpinBox.value will still return 0.003). Default is False.
        step           (float) The size of a single step. This is used when clicking the up/
                       down arrows, when rolling the mouse wheel, or when pressing
                       keyboard arrows while the widget has keyboard focus. Note that
                       the interpretation of this value is different when specifying
                       the 'dec' argument. Default is 0.01.
        dec            (bool) If True, then the step value will be adjusted to match
                       the current size of the variable (for example, a value of 15
                       might step in increments of 1 whereas a value of 1500 would
                       step in increments of 100). In this case, the 'step' argument
                       is interpreted *relative* to the current value. The most common
                       'step' values when dec=True are 0.1, 0.2, 0.5, and 1.0. Default is False.
        minStep        (float) When dec=True, this specifies the minimum allowable step size.
        int            (bool) if True, the value is forced to integer type. Default is False
        decimals       (int) Number of decimal values to display. Default is 2.
        readonly       (bool) If True, then mouse and keyboard interactions are caught and
                       will not produce a valueChanged signal, but the value can be still
                       changed programmatic via the setValue method. Default is False.
        ============== ========================================================================
        """
        QtGui.QAbstractSpinBox.__init__(self, parent)
        self.lastValEmitted = None
        self.lastText = ''
        self.textValid = True  ## If false, we draw a red border
        self.setMinimumWidth(0)
        self.setMaximumHeight(20)
        self.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred)
        self.opts = {
            'bounds': [None, None],

            ## Log scaling options   #### Log mode is no longer supported.
            #'step': 0.1,
            #'minStep': 0.001,
            #'log': True,
            #'dec': False,

            ## decimal scaling option - example
            #'step': 0.1,
            #'minStep': .001,
            #'log': False,
            #'dec': True,

            ## normal arithmetic step
            'step': D('0.01'),  ## if 'dec' is false, the spinBox steps by 'step' every time
                                ## if 'dec' is True, the step size is relative to the value
                                ## 'step' needs to be an integral divisor of ten, ie 'step'*n=10 for some integer value of n (but only if dec is True)
            'log': False,
            'dec': False,   ## if true, does decimal stepping. ie from 1-10 it steps by 'step', from 10 to 100 it steps by 10*'step', etc.
                            ## if true, minStep must be set in order to cross zero.


            'int': False, ## Set True to force value to be integer

            'suffix': '',
            'siPrefix': False,   ## Set to True to display numbers with SI prefix (ie, 100pA instead of 1e-10A)

            'delay': 0.3, ## delay sending wheel update signals for 300ms

            'delayUntilEditFinished': True,   ## do not send signals until text editing has finished

            ## for compatibility with QDoubleSpinBox and QSpinBox
            'decimals': 2,

            'readonly': False,

        }

        self.decOpts = ['step', 'minStep']
        self.val = D(asUnicode(value))  ## Value is precise decimal. Ordinary math not allowed.
        self.updateText()
        self.skipValidate = False
        self.setCorrectionMode(self.CorrectToPreviousValue)
        self.setKeyboardTracking(False)
        self.setOpts(**kwargs)


        self.editingFinished.connect(self.editingFinishedEvent)
        self.proxy = SignalProxy(self.sigValueChanging, slot=self.delayedChange, delay=self.opts['delay'])


    def event(self, ev):
        ret = QtGui.QAbstractSpinBox.event(self, ev)
        if ev.type() == QtCore.QEvent.KeyPress and ev.key() == QtCore.Qt.Key_Return:
            ret = True  ## For some reason, spinbox pretends to ignore return key press

        #Fix: introduce the Escape event, which is restoring the previous display.
        if ev.type() == QtCore.QEvent.KeyPress and ev.key() == QtCore.Qt.Key_Escape:
            self.updateText()
            ret = True
        return ret

    ##lots of config options, just gonna stuff 'em all in here rather than do the get/set crap.
    def setOpts(self, **opts):
        """
        Changes the behavior of the SpinBox. Accepts most of the arguments
        allowed in :func:`__init__ <pyqtgraph.SpinBox.__init__>`.

        """
        #print opts
        for k in opts:
            if k == 'bounds':
                #print opts[k]
                self.setMinimum(opts[k][0], update=False)
                self.setMaximum(opts[k][1], update=False)
                #for i in [0,1]:
                    #if opts[k][i] is None:
                        #self.opts[k][i] = None
                    #else:
                        #self.opts[k][i] = D(unicode(opts[k][i]))
            elif k in ['step', 'minStep']:
                self.opts[k] = D(asUnicode(opts[k]))
            elif k == 'value':
                pass   ## don't set value until bounds have been set
            else:
                self.opts[k] = opts[k]
        if 'value' in opts:
            self.setValue(opts['value'])

        ## If bounds have changed, update value to match
        if 'bounds' in opts and 'value' not in opts:
            self.setValue()

        ## sanity checks:
        if self.opts['int']:
            if 'step' in opts:
                step = opts['step']
                ## not necessary..
                #if int(step) != step:
                    #raise Exception('Integer SpinBox must have integer step size.')
            else:
                self.opts['step'] = int(self.opts['step'])

            if 'minStep' in opts:
                step = opts['minStep']
                if int(step) != step:
                    raise Exception('Integer SpinBox must have integer minStep size.')
            else:
                ms = int(self.opts.get('minStep', 1))
                if ms < 1:
                    ms = 1
                self.opts['minStep'] = ms

        if 'delay' in opts:
            self.proxy.setDelay(opts['delay'])

        if 'readonly' in opts:
            self.opts['readonly'] = opts['readonly']

        self.updateText()

    #Fix: reimplement the methods for compatibility reasons to QSpinBox and QDoubleSpinBox methods
    def maximum(self):
        """ Reimplement the maximum functionality."""
        max_val = self.opts['bounds'][1]

        if self.opts['int'] and max_val is not None:
            return int(max_val)
        elif max_val is not None:
            return float(max_val)
        else:
            return max_val

    def setMaximum(self, m, update=True):
        """Set the maximum allowed value (or None for no limit)"""
        if m is not None:

            #FIX: insert the integer functionality:
            if self.opts['int']:
                m = int(m)

            m = D(asUnicode(m))
        self.opts['bounds'][1] = m
        if update:
            self.setValue()

    #Fix: reimplement the methods for compatibility reasons to QSpinBox and QDoubleSpinBox methods
    def minimum(self):
        """ Reimplement the minimum functionality."""

        min_val = self.opts['bounds'][0]

        if self.opts['int'] and min_val is not None:
            return int(min_val)
        elif min_val is not None:
            return float(min_val)
        else:
            return min_val

    def setMinimum(self, m, update=True):
        """Set the minimum allowed value (or None for no limit)"""
        if m is not None:

            #FIX: insert the integer functionality:
            if self.opts['int']:
                m = int(m)

            m = D(asUnicode(m))
        self.opts['bounds'][0] = m
        if update:
            self.setValue()

    def setPrefix(self, p):
        self.setOpts(prefix=p)

    def setRange(self, r0, r1):
        self.setOpts(bounds = [r0,r1])

    def setProperty(self, prop, val):
        ## for QSpinBox compatibility
        if prop == 'value':
            #if type(val) is QtCore.QVariant:
                #val = val.toDouble()[0]
            self.setValue(val)
        else:
            print("Warning: SpinBox.setProperty('{0!s}', ..) not supported.".format(prop))

    def setSuffix(self, suf):
        self.setOpts(suffix=suf)

    def setSingleStep(self, step):
        self.setOpts(step=step)

    def setDecimals(self, decimals):
        self.setOpts(decimals=decimals)

    def selectNumber(self):
        """
        Select the numerical portion of the text to allow quick editing by the user.
        """
        le = self.lineEdit()
        text = asUnicode(le.text())
        if self.opts['suffix'] == '':
            le.setSelection(0, len(text))
        else:
            try:
                index = text.index(' ')
            except ValueError:
                return
            le.setSelection(0, index)

    #Fix: reimplement the methods for compatibility reasons to QSpinBox and QDoubleSpinBox methods
    def suffix(self):
        return self.opts['suffix']

    #Fix: reimplement the methods for compatibility reasons to QSpinBox and QDoubleSpinBox methods
    def prefix(self):
        return self.opts['prefix']

    def value(self):
        """
        Return the value of this SpinBox.

        """
        if self.opts['int']:
            return int(self.val)
        else:
            return float(self.val)

    def setValue(self, value=None, update=True, delaySignal=False):
        """
        Set the value of this spin.
        If the value is out of bounds, it will be clipped to the nearest boundary.
        If the spin is integer type, the value will be coerced to int.
        Returns the actual value set.

        If value is None, then the current value is used (this is for resetting
        the value after bounds, etc. have changed)
        """

        if value is None:
            value = self.value()

        bounds = self.opts['bounds']
        if bounds[0] is not None and value < bounds[0]:
            value = bounds[0]
        if bounds[1] is not None and value > bounds[1]:
            value = bounds[1]

        if self.opts['int']:
            value = int(value)

        value = D(asUnicode(value))
        if value == self.val:
            return
        prev = self.val

        self.val = value
        if update:
            self.updateText(prev=prev)

        self.sigValueChanging.emit(self, float(self.val))  ## change will be emitted in 300ms if there are no subsequent changes.
        if not delaySignal:
            self.emitChanged()

        return value

    value_float = Property(float, value, setValue,
                           doc='Qt property value as type float')
    value_int = Property(int, value, setValue,
                         doc='Qt property value as type int')

    def emitChanged(self):
        self.lastValEmitted = self.val
        self.valueChanged.emit(float(self.val))
        self.sigValueChanged.emit(self)

    def delayedChange(self):
        try:
            if self.val != self.lastValEmitted:
                self.emitChanged()
        except RuntimeError:
            pass  ## This can happen if we try to handle a delayed signal after someone else has already deleted the underlying C++ object.

    def widgetGroupInterface(self):
        return (self.valueChanged, SpinBox.value, SpinBox.setValue)

    def sizeHint(self):
        return QtCore.QSize(120, 0)

    def stepEnabled(self):
        return self.StepUpEnabled | self.StepDownEnabled

    #def fixup(self, *args):
        #print "fixup:", args

    def stepBy(self, n):
        n = D(int(n))   ## n must be integral number of steps.
        s = [D(-1), D(1)][n >= 0]  ## determine sign of step
        val = self.val

        for i in range(int(abs(n))):

            if self.opts['log']:
                raise Exception("Log mode no longer supported.")
            #    step = abs(val) * self.opts['step']
            #    if 'minStep' in self.opts:
            #        step = max(step, self.opts['minStep'])
            #    val += step * s
            if self.opts['dec']:
                if val == 0:
                    step = self.opts['minStep']
                    exp = None
                else:
                    vs = [D(-1), D(1)][val >= 0]
                    #exp = D(int(abs(val*(D('1.01')**(s*vs))).log10()))
                    fudge = D('1.01')**(s*vs) ## fudge factor. at some places, the step size depends on the step sign.
                    exp = abs(val * fudge).log10().quantize(1, rounding=ROUND_FLOOR)
                    step = self.opts['step'] * D(10)**exp
                if 'minStep' in self.opts:
                    step = max(step, self.opts['minStep'])
                val += s * step
                #print "Exp:", exp, "step", step, "val", val
            else:
                val += s*self.opts['step']

            if 'minStep' in self.opts and abs(val) < self.opts['minStep']:
                val = D(0)
        self.setValue(val, delaySignal=True)  ## note all steps (arrow buttons, wheel, up/down keys..) emit delayed signals only.

    def valueInRange(self, value):
        bounds = self.opts['bounds']
        if bounds[0] is not None and value < bounds[0]:
            return False
        if bounds[1] is not None and value > bounds[1]:
            return False
        if self.opts.get('int', False):
            if int(value) != value:
                return False
        return True


    def updateText(self, prev=None):
        # print("Update text.")

        self.skipValidate = True
        if self.opts['siPrefix']:
            if self.val == 0 and prev is not None:
                (s, p) = fn.siScale(prev)
                txt = "0.0 {0!s}{1!s}".format(p, self.opts['suffix'])
            else:
                txt = fn.siFormat(float(self.val),
                                  precision=self.opts['decimals']+1,
                                  suffix=self.opts['suffix']
                                  )
        else:
            txt = '{0:.14g}{1!s}'.format(self.val , self.opts['suffix'])
        self.lineEdit().setText(txt)
        self.lastText = txt
        self.skipValidate = False

    def validate(self, strn, pos):
        # print('validate', strn, pos)
        if self.skipValidate:
            # print("skip validate")
            #self.textValid = False
            ret = QtGui.QValidator.Acceptable
        else:
            try:
                ## first make sure we didn't mess with the suffix
                suff = self.opts.get('suffix', '')

                # fix: if the whole text is selected and one needs to typ in a
                #      new number, then a single integer character is ignored.
                if len(strn) == 1 and strn.isdigit():
                    scl_str = fn.siScale(self.val)[1]
                    strn = '{0} {1}{2}'.format(strn, scl_str, suff)

                if len(suff) > 0 and asUnicode(strn)[-len(suff):] != suff:
                    #print '"%s" != "%s"' % (unicode(strn)[-len(suff):], suff)
                    ret = QtGui.QValidator.Invalid
                    # print('invalid input', 'suff:', suff, '{0} != {1}'.format(asUnicode(strn)[-len(suff):], suff))

                ## next see if we actually have an interpretable value
                else:
                    val = self.interpret()
                    if val is False:
                        #print "can't interpret"
                        #self.setStyleSheet('SpinBox {border: 2px solid #C55;}')
                        #self.textValid = False
                        ret = QtGui.QValidator.Intermediate
                    else:
                        if self.valueInRange(val):
                            if not self.opts['delayUntilEditFinished']:
                                self.setValue(val, update=False)
                            #print "  OK:", self.val
                            #self.setStyleSheet('')
                            #self.textValid = True

                            ret = QtGui.QValidator.Acceptable
                        else:
                            ret = QtGui.QValidator.Intermediate

            except:
                #print "  BAD"
                #import sys
                #sys.excepthook(*sys.exc_info())
                #self.textValid = False
                #self.setStyleSheet('SpinBox {border: 2px solid #C55;}')
                ret = QtGui.QValidator.Intermediate

        ## draw / clear border
        if ret == QtGui.QValidator.Intermediate:
            self.textValid = False
        elif ret == QtGui.QValidator.Acceptable:
            self.textValid = True
        ## note: if text is invalid, we don't change the textValid flag
        ## since the text will be forced to its previous state anyway
        self.update()

        ## support 2 different pyqt APIs. Bleh.
        if hasattr(QtCore, 'QString'):
            return (ret, pos)
        else:
            return (ret, strn, pos)

    def paintEvent(self, ev):
        QtGui.QAbstractSpinBox.paintEvent(self, ev)

        ## draw red border if text is invalid
        if not self.textValid:
            p = QtGui.QPainter(self)
            p.setRenderHint(p.Antialiasing)
            p.setPen(fn.mkPen((200,50,50), width=2))
            p.drawRoundedRect(self.rect().adjusted(2, 2, -2, -2), 4, 4)
            p.end()


    def interpret(self):
        """Return value of text. Return False if text is invalid, raise exception if text is intermediate"""
        strn = self.lineEdit().text()

        #Fix: strip leading blank characters, which produce errors:
        strn = strn.lstrip()

        suf = self.opts['suffix']
        if len(suf) > 0:
            if strn[-len(suf):] != suf:
                return False
            #raise Exception("Units are invalid.")
            strn = strn[:-len(suf)]
        try:
            val = fn.siEval(strn)
        except:
            #sys.excepthook(*sys.exc_info())
            #print "invalid"
            return False
        #print val
        return val

    #def interpretText(self, strn=None):
        #print "Interpret:", strn
        #if strn is None:
            #strn = self.lineEdit().text()
        #self.setValue(siEval(strn), update=False)
        ##QtGui.QAbstractSpinBox.interpretText(self)


    def editingFinishedEvent(self):
        """Edit has finished; set value."""
        #print "Edit finished."
        if asUnicode(self.lineEdit().text()) == self.lastText:
            #print "no text change."
            return
        try:
            val = self.interpret()
        except:
            return

        if val is False:
            #print "value invalid:", str(self.lineEdit().text())
            return
        if val == self.val:
            #print "no value change:", val, self.val
            return
        self.setValue(val, delaySignal=False)  ## allow text update so that values are reformatted pretty-like

    #def textChanged(self):
        #print "Text changed."


### Drop-in replacement for SpinBox; just for crash-testing
#class SpinBox(QtGui.QDoubleSpinBox):
    #valueChanged = QtCore.Signal(object)     # (value)  for compatibility with QSpinBox
    #sigValueChanged = QtCore.Signal(object)  # (self)
    #sigValueChanging = QtCore.Signal(object)  # (value)
    #def __init__(self, parent=None, *args, **kargs):
        #QtGui.QSpinBox.__init__(self, parent)

    #def  __getattr__(self, attr):
        #return lambda *args, **kargs: None

    #def widgetGroupInterface(self):
        #return (self.valueChanged, SpinBox.value, SpinBox.setValue)

    def isReadOnly(self):
        """ Overwrite the QAbstractSpinBox method to obtain the ReadOnly state.
        """
        return self.opts['readonly']

    def mousePressEvent(self, event):
        """ Handle what happens on press event of the mouse.

        @param event: QEvent of a Mouse Release action
        """

        if self.isReadOnly():
            event.accept()
        else:
            super(SpinBox, self).mousePressEvent(event)

    # Comment out this method, since it is called, if QToolTip is going to be
    # displayed. You would not see any QTooltip if you catch that signal.
    # def mouseMoveEvent(self, event):
    #     """ Handle what happens on move (over) event of the mouse.
    #
    #     @param event: QEvent of a Mouse Move action
    #     """
    #
    #     if ( self.isReadOnly() ):
    #         event.accept()
    #     else:
    #         super(SpinBox, self).mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        """ Handle what happens on release of the mouse.

        @param event: QEvent of a Mouse Release action
        """

        if self.isReadOnly() :
            event.accept()
        else:
            super(SpinBox, self).mouseReleaseEvent(event)

    # Handle event in which the widget has focus and the spacebar is pressed.
    def keyPressEvent(self, event):
        """ Handle what happens on keypress.

        @param event: QEvent of a key press Action
        """

        if self.isReadOnly():
            event.accept()
        else:
            super(SpinBox, self).keyPressEvent(event)

    def wheelEvent(self, event):
        """ Handle what happens on a wheel event of the mouse.

        @param event: QEvent of a Mouse Wheel event
        """

        if self.isReadOnly():
            event.accept()
        else:
            super(SpinBox, self).wheelEvent(event)


    @QtCore.pyqtSlot(bool)
    def setReadOnly(self, state):
        """ Overwrite the QAbstractSpinBox method to set the ReadOnly state.

        @param bool state: True or False, for having a readonly QRadioButton.

        Important, declare that slot as a qt slot to provide a C++ signature for
        that. The advantage is less memory consumption and slightly faster
        performance.
        Note: Not using the slot decorator causes that the signal connection
        mechanism is forced to work out manually the type conversion to map from
        the underlying C++ function signatures to the Python functions. When the
        slot decorators are used, the type mapping can be explicit!
        """

        self.setOpts(readonly=state)
    readOnly = QtCore.pyqtProperty(bool, isReadOnly, setReadOnly)
Exemplo n.º 4
0
    def __init__(self, parent=None, value=0.0, **kwargs):
        """
        ============== ========================================================================
        **Arguments:**
        parent         Sets the parent widget for this SpinBox (optional). Default is None.
        value          (float/int) initial value. Default is 0.0.
        bounds         (min,max) Minimum and maximum values allowed in the SpinBox.
                       Either may be None to leave the value unbounded. By default, values are unbounded.
        suffix         (str) suffix (units) to display after the numerical value. By default, suffix is an empty str.
        siPrefix       (bool) If True, then an SI prefix is automatically prepended
                       to the units and the value is scaled accordingly. For example,
                       if value=0.003 and suffix='V', then the SpinBox will display
                       "300 mV" (but a call to SpinBox.value will still return 0.003). Default is False.
        step           (float) The size of a single step. This is used when clicking the up/
                       down arrows, when rolling the mouse wheel, or when pressing
                       keyboard arrows while the widget has keyboard focus. Note that
                       the interpretation of this value is different when specifying
                       the 'dec' argument. Default is 0.01.
        dec            (bool) If True, then the step value will be adjusted to match
                       the current size of the variable (for example, a value of 15
                       might step in increments of 1 whereas a value of 1500 would
                       step in increments of 100). In this case, the 'step' argument
                       is interpreted *relative* to the current value. The most common
                       'step' values when dec=True are 0.1, 0.2, 0.5, and 1.0. Default is False.
        minStep        (float) When dec=True, this specifies the minimum allowable step size.
        int            (bool) if True, the value is forced to integer type. Default is False
        decimals       (int) Number of decimal values to display. Default is 2.
        readonly       (bool) If True, then mouse and keyboard interactions are caught and
                       will not produce a valueChanged signal, but the value can be still
                       changed programmatic via the setValue method. Default is False.
        ============== ========================================================================
        """
        QtGui.QAbstractSpinBox.__init__(self, parent)
        self.lastValEmitted = None
        self.lastText = ''
        self.textValid = True  ## If false, we draw a red border
        self.setMinimumWidth(0)
        self.setMaximumHeight(20)
        self.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred)
        self.opts = {
            'bounds': [None, None],

            ## Log scaling options   #### Log mode is no longer supported.
            #'step': 0.1,
            #'minStep': 0.001,
            #'log': True,
            #'dec': False,

            ## decimal scaling option - example
            #'step': 0.1,
            #'minStep': .001,
            #'log': False,
            #'dec': True,

            ## normal arithmetic step
            'step': D('0.01'),  ## if 'dec' is false, the spinBox steps by 'step' every time
                                ## if 'dec' is True, the step size is relative to the value
                                ## 'step' needs to be an integral divisor of ten, ie 'step'*n=10 for some integer value of n (but only if dec is True)
            'log': False,
            'dec': False,   ## if true, does decimal stepping. ie from 1-10 it steps by 'step', from 10 to 100 it steps by 10*'step', etc.
                            ## if true, minStep must be set in order to cross zero.


            'int': False, ## Set True to force value to be integer

            'suffix': '',
            'siPrefix': False,   ## Set to True to display numbers with SI prefix (ie, 100pA instead of 1e-10A)

            'delay': 0.3, ## delay sending wheel update signals for 300ms

            'delayUntilEditFinished': True,   ## do not send signals until text editing has finished

            ## for compatibility with QDoubleSpinBox and QSpinBox
            'decimals': 2,

            'readonly': False,

        }

        self.decOpts = ['step', 'minStep']
        self.val = D(asUnicode(value))  ## Value is precise decimal. Ordinary math not allowed.
        self.updateText()
        self.skipValidate = False
        self.setCorrectionMode(self.CorrectToPreviousValue)
        self.setKeyboardTracking(False)
        self.setOpts(**kwargs)


        self.editingFinished.connect(self.editingFinishedEvent)
        self.proxy = SignalProxy(self.sigValueChanging, slot=self.delayedChange, delay=self.opts['delay'])
Exemplo n.º 5
0
    def __init__(self, parent=None, name="ImageView", *args):
        QtGui.QWidget.__init__(self, parent, *args)
        self.levelMax = 4096
        self.levelMin = 0
        self.name = name
        self.image = None
        self.axes = {}
        self.imageDisp = None
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.scene = self.ui.graphicsView.scene()

        self.ignoreTimeLine = False

        #if 'linux' in sys.platform.lower():   ## Stupid GL bug in linux.
        #    self.ui.graphicsView.setViewport(QtGui.QWidget())

        #self.ui.graphicsView.enableMouse(True)
        #self.ui.graphicsView.autoPixelRange = False
        #self.ui.graphicsView.setAspectLocked(True)
        #self.ui.graphicsView.invertY()
        #self.ui.graphicsView.enableMouse()
        self.view = ViewBox()
        self.ui.graphicsView.setCentralItem(self.view)
        self.view.setAspectLocked(True)
        self.view.invertY()

        #self.ticks = [t[0] for t in self.ui.gradientWidget.listTicks()]
        #self.ticks[0].colorChangeAllowed = False
        #self.ticks[1].colorChangeAllowed = False
        #self.ui.gradientWidget.allowAdd = False
        #self.ui.gradientWidget.setTickColor(self.ticks[1], QtGui.QColor(255,255,255))
        #self.ui.gradientWidget.setOrientation('right')

        self.imageItem = ImageItem()
        self.view.addItem(self.imageItem)
        self.currentIndex = 0

        self.ui.histogram.setImageItem(self.imageItem)

        self.ui.normGroup.hide()

        self.roi = PlotROI(10)
        self.roi.setZValue(20)
        self.view.addItem(self.roi)
        self.roi.hide()
        self.normRoi = PlotROI(10)
        self.normRoi.setPen(QtGui.QPen(QtGui.QColor(255, 255, 0)))
        self.normRoi.setZValue(20)
        self.view.addItem(self.normRoi)
        self.normRoi.hide()
        #self.ui.roiPlot.hide()
        self.roiCurve = self.ui.roiPlot.plot()
        self.timeLine = InfiniteLine(0, movable=True)
        self.timeLine.setPen(QtGui.QPen(QtGui.QColor(255, 255, 0, 200)))
        self.timeLine.setZValue(1)
        self.ui.roiPlot.addItem(self.timeLine)
        self.ui.splitter.setSizes([self.height() - 35, 35])
        self.ui.roiPlot.hideAxis('left')

        self.keysPressed = {}
        self.playTimer = QtCore.QTimer()
        self.playRate = 0
        self.lastPlayTime = 0

        #self.normLines = []
        #for i in [0,1]:
        #l = InfiniteLine(self.ui.roiPlot, 0)
        #l.setPen(QtGui.QPen(QtGui.QColor(0, 100, 200, 200)))
        #self.ui.roiPlot.addItem(l)
        #self.normLines.append(l)
        #l.hide()
        self.normRgn = LinearRegionItem()
        self.normRgn.setZValue(0)
        self.ui.roiPlot.addItem(self.normRgn)
        self.normRgn.hide()

        ## wrap functions from view box
        for fn in ['addItem', 'removeItem']:
            setattr(self, fn, getattr(self.view, fn))

        ## wrap functions from histogram
        for fn in [
                'setHistogramRange', 'autoHistogramRange', 'getLookupTable',
                'getLevels'
        ]:
            setattr(self, fn, getattr(self.ui.histogram, fn))

        self.timeLine.sigPositionChanged.connect(self.timeLineChanged)
        #self.ui.gradientWidget.sigGradientChanged.connect(self.updateImage)
        self.ui.roiBtn.clicked.connect(self.roiClicked)
        self.roi.sigRegionChanged.connect(self.roiChanged)
        self.ui.normBtn.toggled.connect(self.normToggled)
        self.ui.normDivideRadio.clicked.connect(self.normRadioChanged)
        self.ui.normSubtractRadio.clicked.connect(self.normRadioChanged)
        self.ui.normOffRadio.clicked.connect(self.normRadioChanged)
        self.ui.normROICheck.clicked.connect(self.updateNorm)
        self.ui.normFrameCheck.clicked.connect(self.updateNorm)
        self.ui.normTimeRangeCheck.clicked.connect(self.updateNorm)
        self.playTimer.timeout.connect(self.timeout)

        self.normProxy = SignalProxy(self.normRgn.sigRegionChanged,
                                     slot=self.updateNorm)
        self.normRoi.sigRegionChangeFinished.connect(self.updateNorm)

        self.ui.roiPlot.registerPlot(self.name + '_ROI')

        self.noRepeatKeys = [
            QtCore.Qt.Key_Right, QtCore.Qt.Key_Left, QtCore.Qt.Key_Up,
            QtCore.Qt.Key_Down, QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown
        ]

        self.roiClicked()  ## initialize roi plot to correct shape / visibility
Exemplo n.º 6
0
    def __init__(self, parent=None, value=0.0, **kwargs):
        """
        ============== ========================================================================
        **Arguments:**
        parent         Sets the parent widget for this SpinBox (optional). Default is None.
        value          (float/int) initial value. Default is 0.0.
        bounds         (min,max) Minimum and maximum values allowed in the SpinBox. 
                       Either may be None to leave the value unbounded. By default, values are unbounded.
        suffix         (str) suffix (units) to display after the numerical value. By default, suffix is an empty str.
        siPrefix       (bool) If True, then an SI prefix is automatically prepended
                       to the units and the value is scaled accordingly. For example,
                       if value=0.003 and suffix='V', then the SpinBox will display
                       "300 mV" (but a call to SpinBox.value will still return 0.003). Default is False.
        step           (float) The size of a single step. This is used when clicking the up/
                       down arrows, when rolling the mouse wheel, or when pressing 
                       keyboard arrows while the widget has keyboard focus. Note that
                       the interpretation of this value is different when specifying
                       the 'dec' argument. Default is 0.01.
        dec            (bool) If True, then the step value will be adjusted to match 
                       the current size of the variable (for example, a value of 15
                       might step in increments of 1 whereas a value of 1500 would
                       step in increments of 100). In this case, the 'step' argument
                       is interpreted *relative* to the current value. The most common
                       'step' values when dec=True are 0.1, 0.2, 0.5, and 1.0. Default is False.
        minStep        (float) When dec=True, this specifies the minimum allowable step size.
        int            (bool) if True, the value is forced to integer type. Default is False
        decimals       (int) Number of decimal values to display. Default is 2. 
        ============== ========================================================================
        """
        QtGui.QAbstractSpinBox.__init__(self, parent)
        self.lastValEmitted = None
        self.lastText = ''
        self.textValid = True  ## If false, we draw a red border
        self.setMinimumWidth(0)
        self.setMaximumHeight(20)
        self.setSizePolicy(QtGui.QSizePolicy.Expanding,
                           QtGui.QSizePolicy.Preferred)
        self.opts = {
            'bounds': [None, None],

            ## Log scaling options   #### Log mode is no longer supported.
            #'step': 0.1,
            #'minStep': 0.001,
            #'log': True,
            #'dec': False,

            ## decimal scaling option - example
            #'step': 0.1,
            #'minStep': .001,
            #'log': False,
            #'dec': True,

            ## normal arithmetic step
            'step':
            D('0.01'
              ),  ## if 'dec' is false, the spinBox steps by 'step' every time
            ## if 'dec' is True, the step size is relative to the value
            ## 'step' needs to be an integral divisor of ten, ie 'step'*n=10 for some integer value of n (but only if dec is True)
            'log': False,
            'dec':
            False,  ## if true, does decimal stepping. ie from 1-10 it steps by 'step', from 10 to 100 it steps by 10*'step', etc. 
            ## if true, minStep must be set in order to cross zero.
            'int': False,  ## Set True to force value to be integer
            'suffix': '',
            'siPrefix':
            False,  ## Set to True to display numbers with SI prefix (ie, 100pA instead of 1e-10A)
            'delay': 0.3,  ## delay sending wheel update signals for 300ms
            'delayUntilEditFinished':
            True,  ## do not send signals until text editing has finished

            ## for compatibility with QDoubleSpinBox and QSpinBox
            'decimals': 3,
        }

        self.decOpts = ['step', 'minStep']

        self.val = D(asUnicode(
            value))  ## Value is precise decimal. Ordinary math not allowed.
        self.updateText()
        self.skipValidate = False
        self.setCorrectionMode(self.CorrectToPreviousValue)
        self.setKeyboardTracking(False)
        self.setOpts(**kwargs)

        self.editingFinished.connect(self.editingFinishedEvent)
        self.proxy = SignalProxy(self.sigValueChanging,
                                 slot=self.delayedChange,
                                 delay=self.opts['delay'])
Exemplo n.º 7
0
class SpinBox(QtGui.QAbstractSpinBox):
    """
    **Bases:** QtGui.QAbstractSpinBox
    
    QSpinBox widget on steroids. Allows selection of numerical value, with extra features:
    
    - SI prefix notation (eg, automatically display "300 mV" instead of "0.003 V")
    - Float values with linear and decimal stepping (1-9, 10-90, 100-900, etc.)
    - Option for unbounded values
    - Delayed signals (allows multiple rapid changes with only one change signal)
    
    =============================  ==============================================
    **Signals:**
    valueChanged(value)            Same as QSpinBox; emitted every time the value 
                                   has changed.
    sigValueChanged(self)          Emitted when value has changed, but also combines
                                   multiple rapid changes into one signal (eg, 
                                   when rolling the mouse wheel).
    sigValueChanging(self, value)  Emitted immediately for all value changes.
    =============================  ==============================================
    """

    ## There's a PyQt bug that leaks a reference to the
    ## QLineEdit returned from QAbstractSpinBox.lineEdit()
    ## This makes it possible to crash the entire program
    ## by making accesses to the LineEdit after the spinBox has been deleted.
    ## I have no idea how to get around this..

    valueChanged = QtCore.Signal(
        object)  # (value)  for compatibility with QSpinBox
    sigValueChanged = QtCore.Signal(object)  # (self)
    sigValueChanging = QtCore.Signal(
        object, object)  # (self, value)  sent immediately; no delay.

    def __init__(self, parent=None, value=0.0, **kwargs):
        """
        ============== ========================================================================
        **Arguments:**
        parent         Sets the parent widget for this SpinBox (optional). Default is None.
        value          (float/int) initial value. Default is 0.0.
        bounds         (min,max) Minimum and maximum values allowed in the SpinBox. 
                       Either may be None to leave the value unbounded. By default, values are unbounded.
        suffix         (str) suffix (units) to display after the numerical value. By default, suffix is an empty str.
        siPrefix       (bool) If True, then an SI prefix is automatically prepended
                       to the units and the value is scaled accordingly. For example,
                       if value=0.003 and suffix='V', then the SpinBox will display
                       "300 mV" (but a call to SpinBox.value will still return 0.003). Default is False.
        step           (float) The size of a single step. This is used when clicking the up/
                       down arrows, when rolling the mouse wheel, or when pressing 
                       keyboard arrows while the widget has keyboard focus. Note that
                       the interpretation of this value is different when specifying
                       the 'dec' argument. Default is 0.01.
        dec            (bool) If True, then the step value will be adjusted to match 
                       the current size of the variable (for example, a value of 15
                       might step in increments of 1 whereas a value of 1500 would
                       step in increments of 100). In this case, the 'step' argument
                       is interpreted *relative* to the current value. The most common
                       'step' values when dec=True are 0.1, 0.2, 0.5, and 1.0. Default is False.
        minStep        (float) When dec=True, this specifies the minimum allowable step size.
        int            (bool) if True, the value is forced to integer type. Default is False
        decimals       (int) Number of decimal values to display. Default is 2. 
        ============== ========================================================================
        """
        QtGui.QAbstractSpinBox.__init__(self, parent)
        self.lastValEmitted = None
        self.lastText = ''
        self.textValid = True  ## If false, we draw a red border
        self.setMinimumWidth(0)
        self.setMaximumHeight(20)
        self.setSizePolicy(QtGui.QSizePolicy.Expanding,
                           QtGui.QSizePolicy.Preferred)
        self.opts = {
            'bounds': [None, None],

            ## Log scaling options   #### Log mode is no longer supported.
            #'step': 0.1,
            #'minStep': 0.001,
            #'log': True,
            #'dec': False,

            ## decimal scaling option - example
            #'step': 0.1,
            #'minStep': .001,
            #'log': False,
            #'dec': True,

            ## normal arithmetic step
            'step':
            D('0.01'
              ),  ## if 'dec' is false, the spinBox steps by 'step' every time
            ## if 'dec' is True, the step size is relative to the value
            ## 'step' needs to be an integral divisor of ten, ie 'step'*n=10 for some integer value of n (but only if dec is True)
            'log': False,
            'dec':
            False,  ## if true, does decimal stepping. ie from 1-10 it steps by 'step', from 10 to 100 it steps by 10*'step', etc. 
            ## if true, minStep must be set in order to cross zero.
            'int': False,  ## Set True to force value to be integer
            'suffix': '',
            'siPrefix':
            False,  ## Set to True to display numbers with SI prefix (ie, 100pA instead of 1e-10A)
            'delay': 0.3,  ## delay sending wheel update signals for 300ms
            'delayUntilEditFinished':
            True,  ## do not send signals until text editing has finished

            ## for compatibility with QDoubleSpinBox and QSpinBox
            'decimals': 3,
        }

        self.decOpts = ['step', 'minStep']

        self.val = D(asUnicode(
            value))  ## Value is precise decimal. Ordinary math not allowed.
        self.updateText()
        self.skipValidate = False
        self.setCorrectionMode(self.CorrectToPreviousValue)
        self.setKeyboardTracking(False)
        self.setOpts(**kwargs)

        self.editingFinished.connect(self.editingFinishedEvent)
        self.proxy = SignalProxy(self.sigValueChanging,
                                 slot=self.delayedChange,
                                 delay=self.opts['delay'])

    def event(self, ev):
        ret = QtGui.QAbstractSpinBox.event(self, ev)
        if ev.type() == QtCore.QEvent.KeyPress and ev.key(
        ) == QtCore.Qt.Key_Return:
            ret = True  ## For some reason, spinbox pretends to ignore return key press
        return ret

    ##lots of config options, just gonna stuff 'em all in here rather than do the get/set crap.
    def setOpts(self, **opts):
        """
        Changes the behavior of the SpinBox. Accepts most of the arguments 
        allowed in :func:`__init__ <pyqtgraph.SpinBox.__init__>`.
        
        """
        #print opts
        for k in opts:
            if k == 'bounds':
                #print opts[k]
                self.setMinimum(opts[k][0], update=False)
                self.setMaximum(opts[k][1], update=False)
                #for i in [0,1]:
                #if opts[k][i] is None:
                #self.opts[k][i] = None
                #else:
                #self.opts[k][i] = D(unicode(opts[k][i]))
            elif k in ['step', 'minStep']:
                self.opts[k] = D(asUnicode(opts[k]))
            elif k == 'value':
                pass  ## don't set value until bounds have been set
            else:
                self.opts[k] = opts[k]
        if 'value' in opts:
            self.setValue(opts['value'])

        ## If bounds have changed, update value to match
        if 'bounds' in opts and 'value' not in opts:
            self.setValue()

        ## sanity checks:
        if self.opts['int']:
            if 'step' in opts:
                step = opts['step']
                ## not necessary..
                #if int(step) != step:
                #raise Exception('Integer SpinBox must have integer step size.')
            else:
                self.opts['step'] = int(self.opts['step'])

            if 'minStep' in opts:
                step = opts['minStep']
                if int(step) != step:
                    raise Exception(
                        'Integer SpinBox must have integer minStep size.')
            else:
                ms = int(self.opts.get('minStep', 1))
                if ms < 1:
                    ms = 1
                self.opts['minStep'] = ms

        if 'delay' in opts:
            self.proxy.setDelay(opts['delay'])

        self.updateText()

    def setMaximum(self, m, update=True):
        """Set the maximum allowed value (or None for no limit)"""
        if m is not None:
            m = D(asUnicode(m))
        self.opts['bounds'][1] = m
        if update:
            self.setValue()

    def setMinimum(self, m, update=True):
        """Set the minimum allowed value (or None for no limit)"""
        if m is not None:
            m = D(asUnicode(m))
        self.opts['bounds'][0] = m
        if update:
            self.setValue()

    def setPrefix(self, p):
        self.setOpts(prefix=p)

    def setRange(self, r0, r1):
        self.setOpts(bounds=[r0, r1])

    def setProperty(self, prop, val):
        ## for QSpinBox compatibility
        if prop == 'value':
            #if type(val) is QtCore.QVariant:
            #val = val.toDouble()[0]
            self.setValue(val)
        else:
            print("Warning: SpinBox.setProperty('%s', ..) not supported." %
                  prop)

    def setSuffix(self, suf):
        self.setOpts(suffix=suf)

    def setSingleStep(self, step):
        self.setOpts(step=step)

    def setDecimals(self, decimals):
        self.setOpts(decimals=decimals)

    def selectNumber(self):
        """
        Select the numerical portion of the text to allow quick editing by the user.
        """
        le = self.lineEdit()
        text = asUnicode(le.text())
        if self.opts['suffix'] == '':
            le.setSelection(0, len(text))
        else:
            try:
                index = text.index(' ')
            except ValueError:
                return
            le.setSelection(0, index)

    def value(self):
        """
        Return the value of this SpinBox.
        
        """
        if self.opts['int']:
            return int(self.val)
        else:
            return float(self.val)

    def setValue(self, value=None, update=True, delaySignal=False):
        """
        Set the value of this spin. 
        If the value is out of bounds, it will be clipped to the nearest boundary.
        If the spin is integer type, the value will be coerced to int.
        Returns the actual value set.
        
        If value is None, then the current value is used (this is for resetting
        the value after bounds, etc. have changed)
        """

        if value is None:
            value = self.value()

        bounds = self.opts['bounds']
        if bounds[0] is not None and value < bounds[0]:
            value = bounds[0]
        if bounds[1] is not None and value > bounds[1]:
            value = bounds[1]

        if self.opts['int']:
            value = int(value)

        value = D(asUnicode(value))
        if value == self.val:
            return
        prev = self.val

        self.val = value
        if update:
            self.updateText(prev=prev)

        self.sigValueChanging.emit(
            self, float(self.val)
        )  ## change will be emitted in 300ms if there are no subsequent changes.
        if not delaySignal:
            self.emitChanged()

        return value

    def emitChanged(self):
        self.lastValEmitted = self.val
        self.valueChanged.emit(float(self.val))
        self.sigValueChanged.emit(self)

    def delayedChange(self):
        try:
            if self.val != self.lastValEmitted:
                self.emitChanged()
        except RuntimeError:
            pass  ## This can happen if we try to handle a delayed signal after someone else has already deleted the underlying C++ object.

    def widgetGroupInterface(self):
        return (self.valueChanged, SpinBox.value, SpinBox.setValue)

    def sizeHint(self):
        return QtCore.QSize(120, 0)

    def stepEnabled(self):
        return self.StepUpEnabled | self.StepDownEnabled

    #def fixup(self, *args):
    #print "fixup:", args

    def stepBy(self, n):
        n = D(int(n))  ## n must be integral number of steps.
        s = [D(-1), D(1)][n >= 0]  ## determine sign of step
        val = self.val

        for i in range(int(abs(n))):

            if self.opts['log']:
                raise Exception("Log mode no longer supported.")
            #    step = abs(val) * self.opts['step']
            #    if 'minStep' in self.opts:
            #        step = max(step, self.opts['minStep'])
            #    val += step * s
            if self.opts['dec']:
                if val == 0:
                    step = self.opts['minStep']
                    exp = None
                else:
                    vs = [D(-1), D(1)][val >= 0]
                    #exp = D(int(abs(val*(D('1.01')**(s*vs))).log10()))
                    fudge = D('1.01')**(
                        s * vs
                    )  ## fudge factor. at some places, the step size depends on the step sign.
                    exp = abs(val * fudge).log10().quantize(1, ROUND_FLOOR)
                    step = self.opts['step'] * D(10)**exp
                if 'minStep' in self.opts:
                    step = max(step, self.opts['minStep'])
                val += s * step
                #print "Exp:", exp, "step", step, "val", val
            else:
                val += s * self.opts['step']

            if 'minStep' in self.opts and abs(val) < self.opts['minStep']:
                val = D(0)
        self.setValue(
            val, delaySignal=True
        )  ## note all steps (arrow buttons, wheel, up/down keys..) emit delayed signals only.

    def valueInRange(self, value):
        bounds = self.opts['bounds']
        if bounds[0] is not None and value < bounds[0]:
            return False
        if bounds[1] is not None and value > bounds[1]:
            return False
        if self.opts.get('int', False):
            if int(value) != value:
                return False
        return True

    def updateText(self, prev=None):

        # get the number of decimal places to print
        decimals = self.opts.get('decimals')

        # temporarily disable validation
        self.skipValidate = True

        # if we're supposed to add a prefix to the label
        if self.opts['siPrefix']:

            # special case: if it's zero use the previous prefix
            if self.val == 0 and prev is not None:
                (s, p) = fn.siScale(prev)

                # NOTE: Could have the user specify a format string and use it here
                txt = ("%." + str(decimals) + "g %s%s") % (0, p,
                                                           self.opts['suffix'])
            else:
                # NOTE: Could have the user specify a format string and send it as an argument here
                txt = fn.siFormat(float(self.val),
                                  precision=decimals,
                                  suffix=self.opts['suffix'])

        # otherwise, format the string manually
        else:
            # NOTE: Could have the user specify a format string and use it here
            txt = ('%.' + str(decimals) + 'g%s') % (self.val,
                                                    self.opts['suffix'])

        # actually set the text
        self.lineEdit().setText(txt)
        self.lastText = txt

        # re-enable the validation
        self.skipValidate = False

    def validate(self, strn, pos):
        if self.skipValidate:
            #print "skip validate"
            #self.textValid = False
            ret = QtGui.QValidator.Acceptable
        else:
            try:
                ## first make sure we didn't mess with the suffix
                suff = self.opts.get('suffix', '')
                if len(suff) > 0 and asUnicode(strn)[-len(suff):] != suff:
                    #print '"%s" != "%s"' % (unicode(strn)[-len(suff):], suff)
                    ret = QtGui.QValidator.Invalid

                ## next see if we actually have an interpretable value
                else:
                    val = self.interpret()
                    if val is False:
                        #print "can't interpret"
                        #self.setStyleSheet('SpinBox {border: 2px solid #C55;}')
                        #self.textValid = False
                        ret = QtGui.QValidator.Intermediate
                    else:
                        if self.valueInRange(val):
                            if not self.opts['delayUntilEditFinished']:
                                self.setValue(val, update=False)
                            #print "  OK:", self.val
                            #self.setStyleSheet('')
                            #self.textValid = True

                            ret = QtGui.QValidator.Acceptable
                        else:
                            ret = QtGui.QValidator.Intermediate

            except:
                #print "  BAD"
                #import sys
                #sys.excepthook(*sys.exc_info())
                #self.textValid = False
                #self.setStyleSheet('SpinBox {border: 2px solid #C55;}')
                ret = QtGui.QValidator.Intermediate

        ## draw / clear border
        if ret == QtGui.QValidator.Intermediate:
            self.textValid = False
        elif ret == QtGui.QValidator.Acceptable:
            self.textValid = True
        ## note: if text is invalid, we don't change the textValid flag
        ## since the text will be forced to its previous state anyway
        self.update()

        ## support 2 different pyqt APIs. Bleh.
        if hasattr(QtCore, 'QString'):
            return (ret, pos)
        else:
            return (ret, strn, pos)

    def paintEvent(self, ev):
        QtGui.QAbstractSpinBox.paintEvent(self, ev)

        ## draw red border if text is invalid
        if not self.textValid:
            p = QtGui.QPainter(self)
            p.setRenderHint(p.Antialiasing)
            p.setPen(fn.mkPen((200, 50, 50), width=2))
            p.drawRoundedRect(self.rect().adjusted(2, 2, -2, -2), 4, 4)
            p.end()

    def interpret(self):
        """Return value of text. Return False if text is invalid, raise exception if text is intermediate"""
        strn = self.lineEdit().text()
        suf = self.opts['suffix']
        if len(suf) > 0:
            if strn[-len(suf):] != suf:
                return False
            #raise Exception("Units are invalid.")
            strn = strn[:-len(suf)]
        try:
            val = fn.siEval(strn)
        except:
            #sys.excepthook(*sys.exc_info())
            #print "invalid"
            return False
        #print val
        return val

    #def interpretText(self, strn=None):
    #print "Interpret:", strn
    #if strn is None:
    #strn = self.lineEdit().text()
    #self.setValue(siEval(strn), update=False)
    ##QtGui.QAbstractSpinBox.interpretText(self)

    def editingFinishedEvent(self):
        """Edit has finished; set value."""
        #print "Edit finished."
        if asUnicode(self.lineEdit().text()) == self.lastText:
            #print "no text change."
            return
        try:
            val = self.interpret()
        except:
            return

        if val is False:
            #print "value invalid:", str(self.lineEdit().text())
            return
        if val == self.val:
            #print "no value change:", val, self.val
            return
        self.setValue(
            val, delaySignal=False
        )  ## allow text update so that values are reformatted pretty-like
Exemplo n.º 8
0
    def __init__(self, parent=None, name="ImageView", view=None, imageItem=None, *args):
        """
        By default, this class creates an :class:`ImageItem <pyqtgraph.ImageItem>` to display image data
        and a :class:`ViewBox <pyqtgraph.ViewBox>` to contain the ImageItem. 
        
        ============= =========================================================
        **Arguments** 
        parent        (QWidget) Specifies the parent widget to which
                      this ImageView will belong. If None, then the ImageView
                      is created with no parent.
        name          (str) The name used to register both the internal ViewBox
                      and the PlotItem used to display ROI data. See the *name*
                      argument to :func:`ViewBox.__init__() 
                      <pyqtgraph.ViewBox.__init__>`.
        view          (ViewBox or PlotItem) If specified, this will be used
                      as the display area that contains the displayed image. 
                      Any :class:`ViewBox <pyqtgraph.ViewBox>`, 
                      :class:`PlotItem <pyqtgraph.PlotItem>`, or other 
                      compatible object is acceptable.
        imageItem     (ImageItem) If specified, this object will be used to
                      display the image. Must be an instance of ImageItem
                      or other compatible object.
        ============= =========================================================
        
        Note: to display axis ticks inside the ImageView, instantiate it 
        with a PlotItem instance as its view::
                
            pg.ImageView(view=pg.PlotItem())
        """
        QtGui.QWidget.__init__(self, parent, *args)
        self.markerRadius = 50 #circle radius marking single points/rois
        self.clicked = []
        self.image_Designation = None
        self.levelMax = 4096
        self.levelMin = 0
        self.name = name
        self.image = None
        self.axes = {}
        self.imageDisp = None
        self.ui = Ui_Form() #pyqtgraph.imageview.ImageViewTemplate_pyqt
        self.ui.setupUi(self)
        self.scene = self.ui.graphicsView.scene()
        
        self.ignoreTimeLine = False
        self.ignoreZLine = False
        
        if view is None:
            self.view = ViewBox()
        else:
            self.view = view
        
        self.ui.graphicsView.setCentralItem(self.view)
        self.view.setAspectLocked(True)
        self.view.invertY()
        
        if imageItem is None:
            self.imageItem = ImageItem()
        else:
            self.imageItem = imageItem
        self.imageview = self.view.addItem(self.imageItem)
        self.currentTime = 0
        self.currentLayer = 0 #layer in z axis
        
        #relay x y coordinates within image
        self.view.scene().sigMouseMoved.connect(self.mouseMoved)
        self.view.scene().sigMouseClicked.connect(self.mouseClicked)
        #self.view.scene().mouseReleaseEvent(self.releaseEvent)
        #self.view.scene().mouseReleaseEvent(self.mouseReleased)
        #pdb.set_trace()
        #generate roi list
        self.croi = [] #holdes x,y,z points for roi
        self.ccroi = [] #hold pg roi for croi
        self.aroi = {} #place to store all rois, each roi is passed as dictionary with each index = currentLayer
        self.aaroi = [] #place to store pg of arois in self.currentLayer
        self.button1 = 'off'
        
        self.ui.histogram.setImageItem(self.imageItem)
        
        self.menu = None
        
        self.ui.normGroup.hide()

        self.roi = PlotROI(10)
        self.roi.setZValue(20)
        self.view.addItem(self.roi)
        self.roi.hide()
        self.normRoi = PlotROI(10)
        self.normRoi.setPen('y')
        self.normRoi.setZValue(20)
        self.view.addItem(self.normRoi)
        self.normRoi.hide()
        self.roiCurve = self.ui.roiPlot.plot()
        
        
        self.timeLine = InfiniteLine(0, movable=True)
        self.timeLine.setPen((255, 255, 0, 200))
        #self.timeLine.setPen((255, 255, 200, 0))
        self.timeLine.setZValue(1)
        self.ui.roiPlot.addItem(self.timeLine)
        self.ui.splitter.setSizes([self.height()-35, 35])
        self.ui.roiPlot.hideAxis('left')
        
        
        
        self.ui.splitter.setSizes([self.height(), 10])
        self.ui.zPlot.plot()
        self.zLine = InfiniteLine(0, movable=True, angle = 0)
        #self.zLine.setBounds([0, 42])
        self.zLine.setPen((255, 255, 0, 200))
        self.zLine.setZValue(self.currentLayer )
        self.ui.ztext.setText(str(self.currentLayer))
        
        self.ui.zPlot.addItem(self.zLine)
        self.ui.zPlot.hideAxis('bottom')
        
        
        
        self.keysPressed = {}
        self.playTimer = QtCore.QTimer()
        self.playRate = 0
        self.lastPlayTime = 0
        
        self.normRgn = LinearRegionItem()
        self.normRgn.setZValue(0)
        self.ui.roiPlot.addItem(self.normRgn)
        self.normRgn.hide()
            
        ## wrap functions from view box
        for fn in ['addItem', 'removeItem']:
            setattr(self, fn, getattr(self.view, fn))

        ## wrap functions from histogram
        for fn in ['setHistogramRange', 'autoHistogramRange', 'getLookupTable', 'getLevels']:
            setattr(self, fn, getattr(self.ui.histogram, fn))

        self.timeLine.sigPositionChanged.connect(self.timeLineChanged)
        self.zLine.sigPositionChanged.connect(self.zLineChanged)
        self.ui.roiBtn.clicked.connect(self.roiClicked)
        self.roi.sigRegionChanged.connect(self.roiChanged)
        #self.ui.normBtn.toggled.connect(self.normToggled)
        self.ui.menuBtn.clicked.connect(self.menuClicked)
        self.ui.normDivideRadio.clicked.connect(self.normRadioChanged)
        self.ui.normSubtractRadio.clicked.connect(self.normRadioChanged)
        self.ui.normOffRadio.clicked.connect(self.normRadioChanged)
        self.ui.normROICheck.clicked.connect(self.updateNorm)
        self.ui.normFrameCheck.clicked.connect(self.updateNorm)
        self.ui.normTimeRangeCheck.clicked.connect(self.updateNorm)
        #radio button for navigation and roi selection
        self.ui.navRadio.clicked.connect(self.NavigationStatus)
        self.ui.radioSinglePoint.clicked.connect(self.radioSinglePoint)
        self.ui.radioAreaROI.clicked.connect(self.radioAreaROI)
        self.ui.radioPolygon.clicked.connect(self.radioPolygon)
        self.ui.radioEdit.clicked.connect(self.radioEdit)
        
        self.playTimer.timeout.connect(self.timeout)
        
        self.normProxy = SignalProxy(self.normRgn.sigRegionChanged, slot=self.updateNorm)
        self.normRoi.sigRegionChangeFinished.connect(self.updateNorm)
        
        self.ui.roiPlot.registerPlot(self.name + '_ROI')
        self.view.register(self.name)
        
        self.noRepeatKeys = [QtCore.Qt.Key_Right, QtCore.Qt.Key_Left, QtCore.Qt.Key_Up, QtCore.Qt.Key_Down, QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown]
        
        self.roiClicked() ## initialize roi plot to correct shape / visibility
Exemplo n.º 9
0
    def __init__(self,
                 parent=None,
                 name="ImageView",
                 view=None,
                 imageItem=None,
                 *args):
        """
        By default, this class creates an :class:`ImageItem <pyqtgraph.ImageItem>` to display image data
        and a :class:`ViewBox <pyqtgraph.ViewBox>` to contain the ImageItem. Custom items may be given instead 
        by specifying the *view* and/or *imageItem* arguments.
        """
        QtGui.QWidget.__init__(self, parent, *args)
        self.levelMax = 4096
        self.levelMin = 0
        self.name = name
        self.image = None
        self.axes = {}
        self.imageDisp = None
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.scene = self.ui.graphicsView.scene()

        self.ignoreTimeLine = False

        if view is None:
            self.view = ViewBox()
        else:
            self.view = view
        self.ui.graphicsView.setCentralItem(self.view)
        self.view.setAspectLocked(True)
        self.view.invertY()

        if imageItem is None:
            self.imageItem = ImageItem()
        else:
            self.imageItem = imageItem
        self.view.addItem(self.imageItem)
        self.currentIndex = 0

        self.ui.histogram.setImageItem(self.imageItem)

        self.ui.normGroup.hide()

        self.roi = PlotROI(10)
        self.roi.setZValue(20)
        self.view.addItem(self.roi)
        self.roi.hide()
        self.normRoi = PlotROI(10)
        self.normRoi.setPen(QtGui.QPen(QtGui.QColor(255, 255, 0)))
        self.normRoi.setZValue(20)
        self.view.addItem(self.normRoi)
        self.normRoi.hide()
        self.roiCurve = self.ui.roiPlot.plot()
        self.timeLine = InfiniteLine(0, movable=True)
        self.timeLine.setPen(QtGui.QPen(QtGui.QColor(255, 255, 0, 200)))
        self.timeLine.setZValue(1)
        self.ui.roiPlot.addItem(self.timeLine)
        self.ui.splitter.setSizes([self.height() - 35, 35])
        self.ui.roiPlot.hideAxis('left')

        self.keysPressed = {}
        self.playTimer = QtCore.QTimer()
        self.playRate = 0
        self.lastPlayTime = 0

        self.normRgn = LinearRegionItem()
        self.normRgn.setZValue(0)
        self.ui.roiPlot.addItem(self.normRgn)
        self.normRgn.hide()

        ## wrap functions from view box
        for fn in ['addItem', 'removeItem']:
            setattr(self, fn, getattr(self.view, fn))

        ## wrap functions from histogram
        for fn in [
                'setHistogramRange', 'autoHistogramRange', 'getLookupTable',
                'getLevels'
        ]:
            setattr(self, fn, getattr(self.ui.histogram, fn))

        self.timeLine.sigPositionChanged.connect(self.timeLineChanged)
        self.ui.roiBtn.clicked.connect(self.roiClicked)
        self.roi.sigRegionChanged.connect(self.roiChanged)
        self.ui.normBtn.toggled.connect(self.normToggled)
        self.ui.normDivideRadio.clicked.connect(self.normRadioChanged)
        self.ui.normSubtractRadio.clicked.connect(self.normRadioChanged)
        self.ui.normOffRadio.clicked.connect(self.normRadioChanged)
        self.ui.normROICheck.clicked.connect(self.updateNorm)
        self.ui.normFrameCheck.clicked.connect(self.updateNorm)
        self.ui.normTimeRangeCheck.clicked.connect(self.updateNorm)
        self.playTimer.timeout.connect(self.timeout)

        self.normProxy = SignalProxy(self.normRgn.sigRegionChanged,
                                     slot=self.updateNorm)
        self.normRoi.sigRegionChangeFinished.connect(self.updateNorm)

        self.ui.roiPlot.registerPlot(self.name + '_ROI')

        self.noRepeatKeys = [
            QtCore.Qt.Key_Right, QtCore.Qt.Key_Left, QtCore.Qt.Key_Up,
            QtCore.Qt.Key_Down, QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown
        ]

        self.roiClicked()  ## initialize roi plot to correct shape / visibility