desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Restore the gradient specified in state.
**Arguments:**
state A dictionary with same structure as those returned by
:func:`saveState <pyqtgraph.GradientEditorItem.saveState>`
Keys must include:
- \'mode\': hsv or rgb
- \'ticks\': a list of tuples (pos, (r,g,b,a))'
| def restoreState(self, state):
| self.setColorMode(state['mode'])
for t in list(self.ticks.keys()):
self.removeTick(t, finish=False)
for t in state['ticks']:
c = QtGui.QColor(*t[1])
self.addTick(t[0], c, finish=False)
self.updateGradient()
self.sigGradientChangeFinished.emit(self)
|
'Set the curves to fill between.
Arguments must be instances of PlotDataItem or PlotCurveItem.
Added in version 0.9.9'
| def setCurves(self, curve1, curve2):
| if (self.curves is not None):
for c in self.curves:
try:
c.sigPlotChanged.disconnect(self.curveChanged)
except (TypeError, RuntimeError):
pass
curves = [curve1, curve2]
for c in curves:
if ((not isinstance(c, PlotDataItem)) and (not isinstance(c, PlotCurveItem))):
raise TypeError('Curves must be PlotDataItem or PlotCurveItem.')
self.curves = curves
curve1.sigPlotChanged.connect(self.curveChanged)
curve2.sigPlotChanged.connect(self.curveChanged)
self.setZValue((min(curve1.zValue(), curve2.zValue()) - 1))
self.curveChanged()
|
'Change the fill brush. Acceps the same arguments as pg.mkBrush()'
| def setBrush(self, *args, **kwds):
| QtGui.QGraphicsPathItem.setBrush(self, fn.mkBrush(*args, **kwds))
|
'**Arguments:**
size Specifies the fixed size (width, height) of the legend. If
this argument is omitted, the legend will autimatically resize
to fit its contents.
offset Specifies the offset position relative to the legend\'s parent.
Positive values offset from the left or top; negative values
offset from the right or bottom. If offset is None, the
legend must be anchored manually by calling anchor() or
positioned by calling setPos().'
| def __init__(self, size=None, offset=None):
| GraphicsWidget.__init__(self)
GraphicsWidgetAnchor.__init__(self)
self.setFlag(self.ItemIgnoresTransformations)
self.layout = QtGui.QGraphicsGridLayout()
self.setLayout(self.layout)
self.items = []
self.size = size
self.offset = offset
if (size is not None):
self.setGeometry(QtCore.QRectF(0, 0, self.size[0], self.size[1]))
|
'Add a new entry to the legend.
**Arguments:**
item A PlotDataItem from which the line and point style
of the item will be determined or an instance of
ItemSample (or a subclass), allowing the item display
to be customized.
title The title to display for this item. Simple HTML allowed.'
| def addItem(self, item, name):
| label = LabelItem(name)
if isinstance(item, ItemSample):
sample = item
else:
sample = ItemSample(item)
row = self.layout.rowCount()
self.items.append((sample, label))
self.layout.addItem(sample, row, 0)
self.layout.addItem(label, row, 1)
self.updateSize()
|
'Removes one item from the legend.
**Arguments:**
title The title displayed for this item.'
| def removeItem(self, name):
| for (sample, label) in self.items:
if (label.text == name):
self.items.remove((sample, label))
self.layout.removeItem(sample)
sample.close()
self.layout.removeItem(label)
label.close()
self.updateSize()
|
'See :func:`setImage <pyqtgraph.ImageItem.setImage>` for all allowed initialization arguments.'
| def __init__(self, image=None, **kargs):
| GraphicsObject.__init__(self)
self.menu = None
self.image = None
self.qimage = None
self.paintMode = None
self.levels = None
self.lut = None
self.autoDownsample = False
self.axisOrder = getConfigOption('imageAxisOrder')
self._effectiveLut = None
self.drawKernel = None
self.border = None
self.removable = False
if (image is not None):
self.setImage(image, **kargs)
else:
self.setOpts(**kargs)
|
'Change the composition mode of the item (see QPainter::CompositionMode
in the Qt documentation). This is useful when overlaying multiple ImageItems.
**Most common arguments:**
QtGui.QPainter.CompositionMode_SourceOver Default; image replaces the background if it
is opaque. Otherwise, it uses the alpha channel to blend
the image with the background.
QtGui.QPainter.CompositionMode_Overlay The image color is mixed with the background color to
reflect the lightness or darkness of the background.
QtGui.QPainter.CompositionMode_Plus Both the alpha and color of the image and background pixels
are added together.
QtGui.QPainter.CompositionMode_Multiply The output is the image color multiplied by the background.'
| def setCompositionMode(self, mode):
| self.paintMode = mode
self.update()
|
'Set image scaling levels. Can be one of:
* [blackLevel, whiteLevel]
* [[minRed, maxRed], [minGreen, maxGreen], [minBlue, maxBlue]]
Only the first format is compatible with lookup tables. See :func:`makeARGB <pyqtgraph.makeARGB>`
for more details on how levels are applied.'
| def setLevels(self, levels, update=True):
| if (levels is not None):
levels = np.asarray(levels)
if (not fn.eq(levels, self.levels)):
self.levels = levels
self._effectiveLut = None
if update:
self.updateImage()
|
'Set the lookup table (numpy array) to use for this image. (see
:func:`makeARGB <pyqtgraph.makeARGB>` for more information on how this is used).
Optionally, lut can be a callable that accepts the current image as an
argument and returns the lookup table to use.
Ordinarily, this table is supplied by a :class:`HistogramLUTItem <pyqtgraph.HistogramLUTItem>`
or :class:`GradientEditorItem <pyqtgraph.GradientEditorItem>`.'
| def setLookupTable(self, lut, update=True):
| if (lut is not self.lut):
self.lut = lut
self._effectiveLut = None
if update:
self.updateImage()
|
'Set the automatic downsampling mode for this ImageItem.
Added in version 0.9.9'
| def setAutoDownsample(self, ads):
| self.autoDownsample = ads
self.qimage = None
self.update()
|
'Scale and translate the image to fit within rect (must be a QRect or QRectF).'
| def setRect(self, rect):
| self.resetTransform()
self.translate(rect.left(), rect.top())
self.scale((rect.width() / self.width()), (rect.height() / self.height()))
|
'Update the image displayed by this item. For more information on how the image
is processed before displaying, see :func:`makeARGB <pyqtgraph.makeARGB>`
**Arguments:**
image (numpy array) Specifies the image data. May be 2D (width, height) or
3D (width, height, RGBa). The array dtype must be integer or floating
point of any bit depth. For 3D arrays, the third dimension must
be of length 3 (RGB) or 4 (RGBA). See *notes* below.
autoLevels (bool) If True, this forces the image to automatically select
levels based on the maximum and minimum values in the data.
By default, this argument is true unless the levels argument is
given.
lut (numpy array) The color lookup table to use when displaying the image.
See :func:`setLookupTable <pyqtgraph.ImageItem.setLookupTable>`.
levels (min, max) The minimum and maximum values to use when rescaling the image
data. By default, this will be set to the minimum and maximum values
in the image. If the image array has dtype uint8, no rescaling is necessary.
opacity (float 0.0-1.0)
compositionMode See :func:`setCompositionMode <pyqtgraph.ImageItem.setCompositionMode>`
border Sets the pen used when drawing the image border. Default is None.
autoDownsample (bool) If True, the image is automatically downsampled to match the
screen resolution. This improves performance for large images and
reduces aliasing. If autoDownsample is not specified, then ImageItem will
choose whether to downsample the image based on its size.
**Notes:**
For backward compatibility, image data is assumed to be in column-major order (column, row).
However, most image data is stored in row-major order (row, column) and will need to be
transposed before calling setImage()::
imageitem.setImage(imagedata.T)
This requirement can be changed by calling ``image.setOpts(axisOrder=\'row-major\')`` or
by changing the ``imageAxisOrder`` :ref:`global configuration option <apiref_config>`.'
| def setImage(self, image=None, autoLevels=None, **kargs):
| profile = debug.Profiler()
gotNewData = False
if (image is None):
if (self.image is None):
return
else:
gotNewData = True
shapeChanged = ((self.image is None) or (image.shape != self.image.shape))
image = image.view(np.ndarray)
if ((self.image is None) or (image.dtype != self.image.dtype)):
self._effectiveLut = None
self.image = image
if ((self.image.shape[0] > ((2 ** 15) - 1)) or (self.image.shape[1] > ((2 ** 15) - 1))):
if ('autoDownsample' not in kargs):
kargs['autoDownsample'] = True
if shapeChanged:
self.prepareGeometryChange()
self.informViewBoundsChanged()
profile()
if (autoLevels is None):
if ('levels' in kargs):
autoLevels = False
else:
autoLevels = True
if autoLevels:
img = self.image
while (img.size > (2 ** 16)):
img = img[::2, ::2]
(mn, mx) = (img.min(), img.max())
if (mn == mx):
mn = 0
mx = 255
kargs['levels'] = [mn, mx]
profile()
self.setOpts(update=False, **kargs)
profile()
self.qimage = None
self.update()
profile()
if gotNewData:
self.sigImageChanged.emit()
|
'Return the transform that maps from this image\'s input array to its
local coordinate system.
This transform corrects for the transposition that occurs when image data
is interpreted in row-major order.'
| def dataTransform(self):
| tr = QtGui.QTransform()
if (self.axisOrder == 'row-major'):
tr.scale(1, (-1))
tr.rotate((-90))
return tr
|
'Return the transform that maps from this image\'s local coordinate
system to its input array.
See dataTransform() for more information.'
| def inverseDataTransform(self):
| tr = QtGui.QTransform()
if (self.axisOrder == 'row-major'):
tr.scale(1, (-1))
tr.rotate((-90))
return tr
|
'Estimate the min/max values of the image data by subsampling.'
| def quickMinMax(self, targetSize=1000000.0):
| data = self.image
while (data.size > targetSize):
ax = np.argmax(data.shape)
sl = ([slice(None)] * data.ndim)
sl[ax] = slice(None, None, 2)
data = data[sl]
return (nanmin(data), nanmax(data))
|
'Save this image to file. Note that this saves the visible image (after scale/color changes), not the original data.'
| def save(self, fileName, *args):
| if (self.qimage is None):
self.render()
self.qimage.save(fileName, *args)
|
'Returns x and y arrays containing the histogram values for the current image.
For an explanation of the return format, see numpy.histogram().
The *step* argument causes pixels to be skipped when computing the histogram to save time.
If *step* is \'auto\', then a step is chosen such that the analyzed data has
dimensions roughly *targetImageSize* for each axis.
The *bins* argument and any extra keyword arguments are passed to
np.histogram(). If *bins* is \'auto\', then a bin number is automatically
chosen based on the image characteristics:
* Integer images will have approximately *targetHistogramSize* bins,
with each bin having an integer width.
* All other types will have *targetHistogramSize* bins.
This method is also used when automatically computing levels.'
| def getHistogram(self, bins='auto', step='auto', targetImageSize=200, targetHistogramSize=500, **kwds):
| if (self.image is None):
return (None, None)
if (step == 'auto'):
step = (int(np.ceil((self.image.shape[0] / targetImageSize))), int(np.ceil((self.image.shape[1] / targetImageSize))))
if np.isscalar(step):
step = (step, step)
stepData = self.image[::step[0], ::step[1]]
if (bins == 'auto'):
if (stepData.dtype.kind in 'ui'):
mn = stepData.min()
mx = stepData.max()
step = np.ceil(((mx - mn) / 500.0))
bins = np.arange(mn, (mx + (1.01 * step)), step, dtype=np.int)
if (len(bins) == 0):
bins = [mn, mx]
else:
bins = 500
kwds['bins'] = bins
stepData = stepData[np.isfinite(stepData)]
hist = np.histogram(stepData, **kwds)
return (hist[1][:(-1)], hist[0])
|
'Set whether the item ignores transformations and draws directly to screen pixels.
If True, the item will not inherit any scale or rotation transformations from its
parent items, but its position will be transformed as usual.
(see GraphicsItem::ItemIgnoresTransformations in the Qt documentation)'
| def setPxMode(self, b):
| self.setFlag(self.ItemIgnoresTransformations, b)
|
'return scene-size of a single pixel in the image'
| def pixelSize(self):
| br = self.sceneBoundingRect()
if (self.image is None):
return (1, 1)
return ((br.width() / self.width()), (br.height() / self.height()))
|
'**Arguments:**
xvals A list of x values (in data coordinates) at which to draw ticks.
yrange A list of [low, high] limits for the tick. 0 is the bottom of
the view, 1 is the top. [0.8, 1] would draw ticks in the top
fifth of the view.
pen The pen to use for drawing ticks. Default is grey. Can be specified
as any argument valid for :func:`mkPen<pyqtgraph.mkPen>`'
| def __init__(self, xvals=None, yrange=None, pen=None):
| if (yrange is None):
yrange = [0, 1]
if (xvals is None):
xvals = []
UIGraphicsItem.__init__(self)
if (pen is None):
pen = (200, 200, 200)
self.path = QtGui.QGraphicsPathItem()
self.ticks = []
self.xvals = []
self.yrange = [0, 1]
self.setPen(pen)
self.setYRange(yrange)
self.setXVals(xvals)
|
'Set the pen to use for drawing ticks. Can be specified as any arguments valid
for :func:`mkPen<pyqtgraph.mkPen>`'
| def setPen(self, *args, **kwargs):
| self.pen = fn.mkPen(*args, **kwargs)
|
'Set the x values for the ticks.
**Arguments:**
vals A list of x values (in data/plot coordinates) at which to draw ticks.'
| def setXVals(self, vals):
| self.xvals = vals
self.rebuildTicks()
|
'Set the y range [low, high] that the ticks are drawn on. 0 is the bottom of
the view, 1 is the top.'
| def setYRange(self, vals):
| self.yrange = vals
self.rebuildTicks()
|
'Create a new LinearRegionItem.
**Arguments:**
values A list of the positions of the lines in the region. These are not
limits; limits can be set by specifying bounds.
orientation Options are LinearRegionItem.Vertical or LinearRegionItem.Horizontal.
If not specified it will be vertical.
brush Defines the brush that fills the region. Can be any arguments that
are valid for :func:`mkBrush <pyqtgraph.mkBrush>`. Default is
transparent blue.
movable If True, the region and individual lines are movable by the user; if
False, they are static.
bounds Optional [min, max] bounding values for the region'
| def __init__(self, values=[0, 1], orientation=None, brush=None, movable=True, bounds=None):
| UIGraphicsItem.__init__(self)
if (orientation is None):
orientation = LinearRegionItem.Vertical
self.orientation = orientation
self.bounds = QtCore.QRectF()
self.blockLineSignal = False
self.moving = False
self.mouseHovering = False
if (orientation == LinearRegionItem.Horizontal):
self.lines = [InfiniteLine(QtCore.QPointF(0, values[0]), 0, movable=movable, bounds=bounds), InfiniteLine(QtCore.QPointF(0, values[1]), 0, movable=movable, bounds=bounds)]
elif (orientation == LinearRegionItem.Vertical):
self.lines = [InfiniteLine(QtCore.QPointF(values[1], 0), 90, movable=movable, bounds=bounds), InfiniteLine(QtCore.QPointF(values[0], 0), 90, movable=movable, bounds=bounds)]
else:
raise Exception('Orientation must be one of LinearRegionItem.Vertical or LinearRegionItem.Horizontal')
for l in self.lines:
l.setParentItem(self)
l.sigPositionChangeFinished.connect(self.lineMoveFinished)
l.sigPositionChanged.connect(self.lineMoved)
if (brush is None):
brush = QtGui.QBrush(QtGui.QColor(0, 0, 255, 50))
self.setBrush(brush)
self.setMovable(movable)
|
'Return the values at the edges of the region.'
| def getRegion(self):
| r = [self.lines[0].value(), self.lines[1].value()]
return (min(r), max(r))
|
'Set the values for the edges of the region.
**Arguments:**
rgn A list or tuple of the lower and upper values.'
| def setRegion(self, rgn):
| if ((self.lines[0].value() == rgn[0]) and (self.lines[1].value() == rgn[1])):
return
self.blockLineSignal = True
self.lines[0].setValue(rgn[0])
self.blockLineSignal = False
self.lines[1].setValue(rgn[1])
self.lineMoved()
self.lineMoveFinished()
|
'Set the brush that fills the region. Can have any arguments that are valid
for :func:`mkBrush <pyqtgraph.mkBrush>`.'
| def setBrush(self, *br, **kargs):
| self.brush = fn.mkBrush(*br, **kargs)
self.currentBrush = self.brush
|
'Optional [min, max] bounding values for the region. To have no bounds on the
region use [None, None].
Does not affect the current position of the region unless it is outside the new bounds.
See :func:`setRegion <pyqtgraph.LinearRegionItem.setRegion>` to set the position
of the region.'
| def setBounds(self, bounds):
| for l in self.lines:
l.setBounds(bounds)
|
'Set lines to be movable by the user, or not. If lines are movable, they will
also accept HoverEvents.'
| def setMovable(self, m):
| for l in self.lines:
l.setMovable(m)
self.movable = m
self.setAcceptHoverEvents(m)
|
'Create a new isocurve item.
**Arguments:**
data A 2-dimensional ndarray. Can be initialized as None, and set
later using :func:`setData <pyqtgraph.IsocurveItem.setData>`
level The cutoff value at which to draw the isocurve.
pen The color of the curve item. Can be anything valid for
:func:`mkPen <pyqtgraph.mkPen>`
axisOrder May be either \'row-major\' or \'col-major\'. By default this uses
the ``imageAxisOrder``
:ref:`global configuration option <apiref_config>`.'
| def __init__(self, data=None, level=0, pen='w', axisOrder=None):
| GraphicsObject.__init__(self)
self.level = level
self.data = None
self.path = None
self.axisOrder = (getConfigOption('imageAxisOrder') if (axisOrder is None) else axisOrder)
self.setPen(pen)
self.setData(data, level)
|
'Set the data/image to draw isocurves for.
**Arguments:**
data A 2-dimensional ndarray.
level The cutoff value at which to draw the curve. If level is not specified,
the previously set level is used.'
| def setData(self, data, level=None):
| if (level is None):
level = self.level
self.level = level
self.data = data
self.path = None
self.prepareGeometryChange()
self.update()
|
'Set the level at which the isocurve is drawn.'
| def setLevel(self, level):
| self.level = level
self.path = None
self.prepareGeometryChange()
self.update()
|
'Set the pen used to draw the isocurve. Arguments can be any that are valid
for :func:`mkPen <pyqtgraph.mkPen>`'
| def setPen(self, *args, **kwargs):
| self.pen = fn.mkPen(*args, **kwargs)
self.update()
|
'Set the brush used to draw the isocurve. Arguments can be any that are valid
for :func:`mkBrush <pyqtgraph.mkBrush>`'
| def setBrush(self, *args, **kwargs):
| self.brush = fn.mkBrush(*args, **kwargs)
self.update()
|
'All keyword arguments are passed to setData().'
| def __init__(self, **opts):
| GraphicsObject.__init__(self)
self.opts = dict(x=None, y=None, height=None, width=None, top=None, bottom=None, left=None, right=None, beam=None, pen=None)
self.setData(**opts)
|
'Update the data in the item. All arguments are optional.
Valid keyword options are:
x, y, height, width, top, bottom, left, right, beam, pen
* x and y must be numpy arrays specifying the coordinates of data points.
* height, width, top, bottom, left, right, and beam may be numpy arrays,
single values, or None to disable. All values should be positive.
* top, bottom, left, and right specify the lengths of bars extending
in each direction.
* If height is specified, it overrides top and bottom.
* If width is specified, it overrides left and right.
* beam specifies the width of the beam at the end of each bar.
* pen may be any single argument accepted by pg.mkPen().
This method was added in version 0.9.9. For prior versions, use setOpts.'
| def setData(self, **opts):
| self.opts.update(opts)
self.path = None
self.update()
self.prepareGeometryChange()
self.informViewBoundsChanged()
|
'**Arguments:**
bounds QRectF with coordinates relative to view box. The default is QRectF(0,0,1,1),
which means the item will have the same bounds as the view.'
| def __init__(self, bounds=None, parent=None):
| GraphicsObject.__init__(self, parent)
self.setFlag(self.ItemSendsScenePositionChanges)
if (bounds is None):
self._bounds = QtCore.QRectF(0, 0, 1, 1)
else:
self._bounds = bounds
self._boundingRect = None
self._updateView()
|
'Called by ViewBox for determining the auto-range bounds.
By default, UIGraphicsItems are excluded from autoRange.'
| def dataBounds(self, axis, frac=1.0, orthoRange=None):
| return None
|
'Called when the view widget/viewbox is resized/rescaled'
| def viewRangeChanged(self):
| self.setNewBounds()
self.update()
|
'Update the item\'s bounding rect to match the viewport'
| def setNewBounds(self):
| self._boundingRect = None
self.prepareGeometryChange()
|
'Return the shape of this item after expanding by 2 pixels'
| def mouseShape(self):
| shape = self.shape()
ds = self.mapToDevice(shape)
stroker = QtGui.QPainterPathStroker()
stroker.setWidh(2)
ds2 = stroker.createStroke(ds).united(ds)
return self.mapFromDevice(ds2)
|
'Forwards all arguments to :func:`setData <pyqtgraph.PlotCurveItem.setData>`.
Some extra arguments are accepted as well:
**Arguments:**
parent The parent GraphicsObject (optional)
clickable If True, the item will emit sigClicked when it is
clicked on. Defaults to False.'
| def __init__(self, *args, **kargs):
| GraphicsObject.__init__(self, kargs.get('parent', None))
self.clear()
self.metaData = {}
self.opts = {'pen': fn.mkPen('w'), 'shadowPen': None, 'fillLevel': None, 'brush': None, 'stepMode': False, 'name': None, 'antialias': getConfigOption('antialias'), 'connect': 'all', 'mouseWidth': 8}
self.setClickable(kargs.get('clickable', False))
self.setData(*args, **kargs)
|
'Sets whether the item responds to mouse clicks.
The *width* argument specifies the width in pixels orthogonal to the
curve that will respond to a mouse click.'
| def setClickable(self, s, width=None):
| self.clickable = s
if (width is not None):
self.opts['mouseWidth'] = width
self._mouseShape = None
self._boundingRect = None
|
'Set the pen used to draw the curve.'
| def setPen(self, *args, **kargs):
| self.opts['pen'] = fn.mkPen(*args, **kargs)
self.invalidateBounds()
self.update()
|
'Set the shadow pen used to draw behind tyhe primary pen.
This pen must have a larger width than the primary
pen to be visible.'
| def setShadowPen(self, *args, **kargs):
| self.opts['shadowPen'] = fn.mkPen(*args, **kargs)
self.invalidateBounds()
self.update()
|
'Set the brush used when filling the area under the curve'
| def setBrush(self, *args, **kargs):
| self.opts['brush'] = fn.mkBrush(*args, **kargs)
self.invalidateBounds()
self.update()
|
'Set the level filled to when filling under the curve'
| def setFillLevel(self, level):
| self.opts['fillLevel'] = level
self.fillPath = None
self.invalidateBounds()
self.update()
|
'**Arguments:**
x, y (numpy arrays) Data to show
pen Pen to use when drawing. Any single argument accepted by
:func:`mkPen <pyqtgraph.mkPen>` is allowed.
shadowPen Pen for drawing behind the primary pen. Usually this
is used to emphasize the curve by providing a
high-contrast border. Any single argument accepted by
:func:`mkPen <pyqtgraph.mkPen>` is allowed.
fillLevel (float or None) Fill the area \'under\' the curve to
*fillLevel*
brush QBrush to use when filling. Any single argument accepted
by :func:`mkBrush <pyqtgraph.mkBrush>` is allowed.
antialias (bool) Whether to use antialiasing when drawing. This
is disabled by default because it decreases performance.
stepMode If True, two orthogonal lines are drawn for each sample
as steps. This is commonly used when drawing histograms.
Note that in this case, len(x) == len(y) + 1
connect Argument specifying how vertexes should be connected
by line segments. Default is "all", indicating full
connection. "pairs" causes only even-numbered segments
to be drawn. "finite" causes segments to be omitted if
they are attached to nan or inf values. For any other
connectivity, specify an array of boolean values.
If non-keyword arguments are used, they will be interpreted as
setData(y) for a single argument and setData(x, y) for two
arguments.'
| def setData(self, *args, **kargs):
| self.updateData(*args, **kargs)
|
'Return a QPainterPath representing the clickable shape of the curve'
| def mouseShape(self):
| if (self._mouseShape is None):
view = self.getViewBox()
if (view is None):
return QtGui.QPainterPath()
stroker = QtGui.QPainterPathStroker()
path = self.getPath()
path = self.mapToItem(view, path)
stroker.setWidth(self.opts['mouseWidth'])
mousePath = stroker.createStroke(path)
self._mouseShape = self.mapFromItem(view, mousePath)
return self._mouseShape
|
'Defines labels to appear next to the color scale. Accepts a dict of {text: value} pairs'
| def setLabels(self, l):
| self.labels = l
self.update()
|
'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())'
| def __init__(self, parent=None, name='ImageView', view=None, imageItem=None, *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 (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()
for fn in ['addItem', 'removeItem']:
setattr(self, fn, getattr(self.view, fn))
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.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()
|
'Set the image to be displayed in the widget.
**Arguments:**
img (numpy array) the image to be displayed. See :func:`ImageItem.setImage` and
*notes* below.
xvals (numpy array) 1D array of z-axis values corresponding to the third axis
in a 3D image. For video, this array should contain the time of each frame.
autoRange (bool) whether to scale/pan the view to fit the image.
autoLevels (bool) whether to update the white/black levels to fit the image.
levels (min, max); the white and black level values to use.
axes Dictionary indicating the interpretation for each axis.
This is only needed to override the default guess. Format is::
{\'t\':0, \'x\':1, \'y\':2, \'c\':3};
pos Change the position of the displayed image
scale Change the scale of the displayed image
transform Set the transform of the displayed image. This option overrides *pos*
and *scale*.
autoHistogramRange If True, the histogram y-range is automatically scaled to fit the
image data.
**Notes:**
For backward compatibility, image data is assumed to be in column-major order (column, row).
However, most image data is stored in row-major order (row, column) and will need to be
transposed before calling setImage()::
imageview.setImage(imagedata.T)
This requirement can be changed by the ``imageAxisOrder``
:ref:`global configuration option <apiref_config>`.'
| def setImage(self, img, autoRange=True, autoLevels=True, levels=None, axes=None, xvals=None, pos=None, scale=None, transform=None, autoHistogramRange=True):
| profiler = debug.Profiler()
if (hasattr(img, 'implements') and img.implements('MetaArray')):
img = img.asarray()
if (not isinstance(img, np.ndarray)):
required = ['dtype', 'max', 'min', 'ndim', 'shape', 'size']
if (not all([hasattr(img, attr) for attr in required])):
raise TypeError(('Image must be NumPy array or any object that provides compatible attributes/methods:\n %s' % str(required)))
self.image = img
self.imageDisp = None
profiler()
if (axes is None):
(x, y) = ((0, 1) if (self.imageItem.axisOrder == 'col-major') else (1, 0))
if (img.ndim == 2):
self.axes = {'t': None, 'x': x, 'y': y, 'c': None}
elif (img.ndim == 3):
if (img.shape[2] <= 4):
self.axes = {'t': None, 'x': x, 'y': y, 'c': 2}
else:
self.axes = {'t': 0, 'x': (x + 1), 'y': (y + 1), 'c': None}
elif (img.ndim == 4):
self.axes = {'t': 0, 'x': (x + 1), 'y': (y + 1), 'c': 3}
else:
raise Exception(('Can not interpret image with dimensions %s' % str(img.shape)))
elif isinstance(axes, dict):
self.axes = axes.copy()
elif (isinstance(axes, list) or isinstance(axes, tuple)):
self.axes = {}
for i in range(len(axes)):
self.axes[axes[i]] = i
else:
raise Exception(("Can not interpret axis specification %s. Must be like {'t': 2, 'x': 0, 'y': 1} or ('t', 'x', 'y', 'c')" % str(axes)))
for x in ['t', 'x', 'y', 'c']:
self.axes[x] = self.axes.get(x, None)
axes = self.axes
if (xvals is not None):
self.tVals = xvals
elif (axes['t'] is not None):
if hasattr(img, 'xvals'):
try:
self.tVals = img.xvals(axes['t'])
except:
self.tVals = np.arange(img.shape[axes['t']])
else:
self.tVals = np.arange(img.shape[axes['t']])
profiler()
self.currentIndex = 0
self.updateImage(autoHistogramRange=autoHistogramRange)
if ((levels is None) and autoLevels):
self.autoLevels()
if (levels is not None):
self.setLevels(*levels)
if self.ui.roiBtn.isChecked():
self.roiChanged()
profiler()
if (self.axes['t'] is not None):
self.ui.roiPlot.setXRange(self.tVals.min(), self.tVals.max())
self.timeLine.setValue(0)
if (len(self.tVals) > 1):
start = self.tVals.min()
stop = (self.tVals.max() + (abs((self.tVals[(-1)] - self.tVals[0])) * 0.02))
elif (len(self.tVals) == 1):
start = (self.tVals[0] - 0.5)
stop = (self.tVals[0] + 0.5)
else:
start = 0
stop = 1
for s in [self.timeLine, self.normRgn]:
s.setBounds([start, stop])
profiler()
self.imageItem.resetTransform()
if (scale is not None):
self.imageItem.scale(*scale)
if (pos is not None):
self.imageItem.setPos(*pos)
if (transform is not None):
self.imageItem.setTransform(transform)
profiler()
if autoRange:
self.autoRange()
self.roiClicked()
profiler()
|
'Begin automatically stepping frames forward at the given rate (in fps).
This can also be accessed by pressing the spacebar.'
| def play(self, rate):
| self.playRate = rate
if (rate == 0):
self.playTimer.stop()
return
self.lastPlayTime = ptime.time()
if (not self.playTimer.isActive()):
self.playTimer.start(16)
|
'Set the min/max intensity levels automatically to match the image data.'
| def autoLevels(self):
| self.setLevels(self.levelMin, self.levelMax)
|
'Set the min/max (bright and dark) levels.'
| def setLevels(self, min, max):
| self.ui.histogram.setLevels(min, max)
|
'Auto scale and pan the view around the image such that the image fills the view.'
| def autoRange(self):
| image = self.getProcessedImage()
self.view.autoRange()
|
'Returns the image data after it has been processed by any normalization options in use.
This method also sets the attributes self.levelMin and self.levelMax
to indicate the range of data in the image.'
| def getProcessedImage(self):
| if (self.imageDisp is None):
image = self.normalize(self.image)
self.imageDisp = image
(self.levelMin, self.levelMax) = list(map(float, self.quickMinMax(self.imageDisp)))
return self.imageDisp
|
'Closes the widget nicely, making sure to clear the graphics scene and release memory.'
| def close(self):
| self.ui.roiPlot.close()
self.ui.graphicsView.close()
self.scene.clear()
del self.image
del self.imageDisp
super(ImageView, self).close()
self.setParent(None)
|
'Set the currently displayed frame index.'
| def setCurrentIndex(self, ind):
| self.currentIndex = np.clip(ind, 0, (self.getProcessedImage().shape[self.axes['t']] - 1))
self.updateImage()
self.ignoreTimeLine = True
self.timeLine.setValue(self.tVals[self.currentIndex])
self.ignoreTimeLine = False
|
'Move video frame ahead n frames (may be negative)'
| def jumpFrames(self, n):
| if (self.axes['t'] is not None):
self.setCurrentIndex((self.currentIndex + n))
|
'Estimate the min/max values of *data* by subsampling.'
| def quickMinMax(self, data):
| while (data.size > 1000000.0):
ax = np.argmax(data.shape)
sl = ([slice(None)] * data.ndim)
sl[ax] = slice(None, None, 2)
data = data[sl]
return (nanmin(data), nanmax(data))
|
'Process *image* using the normalization options configured in the
control panel.
This can be repurposed to process any data through the same filter.'
| def normalize(self, image):
| if self.ui.normOffRadio.isChecked():
return image
div = self.ui.normDivideRadio.isChecked()
norm = image.view(np.ndarray).copy()
if div:
norm = norm.astype(np.float32)
if (self.ui.normTimeRangeCheck.isChecked() and (image.ndim == 3)):
(sind, start) = self.timeIndex(self.normRgn.lines[0])
(eind, end) = self.timeIndex(self.normRgn.lines[1])
n = image[sind:(eind + 1)].mean(axis=0)
n.shape = ((1,) + n.shape)
if div:
norm /= n
else:
norm -= n
if (self.ui.normFrameCheck.isChecked() and (image.ndim == 3)):
n = image.mean(axis=1).mean(axis=1)
n.shape = (n.shape + (1, 1))
if div:
norm /= n
else:
norm -= n
if (self.ui.normROICheck.isChecked() and (image.ndim == 3)):
n = self.normRoi.getArrayRegion(norm, self.imageItem, (1, 2)).mean(axis=1).mean(axis=1)
n = n[:, np.newaxis, np.newaxis]
if div:
norm /= n
else:
norm -= n
return norm
|
'Return the ViewBox (or other compatible object) which displays the ImageItem'
| def getView(self):
| return self.view
|
'Return the ImageItem for this ImageView.'
| def getImageItem(self):
| return self.imageItem
|
'Return the ROI PlotWidget for this ImageView'
| def getRoiPlot(self):
| return self.ui.roiPlot
|
'Return the HistogramLUTWidget for this ImageView'
| def getHistogramWidget(self):
| return self.ui.histogram
|
'Export data from the ImageView to a file, or to a stack of files if
the data is 3D. Saving an image stack will result in index numbers
being added to the file name. Images are saved as they would appear
onscreen, with levels and lookup table applied.'
| def export(self, fileName):
| img = self.getProcessedImage()
if self.hasTimeAxis():
(base, ext) = os.path.splitext(fileName)
fmt = ('%%s%%0%dd%%s' % int((np.log10(img.shape[0]) + 1)))
for i in range(img.shape[0]):
self.imageItem.setImage(img[i], autoLevels=False)
self.imageItem.save((fmt % (base, i, ext)))
self.updateImage()
else:
self.imageItem.save(fileName)
|
'Set the color map.
**Arguments**
colormap (A ColorMap() instance) The ColorMap to use for coloring
images.'
| def setColorMap(self, colormap):
| self.ui.histogram.gradient.setColorMap(colormap)
|
'Set one of the gradients defined in :class:`GradientEditorItem <pyqtgraph.graphicsItems.GradientEditorItem>`.
Currently available gradients are:'
| @addGradientListToDocstring()
def setPredefinedGradient(self, name):
| self.ui.histogram.gradient.loadPreset(name)
|
'**Arguments:**
namespace dictionary containing the initial variables present in the default namespace
historyFile optional file for storing command history
text initial text to display in the console window
editor optional string for invoking code editor (called when stack trace entries are
double-clicked). May contain {fileName} and {lineNum} format keys. Example::
editorCommand --loadfile {fileName} --gotoline {lineNum}'
| def __init__(self, parent=None, namespace=None, historyFile=None, text=None, editor=None):
| QtGui.QWidget.__init__(self, parent)
if (namespace is None):
namespace = {}
namespace['__console__'] = self
self.localNamespace = namespace
self.editor = editor
self.multiline = None
self.inCmd = False
self.ui = template.Ui_Form()
self.ui.setupUi(self)
self.output = self.ui.output
self.input = self.ui.input
self.input.setFocus()
if (text is not None):
self.output.setPlainText(text)
self.historyFile = historyFile
history = self.loadHistory()
if (history is not None):
self.input.history = ([''] + history)
self.ui.historyList.addItems(history[::(-1)])
self.ui.historyList.hide()
self.ui.exceptionGroup.hide()
self.input.sigExecuteCmd.connect(self.runCmd)
self.ui.historyBtn.toggled.connect(self.ui.historyList.setVisible)
self.ui.historyList.itemClicked.connect(self.cmdSelected)
self.ui.historyList.itemDoubleClicked.connect(self.cmdDblClicked)
self.ui.exceptionBtn.toggled.connect(self.ui.exceptionGroup.setVisible)
self.ui.catchAllExceptionsBtn.toggled.connect(self.catchAllExceptions)
self.ui.catchNextExceptionBtn.toggled.connect(self.catchNextException)
self.ui.clearExceptionBtn.clicked.connect(self.clearExceptionClicked)
self.ui.exceptionStackList.itemClicked.connect(self.stackItemClicked)
self.ui.exceptionStackList.itemDoubleClicked.connect(self.stackItemDblClicked)
self.ui.onlyUncaughtCheck.toggled.connect(self.updateSysTrace)
self.currentTraceback = None
|
'Return the list of previously-invoked command strings (or None).'
| def loadHistory(self):
| if (self.historyFile is not None):
return pickle.load(open(self.historyFile, 'rb'))
|
'Store the list of previously-invoked command strings.'
| def saveHistory(self, history):
| if (self.historyFile is not None):
pickle.dump(open(self.historyFile, 'wb'), history)
|
'Display the current exception and stack.'
| def displayException(self):
| tb = traceback.format_exc()
lines = []
indent = 4
prefix = ''
for l in tb.split('\n'):
lines.append((((' ' * indent) + prefix) + l))
self.write('\n'.join(lines))
self.exceptionHandler(*sys.exc_info())
|
'If True, the console will catch all unhandled exceptions and display the stack
trace. Each exception caught clears the last.'
| def catchAllExceptions(self, catch=True):
| self.ui.catchAllExceptionsBtn.setChecked(catch)
if catch:
self.ui.catchNextExceptionBtn.setChecked(False)
self.enableExceptionHandling()
self.ui.exceptionBtn.setChecked(True)
else:
self.disableExceptionHandling()
|
'If True, the console will catch the next unhandled exception and display the stack
trace.'
| def catchNextException(self, catch=True):
| self.ui.catchNextExceptionBtn.setChecked(catch)
if catch:
self.ui.catchAllExceptionsBtn.setChecked(False)
self.enableExceptionHandling()
self.ui.exceptionBtn.setChecked(True)
else:
self.disableExceptionHandling()
|
'Initialize WidgetGroup, adding specified widgets into this group.
widgetList can be:
- a list of widget specifications (widget, [name], [scale])
- a dict of name: widget pairs
- any QObject, and all compatible child widgets will be added recursively.
The \'scale\' parameter for each widget allows QSpinBox to display a different value than the value recorded
in the group state (for example, the program may set a spin box value to 100e-6 and have it displayed as 100 to the user)'
| def __init__(self, widgetList=None):
| QtCore.QObject.__init__(self)
self.widgetList = weakref.WeakKeyDictionary()
self.scales = weakref.WeakKeyDictionary()
self.cache = {}
self.uncachedWidgets = weakref.WeakKeyDictionary()
if isinstance(widgetList, QtCore.QObject):
self.autoAdd(widgetList)
elif isinstance(widgetList, list):
for w in widgetList:
self.addWidget(*w)
elif isinstance(widgetList, dict):
for (name, w) in widgetList.items():
self.addWidget(w, name)
elif (widgetList is None):
return
else:
raise Exception(('Wrong argument type %s' % type(widgetList)))
|
'Return true if we should automatically search the children of this object for more.'
| def checkForChildren(self, obj):
| iface = self.interface(obj)
return ((len(iface) > 3) and iface[3])
|
'Ask the user to decide whether an image test passes or fails.
This method displays the test image, reference image, and the difference
between the two. It then blocks until the user selects the test output
by clicking a pass/fail button or typing p/f. If the user fails the test,
then an exception is raised.'
| def test(self, im1, im2, message):
| self.show()
if (im2 is None):
message += ('\nImage1: %s %s Image2: [no standard]' % (im1.shape, im1.dtype))
im2 = np.zeros((1, 1, 3), dtype=np.ubyte)
else:
message += ('\nImage1: %s %s Image2: %s %s' % (im1.shape, im1.dtype, im2.shape, im2.dtype))
self.label.setText(message)
self.views[0].image.setImage(im1)
self.views[1].image.setImage(im2)
diff = makeDiffImage(im1, im2)
self.views[2].image.setImage(diff)
self.views[0].autoRange()
while True:
QtGui.QApplication.processEvents()
lastKey = self.lastKey
self.lastKey = None
if ((lastKey in ('f', 'esc')) or (not self.isVisible())):
raise Exception('User rejected test result.')
elif (lastKey == 'p'):
break
time.sleep(0.03)
for v in self.views:
v.image.setImage(np.zeros((1, 1, 3), dtype=np.ubyte))
|
'Extends QMatrix4x4.map() to allow mapping (3, ...) arrays of coordinates'
| def map(self, obj):
| if (isinstance(obj, np.ndarray) and (obj.ndim >= 2) and (obj.shape[0] in (2, 3))):
return fn.transformCoordinates(self, obj)
else:
return QtGui.QMatrix4x4.map(self, obj)
|
'Set the input values of the flowchart. This will automatically propagate
the new values throughout the flowchart, (possibly) causing the output to change.'
| def setInput(self, **args):
| self.inputWasSet = True
self.inputNode.setOutput(**args)
|
'Return a dict of the values on the Flowchart\'s output terminals.'
| def output(self):
| return self.outputNode.inputValues()
|
'If the terminal belongs to the external Node, return the corresponding internal terminal'
| def internalTerminal(self, term):
| if (term.node() is self):
if term.isInput():
return self.inputNode[term.name()]
else:
return self.outputNode[term.name()]
else:
return term
|
'Connect two terminals together within this flowchart.'
| def connectTerminals(self, term1, term2):
| term1 = self.internalTerminal(term1)
term2 = self.internalTerminal(term2)
term1.connectTo(term2)
|
'Process data through the flowchart, returning the output.
Keyword arguments must be the names of input terminals.
The return value is a dict with one key per output terminal.'
| def process(self, **args):
| data = {}
order = self.processOrder()
for (n, t) in self.inputNode.outputs().items():
if (n in args):
data[t] = args[n]
ret = {}
for (c, arg) in order:
if (c == 'p'):
node = arg
if (node is self.inputNode):
continue
outs = list(node.outputs().values())
ins = list(node.inputs().values())
args = {}
for inp in ins:
inputs = inp.inputTerminals()
if (len(inputs) == 0):
continue
if inp.isMultiValue():
args[inp.name()] = dict([(i, data[i]) for i in inputs if (i in data)])
else:
args[inp.name()] = data[inputs[0]]
if (node is self.outputNode):
ret = args
else:
try:
if node.isBypassed():
result = node.processBypassed(args)
else:
result = node.process(display=False, **args)
except:
print ('Error processing node %s. Args are: %s' % (str(node), str(args)))
raise
for out in outs:
try:
data[out] = result[out.name()]
except KeyError:
pass
elif (c == 'd'):
if (arg in data):
del data[arg]
return ret
|
'Return the order of operations required to process this chart.
The order returned should look like [(\'p\', node1), (\'p\', node2), (\'d\', terminal1), ...]
where each tuple specifies either (p)rocess this node or (d)elete the result from this terminal'
| def processOrder(self):
| deps = {}
tdeps = {}
for (name, node) in self._nodes.items():
deps[node] = node.dependentNodes()
for t in node.outputs().values():
tdeps[t] = t.dependentNodes()
order = fn.toposort(deps)
ops = [('p', n) for n in order]
dels = []
for (t, nodes) in tdeps.items():
lastInd = 0
lastNode = None
for n in nodes:
if (n is self):
lastInd = None
break
else:
try:
ind = order.index(n)
except ValueError:
continue
if ((lastNode is None) or (ind > lastInd)):
lastNode = n
lastInd = ind
if (lastInd is not None):
dels.append(((lastInd + 1), t))
dels.sort(key=(lambda a: a[0]), reverse=True)
for (i, t) in dels:
ops.insert(i, ('d', t))
return ops
|
'Triggered when a node\'s output values have changed. (NOT called during process())
Propagates new data forward through network.'
| def nodeOutputChanged(self, startNode):
| if self.processing:
return
self.processing = True
try:
deps = {}
for (name, node) in self._nodes.items():
deps[node] = []
for t in node.outputs().values():
deps[node].extend(t.dependentNodes())
order = fn.toposort(deps, nodes=[startNode])
order.reverse()
terms = set(startNode.outputs().values())
for node in order[1:]:
update = False
for term in list(node.inputs().values()):
deps = list(term.connections().keys())
for d in deps:
if (d in terms):
update |= True
term.inputChanged(d, process=False)
if update:
node.update()
terms |= set(node.outputs().values())
finally:
self.processing = False
if self.inputWasSet:
self.inputWasSet = False
else:
self.sigStateChanged.emit()
|
'Return the graphicsItem which displays the internals of this flowchart.
(graphicsItem() still returns the external-view item)'
| def chartGraphicsItem(self):
| return self.viewBox
|
'**Arguments:**
name The name of this specific node instance. It can be any
string, but must be unique within a flowchart. Usually,
we simply let the flowchart decide on a name when calling
Flowchart.addNode(...)
terminals Dict-of-dicts specifying the terminals present on this Node.
Terminal specifications look like::
\'inputTerminalName\': {\'io\': \'in\'}
\'outputTerminalName\': {\'io\': \'out\'}
There are a number of optional parameters for terminals:
multi, pos, renamable, removable, multiable, bypass. See
the Terminal class for more information.
allowAddInput bool; whether the user is allowed to add inputs by the
context menu.
allowAddOutput bool; whether the user is allowed to add outputs by the
context menu.
allowRemove bool; whether the user is allowed to remove this node by the
context menu.'
| def __init__(self, name, terminals=None, allowAddInput=False, allowAddOutput=False, allowRemove=True):
| QtCore.QObject.__init__(self)
self._name = name
self._bypass = False
self.bypassButton = None
self._graphicsItem = None
self.terminals = OrderedDict()
self._inputs = OrderedDict()
self._outputs = OrderedDict()
self._allowAddInput = allowAddInput
self._allowAddOutput = allowAddOutput
self._allowRemove = allowRemove
self.exception = None
if (terminals is None):
return
for (name, opts) in terminals.items():
self.addTerminal(name, **opts)
|
'Return an unused terminal name'
| def nextTerminalName(self, name):
| name2 = name
i = 1
while (name2 in self.terminals):
name2 = ('%s.%d' % (name, i))
i += 1
return name2
|
'Add a new input terminal to this Node with the given name. Extra
keyword arguments are passed to Terminal.__init__.
This is a convenience function that just calls addTerminal(io=\'in\', ...)'
| def addInput(self, name='Input', **args):
| return self.addTerminal(name, io='in', **args)
|
'Add a new output terminal to this Node with the given name. Extra
keyword arguments are passed to Terminal.__init__.
This is a convenience function that just calls addTerminal(io=\'out\', ...)'
| def addOutput(self, name='Output', **args):
| return self.addTerminal(name, io='out', **args)
|
'Remove the specified terminal from this Node. May specify either the
terminal\'s name or the terminal itself.
Causes sigTerminalRemoved to be emitted.'
| def removeTerminal(self, term):
| if isinstance(term, Terminal):
name = term.name()
else:
name = term
term = self.terminals[name]
term.close()
del self.terminals[name]
if (name in self._inputs):
del self._inputs[name]
if (name in self._outputs):
del self._outputs[name]
self.graphicsItem().updateTerminals()
self.sigTerminalRemoved.emit(self, term)
|
'Called after a terminal has been renamed
Causes sigTerminalRenamed to be emitted.'
| def terminalRenamed(self, term, oldName):
| newName = term.name()
for d in [self.terminals, self._inputs, self._outputs]:
if (oldName not in d):
continue
d[newName] = d[oldName]
del d[oldName]
self.graphicsItem().updateTerminals()
self.sigTerminalRenamed.emit(term, oldName)
|
'Add a new terminal to this Node with the given name. Extra
keyword arguments are passed to Terminal.__init__.
Causes sigTerminalAdded to be emitted.'
| def addTerminal(self, name, **opts):
| name = self.nextTerminalName(name)
term = Terminal(self, name, **opts)
self.terminals[name] = term
if term.isInput():
self._inputs[name] = term
elif term.isOutput():
self._outputs[name] = term
self.graphicsItem().updateTerminals()
self.sigTerminalAdded.emit(self, term)
return term
|
'Return dict of all input terminals.
Warning: do not modify.'
| def inputs(self):
| return self._inputs
|
'Return dict of all output terminals.
Warning: do not modify.'
| def outputs(self):
| return self._outputs
|
'Process data through this node. This method is called any time the flowchart
wants the node to process data. It will be called with one keyword argument
corresponding to each input terminal, and must return a dict mapping the name
of each output terminal to its new value.
This method is also called with a \'display\' keyword argument, which indicates
whether the node should update its display (if it implements any) while processing
this data. This is primarily used to disable expensive display operations
during batch processing.'
| def process(self, **kargs):
| return {}
|
'Return the GraphicsItem for this node. Subclasses may re-implement
this method to customize their appearance in the flowchart.'
| def graphicsItem(self):
| if (self._graphicsItem is None):
self._graphicsItem = NodeGraphicsItem(self)
return self._graphicsItem
|
'Return the terminal with the given name'
| def __getattr__(self, attr):
| if (attr not in self.terminals):
raise AttributeError(attr)
else:
import traceback
traceback.print_stack()
print "Warning: use of node.terminalName is deprecated; use node['terminalName'] instead."
return self.terminals[attr]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.