desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Insert a new child at pos.
If pos is a Parameter, then insert at the position of that Parameter.
If child is a dict, then a parameter is constructed using
:func:`Parameter.create <pyqtgraph.parametertree.Parameter.create>`.
By default, the child\'s \'autoIncrementName\' option determines whether
the name will be adjusted to avoid prior name collisions. This
behavior may be overridden by specifying the *autoIncrementName*
argument. This argument was added in version 0.9.9.'
| def insertChild(self, pos, child, autoIncrementName=None):
| if isinstance(child, dict):
child = Parameter.create(**child)
name = child.name()
if ((name in self.names) and (child is not self.names[name])):
if ((autoIncrementName is True) or ((autoIncrementName is None) and child.opts.get('autoIncrementName', False))):
name = self.incrementName(name)
child.setName(name)
else:
raise Exception(('Already have child named %s' % str(name)))
if isinstance(pos, Parameter):
pos = self.childs.index(pos)
with self.treeChangeBlocker():
if (child.parent() is not None):
child.remove()
self.names[name] = child
self.childs.insert(pos, child)
child.parentChanged(self)
self.sigChildAdded.emit(self, child, pos)
child.sigTreeStateChanged.connect(self.treeStateChanged)
return child
|
'Remove a child parameter.'
| def removeChild(self, child):
| name = child.name()
if ((name not in self.names) or (self.names[name] is not child)):
raise Exception(("Parameter %s is not my child; can't remove." % str(child)))
del self.names[name]
self.childs.pop(self.childs.index(child))
child.parentChanged(None)
self.sigChildRemoved.emit(self, child)
try:
child.sigTreeStateChanged.disconnect(self.treeStateChanged)
except (TypeError, RuntimeError):
pass
|
'Remove all child parameters.'
| def clearChildren(self):
| for ch in self.childs[:]:
self.removeChild(ch)
|
'Return a list of this parameter\'s children.
Warning: this overrides QObject.children'
| def children(self):
| return self.childs[:]
|
'Return True if this Parameter has children.'
| def hasChildren(self):
| return (len(self.childs) > 0)
|
'This method is called when the parameter\'s parent has changed.
It may be useful to extend this method in subclasses.'
| def parentChanged(self, parent):
| self._parent = parent
self.sigParentChanged.emit(self, parent)
|
'Return the parent of this parameter.'
| def parent(self):
| return self._parent
|
'Remove this parameter from its parent\'s child list'
| def remove(self):
| parent = self.parent()
if (parent is None):
raise Exception('Cannot remove; no parent.')
parent.removeChild(self)
self.sigRemoved.emit(self)
|
'Get the value of a child parameter. The name may also be a tuple giving
the path to a sub-parameter::
value = param[(\'child\', \'grandchild\')]'
| def __getitem__(self, names):
| if (not isinstance(names, tuple)):
names = (names,)
return self.param(*names).value()
|
'Set the value of a child parameter. The name may also be a tuple giving
the path to a sub-parameter::
param[(\'child\', \'grandchild\')] = value'
| def __setitem__(self, names, value):
| if isinstance(names, basestring):
names = (names,)
return self.param(*names).setValue(value)
|
'Return a child parameter.
Accepts the name of the child or a tuple (path, to, child)
Added in version 0.9.9. Ealier versions used the \'param\' method, which is still
implemented for backward compatibility.'
| def child(self, *names):
| try:
param = self.names[names[0]]
except KeyError:
raise Exception(('Parameter %s has no child named %s' % (self.name(), names[0])))
if (len(names) > 1):
return param.param(*names[1:])
else:
return param
|
'Hide this parameter. It and its children will no longer be visible in any ParameterTree
widgets it is connected to.'
| def hide(self):
| self.show(False)
|
'Show this parameter.'
| def show(self, s=True):
| self.opts['visible'] = s
self.sigOptionsChanged.emit(self, {'visible': s})
|
'Return an object that can be used to temporarily block and accumulate
sigTreeStateChanged signals. This is meant to be used when numerous changes are
about to be made to the tree and only one change signal should be
emitted at the end.
Example::
with param.treeChangeBlocker():
param.addChild(...)
param.removeChild(...)
param.setValue(...)'
| def treeChangeBlocker(self):
| return SignalBlocker(self.blockTreeChangeSignal, self.unblockTreeChangeSignal)
|
'Used to temporarily block and accumulate tree change signals.
*You must remember to unblock*, so it is advisable to use treeChangeBlocker() instead.'
| def blockTreeChangeSignal(self):
| self.blockTreeChangeEmit += 1
|
'Unblocks enission of sigTreeStateChanged and flushes the changes out through a single signal.'
| def unblockTreeChangeSignal(self):
| self.blockTreeChangeEmit -= 1
self.emitTreeChanges()
|
'Called when the state of any sub-parameter has changed.
**Arguments:**
param The immediate child whose tree state has changed.
note that the change may have originated from a grandchild.
changes List of tuples describing all changes that have been made
in this event: (param, changeDescr, data)
This function can be extended to react to tree state changes.'
| def treeStateChanged(self, param, changes):
| self.treeStateChanges.extend(changes)
self.emitTreeChanges()
|
'Return a single widget that should be placed in the second tree column.
The widget must be given three attributes:
sigChanged a signal that is emitted when the widget\'s value is changed
value a function that returns the value
setValue a function that sets the value
This is a good function to override in subclasses.'
| def makeWidget(self):
| opts = self.param.opts
t = opts['type']
if (t in ('int', 'float')):
defs = {'value': 0, 'min': None, 'max': None, 'step': 1.0, 'dec': False, 'siPrefix': False, 'suffix': '', 'decimals': 3}
if (t == 'int'):
defs['int'] = True
defs['minStep'] = 1.0
for k in defs:
if (k in opts):
defs[k] = opts[k]
if ('limits' in opts):
(defs['min'], defs['max']) = opts['limits']
w = SpinBox()
w.setOpts(**defs)
w.sigChanged = w.sigValueChanged
w.sigChanging = w.sigValueChanging
elif (t == 'bool'):
w = QtGui.QCheckBox()
w.sigChanged = w.toggled
w.value = w.isChecked
w.setValue = w.setChecked
w.setEnabled((not opts.get('readonly', False)))
self.hideWidget = False
elif (t == 'str'):
w = QtGui.QLineEdit()
w.setStyleSheet('border: 0px')
w.sigChanged = w.editingFinished
w.value = (lambda : asUnicode(w.text()))
w.setValue = (lambda v: w.setText(asUnicode(v)))
w.sigChanging = w.textChanged
elif (t == 'color'):
w = ColorButton()
w.sigChanged = w.sigColorChanged
w.sigChanging = w.sigColorChanging
w.value = w.color
w.setValue = w.setColor
self.hideWidget = False
w.setFlat(True)
w.setEnabled((not opts.get('readonly', False)))
elif (t == 'colormap'):
from ..widgets.GradientWidget import GradientWidget
w = GradientWidget(orientation='bottom')
w.sigChanged = w.sigGradientChangeFinished
w.sigChanging = w.sigGradientChanged
w.value = w.colorMap
w.setValue = w.setColorMap
self.hideWidget = False
else:
raise Exception(("Unknown type '%s'" % asUnicode(t)))
return w
|
'Update the display label to reflect the value of the parameter.'
| def updateDisplayLabel(self, value=None):
| if (value is None):
value = self.param.value()
opts = self.param.opts
if isinstance(self.widget, QtGui.QAbstractSpinBox):
text = asUnicode(self.widget.lineEdit().text())
elif isinstance(self.widget, QtGui.QComboBox):
text = self.widget.currentText()
else:
text = asUnicode(value)
self.displayLabel.setText(text)
|
'Called when the widget\'s value is changing, but not finalized.
For example: editing text before pressing enter or changing focus.'
| def widgetValueChanging(self, *args):
| self.param.sigValueChanging.emit(self.param, args[(-1)])
|
'Called when this item has been selected (sel=True) OR deselected (sel=False)'
| def selected(self, sel):
| ParameterItem.selected(self, sel)
if (self.widget is None):
return
if (sel and self.param.writable()):
self.showEditor()
elif self.hideWidget:
self.hideEditor()
|
'Called when the parameter\'s limits have changed'
| def limitsChanged(self, param, limits):
| ParameterItem.limitsChanged(self, param, limits)
t = self.param.opts['type']
if ((t == 'int') or (t == 'float')):
self.widget.setOpts(bounds=limits)
else:
return
|
'Called when this item is added or removed from a tree.'
| def treeWidgetChanged(self):
| ParameterItem.treeWidgetChanged(self)
if (self.widget is not None):
tree = self.treeWidget()
if (tree is None):
return
tree.setItemWidget(self, 1, self.layoutWidget)
self.displayLabel.hide()
self.selected(False)
|
'Called when any options are changed that are not
name, value, default, or limits'
| def optsChanged(self, param, opts):
| ParameterItem.optsChanged(self, param, opts)
if ('readonly' in opts):
self.updateDefaultBtn()
if isinstance(self.widget, (QtGui.QCheckBox, ColorButton)):
self.widget.setEnabled((not opts['readonly']))
if isinstance(self.widget, SpinBox):
sbOpts = {}
if (('units' in opts) and ('suffix' not in opts)):
sbOpts['suffix'] = opts['units']
for (k, v) in opts.items():
if (k in self.widget.opts):
sbOpts[k] = v
self.widget.setOpts(**sbOpts)
self.updateDisplayLabel()
|
'Called when "add new" button is clicked
The parameter MUST have an \'addNew\' method defined.'
| def addClicked(self):
| self.param.addNew()
|
'Called when "add new" combo is changed
The parameter MUST have an \'addNew\' method defined.'
| def addChanged(self):
| if (self.addWidget.currentIndex() == 0):
return
typ = asUnicode(self.addWidget.currentText())
self.param.addNew(typ)
self.addWidget.setCurrentIndex(0)
|
'This method is called when the user has requested to add a new item to the group.'
| def addNew(self, typ=None):
| raise Exception('Must override this function in subclass.')
|
'Change the list of options available for the user to add to the group.'
| def setAddList(self, vals):
| self.setOpts(addList=vals)
|
'Reset all variables in the solver to their default state.'
| def reset(self):
| self._currentGets.clear()
for k in self.defaultState:
self._vars[k] = self.defaultState[k][:]
|
'Set the value of a state variable.
If None is given for the value, then the constraint will also be set to None.
If a tuple is given for a scalar variable, then the tuple is used as a range constraint instead of a value.
Otherwise, the constraint is set to \'fixed\'.'
| def __setattr__(self, name, value):
| if (name in self._vars):
if (value is None):
self.set(name, value, None)
elif (isinstance(value, tuple) and (self._vars[name][1] is not np.ndarray)):
self.set(name, None, value)
else:
self.set(name, value, 'fixed')
elif hasattr(self, name):
object.__setattr__(self, name, value)
else:
raise AttributeError(name)
|
'Return the value for parameter *name*.
If the value has not been specified, then attempt to compute it from
other interacting parameters.
If no value can be determined, then raise RuntimeError.'
| def get(self, name):
| if (name in self._currentGets):
raise RuntimeError(("Cyclic dependency while calculating '%s'." % name))
self._currentGets.add(name)
try:
v = self._vars[name][0]
if (v is None):
cfunc = getattr(self, ('_' + name), None)
if (cfunc is None):
v = None
else:
v = cfunc()
if (v is None):
raise RuntimeError(("Parameter '%s' is not specified." % name))
v = self.set(name, v)
finally:
self._currentGets.remove(name)
return v
|
'Set a variable *name* to *value*. The actual set value is returned (in
some cases, the value may be cast into another type).
If *value* is None, then the value is left to be determined in the
future. At any time, the value may be re-assigned arbitrarily unless
a constraint is given.
If *constraint* is True (the default), then supplying a value that
violates a previously specified constraint will raise an exception.
If *constraint* is \'fixed\', then the value is set (if provided) and
the variable will not be updated automatically in the future.
If *constraint* is a tuple, then the value is constrained to be within the
given (min, max). Either constraint may be None to disable
it. In some cases, a constraint cannot be satisfied automatically,
and the user will be forced to resolve the constraint manually.
If *constraint* is None, then any constraints are removed for the variable.'
| def set(self, name, value=None, constraint=True):
| var = self._vars[name]
if (constraint is None):
if ('n' not in var[3]):
raise TypeError(("Empty constraints not allowed for '%s'" % name))
var[2] = constraint
elif (constraint == 'fixed'):
if ('f' not in var[3]):
raise TypeError(("Fixed constraints not allowed for '%s'" % name))
var[2] = constraint
elif isinstance(constraint, tuple):
if ('r' not in var[3]):
raise TypeError(("Range constraints not allowed for '%s'" % name))
assert (len(constraint) == 2)
var[2] = constraint
elif (constraint is not True):
raise TypeError(("constraint must be None, True, 'fixed', or tuple. (got %s)" % constraint))
if (var[1] is np.ndarray):
value = np.array(value, dtype=float)
elif ((var[1] in (int, float, tuple)) and (value is not None)):
value = var[1](value)
if ((constraint is True) and (not self.check_constraint(name, value))):
raise ValueError(('Setting %s = %s violates constraint %s' % (name, value, var[2])))
if (var[0] is not None):
self.resetUnfixed()
var[0] = value
return value
|
'Return a serializable description of the solver\'s current state.'
| def saveState(self):
| state = OrderedDict()
for (name, var) in self._vars.items():
state[name] = (var[0], var[2])
return state
|
'Restore the state of all values and constraints in the solver.'
| def restoreState(self, state):
| self.reset()
for (name, var) in state.items():
self.set(name, var[0], var[1])
|
'For any variable that does not have a fixed value, reset
its value to None.'
| def resetUnfixed(self):
| for var in self._vars.values():
if (var[2] != 'fixed'):
var[0] = None
|
'Return True if this item should be included in the tab-focus order'
| def isFocusable(self):
| return False
|
'Give input focus to this item.
Can be reimplemented to display editor widgets, etc.'
| def setFocus(self):
| pass
|
'Give focus to the next (or previous) focusable item in the parameter tree'
| def focusNext(self, forward=True):
| self.treeWidget().focusNext(self, forward=forward)
|
'Called when this item is added or removed from a tree.
Expansion, visibility, and column widgets must all be configured AFTER
the item is added to a tree, not during __init__.'
| def treeWidgetChanged(self):
| self.setHidden((not self.param.opts.get('visible', True)))
self.setExpanded(self.param.opts.get('expanded', True))
|
'Called when the text in a column has been edited (or otherwise changed).
By default, we only use changes to column 0 to rename the parameter.'
| def columnChangedEvent(self, col):
| if ((col == 0) and (self.param.opts.get('title', None) is None)):
if self.ignoreNameColumnChange:
return
try:
newName = self.param.setName(asUnicode(self.text(col)))
except Exception:
self.setText(0, self.param.name())
raise
try:
self.ignoreNameColumnChange = True
self.nameChanged(self, newName)
finally:
self.ignoreNameColumnChange = False
|
'Called when the parameter\'s limits have changed'
| def limitsChanged(self, param, limits):
| pass
|
'Called when the parameter\'s default value has changed'
| def defaultChanged(self, param, default):
| pass
|
'Called when any options are changed that are not
name, value, default, or limits'
| def optsChanged(self, param, opts):
| if ('visible' in opts):
self.setHidden((not opts['visible']))
|
'Called when this item has been selected (sel=True) OR deselected (sel=False)'
| def selected(self, sel):
| pass
|
'Return (r,g,b,a) normalized for use in opengl'
| def glColor(self):
| return ((self.red() / 255.0), (self.green() / 255.0), (self.blue() / 255.0), (self.alpha() / 255.0))
|
'Acceptable arguments are:
x, y
[x, y]
Point(x,y)'
| def translate(self, *args):
| t = Point(*args)
self.setTranslate((self._state['pos'] + t))
|
'Acceptable arguments are:
x, y
[x, y]
Point(x,y)'
| def setTranslate(self, *args):
| self._state['pos'] = Point(*args)
self.update()
|
'Acceptable arguments are:
x, y
[x, y]
Point(x,y)'
| def scale(self, *args):
| s = Point(*args)
self.setScale((self._state['scale'] * s))
|
'Acceptable arguments are:
x, y
[x, y]
Point(x,y)'
| def setScale(self, *args):
| self._state['scale'] = Point(*args)
self.update()
|
'Rotate the transformation by angle (in degrees)'
| def rotate(self, angle):
| self.setRotate((self._state['angle'] + angle))
|
'Set the transformation rotation to angle (in degrees)'
| def setRotate(self, angle):
| self._state['angle'] = angle
self.update()
|
'A / B == B^-1 * A'
| def __truediv__(self, t):
| dt = (t.inverted()[0] * self)
return SRTTransform(dt)
|
'Sets the button\'s color and emits both sigColorChanged and sigColorChanging.'
| def setColor(self, color, finished=True):
| self._color = functions.mkColor(color)
if finished:
self.sigColorChanged.emit(self)
else:
self.sigColorChanging.emit(self)
self.update()
|
'The *orientation* argument may be \'bottom\', \'top\', \'left\', or \'right\'
indicating whether the gradient is displayed horizontally (top, bottom)
or vertically (left, right) and on what side of the gradient the editable
ticks will appear.
All other arguments are passed to
:func:`GradientEditorItem.__init__ <pyqtgraph.GradientEditorItem.__init__>`.
Note: For convenience, this class wraps methods from
:class:`GradientEditorItem <pyqtgraph.GradientEditorItem>`.'
| def __init__(self, parent=None, orientation='bottom', *args, **kargs):
| GraphicsView.__init__(self, parent, useOpenGL=False, background=None)
self.maxDim = 31
kargs['tickPen'] = 'k'
self.item = GradientEditorItem(*args, **kargs)
self.item.sigGradientChanged.connect(self.sigGradientChanged)
self.item.sigGradientChangeFinished.connect(self.sigGradientChangeFinished)
self.setCentralItem(self.item)
self.setOrientation(orientation)
self.setCacheMode(self.CacheNone)
self.setRenderHints((QtGui.QPainter.Antialiasing | QtGui.QPainter.TextAntialiasing))
self.setFrameStyle((QtGui.QFrame.NoFrame | QtGui.QFrame.Plain))
|
'Set the orientation of the widget. May be one of \'bottom\', \'top\',
\'left\', or \'right\'.'
| def setOrientation(self, ort):
| self.item.setOrientation(ort)
self.orientation = ort
self.setMaxDim()
|
'Calls success() or failure(). If you want the message to be displayed until the user takes an action, set limitedTime to False. Then call self.reset() after the desired action.Threadsafe.'
| def feedback(self, success, message=None, tip='', limitedTime=True):
| if success:
self.success(message, tip, limitedTime=limitedTime)
else:
self.failure(message, tip, limitedTime=limitedTime)
|
'Displays specified message on button and flashes button green to let user know action was successful. If you want the success to be displayed until the user takes an action, set limitedTime to False. Then call self.reset() after the desired action. Threadsafe.'
| def success(self, message=None, tip='', limitedTime=True):
| isGuiThread = (QtCore.QThread.currentThread() == QtCore.QCoreApplication.instance().thread())
if isGuiThread:
self.setEnabled(True)
self.startBlink('#0F0', message, tip, limitedTime=limitedTime)
else:
self.sigCallSuccess.emit(message, tip, limitedTime)
|
'Displays specified message on button and flashes button red to let user know there was an error. If you want the error to be displayed until the user takes an action, set limitedTime to False. Then call self.reset() after the desired action. Threadsafe.'
| def failure(self, message=None, tip='', limitedTime=True):
| isGuiThread = (QtCore.QThread.currentThread() == QtCore.QCoreApplication.instance().thread())
if isGuiThread:
self.setEnabled(True)
self.startBlink('#F00', message, tip, limitedTime=limitedTime)
else:
self.sigCallFailure.emit(message, tip, limitedTime)
|
'Displays specified message on button to let user know the action is in progress. Threadsafe.'
| def processing(self, message='Processing..', tip='', processEvents=True):
| isGuiThread = (QtCore.QThread.currentThread() == QtCore.QCoreApplication.instance().thread())
if isGuiThread:
self.setEnabled(False)
self.setText(message, temporary=True)
self.setToolTip(tip, temporary=True)
if processEvents:
QtGui.QApplication.processEvents()
else:
self.sigCallProcess.emit(message, tip, processEvents)
|
'Resets the button to its original text and style. Threadsafe.'
| def reset(self):
| isGuiThread = (QtCore.QThread.currentThread() == QtCore.QCoreApplication.instance().thread())
if isGuiThread:
self.limitedTime = True
self.setText()
self.setToolTip()
self.setStyleSheet()
else:
self.sigReset.emit()
|
'All positional arguments are passed to QTableWidget.__init__().
**Keyword Arguments**
editable (bool) If True, cells in the table can be edited
by the user. Default is False.
sortable (bool) If True, the table may be soted by
clicking on column headers. Note that this also
causes rows to appear initially shuffled until
a sort column is selected. Default is True.
*(added in version 0.9.9)*'
| def __init__(self, *args, **kwds):
| QtGui.QTableWidget.__init__(self, *args)
self.itemClass = TableWidgetItem
self.setVerticalScrollMode(self.ScrollPerPixel)
self.setSelectionMode(QtGui.QAbstractItemView.ContiguousSelection)
self.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
self.clear()
kwds.setdefault('sortable', True)
kwds.setdefault('editable', False)
self.setEditable(kwds.pop('editable'))
self.setSortingEnabled(kwds.pop('sortable'))
if (len(kwds) > 0):
raise TypeError(("Invalid keyword arguments '%s'" % kwds.keys()))
self._sorting = None
self._formats = {None: None}
self.sortModes = {}
self.itemChanged.connect(self.handleItemChanged)
self.contextMenu = QtGui.QMenu()
self.contextMenu.addAction('Copy Selection').triggered.connect(self.copySel)
self.contextMenu.addAction('Copy All').triggered.connect(self.copyAll)
self.contextMenu.addAction('Save Selection').triggered.connect(self.saveSel)
self.contextMenu.addAction('Save All').triggered.connect(self.saveAll)
|
'Clear all contents from the table.'
| def clear(self):
| QtGui.QTableWidget.clear(self)
self.verticalHeadersSet = False
self.horizontalHeadersSet = False
self.items = []
self.setRowCount(0)
self.setColumnCount(0)
self.sortModes = {}
|
'Set the data displayed in the table.
Allowed formats are:
* numpy arrays
* numpy record arrays
* metaarrays
* list-of-lists [[1,2,3], [4,5,6]]
* dict-of-lists {\'x\': [1,2,3], \'y\': [4,5,6]}
* list-of-dicts [{\'x\': 1, \'y\': 4}, {\'x\': 2, \'y\': 5}, ...]'
| def setData(self, data):
| self.clear()
self.appendData(data)
self.resizeColumnsToContents()
|
'Add new rows to the table.
See :func:`setData() <pyqtgraph.TableWidget.setData>` for accepted
data types.'
| @_defersort
def appendData(self, data):
| startRow = self.rowCount()
(fn0, header0) = self.iteratorFn(data)
if (fn0 is None):
self.clear()
return
it0 = fn0(data)
try:
first = next(it0)
except StopIteration:
return
(fn1, header1) = self.iteratorFn(first)
if (fn1 is None):
self.clear()
return
firstVals = [x for x in fn1(first)]
self.setColumnCount(len(firstVals))
if ((not self.verticalHeadersSet) and (header0 is not None)):
labels = [self.verticalHeaderItem(i).text() for i in range(self.rowCount())]
self.setRowCount((startRow + len(header0)))
self.setVerticalHeaderLabels((labels + header0))
self.verticalHeadersSet = True
if ((not self.horizontalHeadersSet) and (header1 is not None)):
self.setHorizontalHeaderLabels(header1)
self.horizontalHeadersSet = True
i = startRow
self.setRow(i, firstVals)
for row in it0:
i += 1
self.setRow(i, [x for x in fn1(row)])
if (self._sorting and (self.horizontalHeader().sortIndicatorSection() >= self.columnCount())):
self.sortByColumn(0, QtCore.Qt.AscendingOrder)
|
'Specify the default text formatting for the entire table, or for a
single column if *column* is specified.
If a string is specified, it is used as a format string for converting
float values (and all other types are converted using str). If a
function is specified, it will be called with the item as its only
argument and must return a string. Setting format = None causes the
default formatter to be used instead.
Added in version 0.9.9.'
| def setFormat(self, format, column=None):
| if ((format is not None) and (not isinstance(format, basestring)) and (not callable(format))):
raise ValueError(('Format argument must string, callable, or None. (got %s)' % format))
self._formats[column] = format
if (column is None):
for c in range(self.columnCount()):
if (self._formats.get(c, None) is None):
for r in range(self.rowCount()):
item = self.item(r, c)
if (item is None):
continue
item.setFormat(format)
else:
if (format is None):
format = self._formats[None]
for r in range(self.rowCount()):
item = self.item(r, column)
if (item is None):
continue
item.setFormat(format)
|
'Set the mode used to sort *column*.
**Sort Modes**
value Compares item.value if available; falls back to text
comparison.
text Compares item.text()
index Compares by the order in which items were inserted.
Added in version 0.9.9'
| def setSortMode(self, column, mode):
| for r in range(self.rowCount()):
item = self.item(r, column)
if hasattr(item, 'setSortMode'):
item.setSortMode(mode)
self.sortModes[column] = mode
|
'Convert entire table (or just selected area) into tab-separated text values'
| def serialize(self, useSelection=False):
| if useSelection:
selection = self.selectedRanges()[0]
rows = list(range(selection.topRow(), (selection.bottomRow() + 1)))
columns = list(range(selection.leftColumn(), (selection.rightColumn() + 1)))
else:
rows = list(range(self.rowCount()))
columns = list(range(self.columnCount()))
data = []
if self.horizontalHeadersSet:
row = []
if self.verticalHeadersSet:
row.append(asUnicode(''))
for c in columns:
row.append(asUnicode(self.horizontalHeaderItem(c).text()))
data.append(row)
for r in rows:
row = []
if self.verticalHeadersSet:
row.append(asUnicode(self.verticalHeaderItem(r).text()))
for c in columns:
item = self.item(r, c)
if (item is not None):
row.append(asUnicode(item.value))
else:
row.append(asUnicode(''))
data.append(row)
s = ''
for row in data:
s += (' DCTB '.join(row) + '\n')
return s
|
'Copy selected data to clipboard.'
| def copySel(self):
| QtGui.QApplication.clipboard().setText(self.serialize(useSelection=True))
|
'Copy all data to clipboard.'
| def copyAll(self):
| QtGui.QApplication.clipboard().setText(self.serialize(useSelection=False))
|
'Save selected data to file.'
| def saveSel(self):
| self.save(self.serialize(useSelection=True))
|
'Save all data to file.'
| def saveAll(self):
| self.save(self.serialize(useSelection=False))
|
'Set whether this item is user-editable.'
| def setEditable(self, editable):
| if editable:
self.setFlags((self.flags() | QtCore.Qt.ItemIsEditable))
else:
self.setFlags((self.flags() & (~ QtCore.Qt.ItemIsEditable)))
|
'Set the mode used to sort this item against others in its column.
**Sort Modes**
value Compares item.value if available; falls back to text
comparison.
text Compares item.text()
index Compares by the order in which items were inserted.'
| def setSortMode(self, mode):
| modes = ('value', 'text', 'index', None)
if (mode not in modes):
raise ValueError(('Sort mode must be one of %s' % str(modes)))
self.sortMode = mode
|
'Define the conversion from item value to displayed text.
If a string is specified, it is used as a format string for converting
float values (and all other types are converted using str). If a
function is specified, it will be called with the item as its only
argument and must return a string.
Added in version 0.9.9.'
| def setFormat(self, fmt):
| if ((fmt is not None) and (not isinstance(fmt, basestring)) and (not callable(fmt))):
raise ValueError(('Format argument must string, callable, or None. (got %s)' % fmt))
self._format = fmt
self._updateText()
|
'Called when the data of this item has changed.'
| def itemChanged(self):
| if (self.text() != self._text):
self.textChanged()
|
'Called when this item\'s text has changed for any reason.'
| def textChanged(self):
| self._text = self.text()
if self._blockValueChange:
return
try:
self.value = type(self.value)(self.text())
except ValueError:
self.value = str(self.text())
|
'Set the minimum height for each sub-plot displayed.
If the total height of all plots is greater than the height of the
widget, then a scroll bar will appear to provide access to the entire
set of plots.
Added in version 0.9.9'
| def setMinimumPlotHeight(self, min):
| self.minPlotHeight = min
self.resizeEvent(None)
|
'**Arguments:**
parent Optional parent widget
useOpenGL If True, the GraphicsView will use OpenGL to do all of its
rendering. This can improve performance on some systems,
but may also introduce bugs (the combination of
QGraphicsView and QGLWidget is still an \'experimental\'
feature of Qt)
background Set the background color of the GraphicsView. Accepts any
single argument accepted by
:func:`mkColor <pyqtgraph.mkColor>`. By
default, the background color is determined using the
\'backgroundColor\' configuration option (see
:func:`setConfigOptions <pyqtgraph.setConfigOptions>`).'
| def __init__(self, parent=None, useOpenGL=None, background='default'):
| self.closed = False
QtGui.QGraphicsView.__init__(self, parent)
from .. import _connectCleanup
_connectCleanup()
if (useOpenGL is None):
useOpenGL = getConfigOption('useOpenGL')
self.useOpenGL(useOpenGL)
self.setCacheMode(self.CacheBackground)
self.setBackgroundRole(QtGui.QPalette.NoRole)
self.setBackground(background)
self.setFocusPolicy(QtCore.Qt.StrongFocus)
self.setFrameShape(QtGui.QFrame.NoFrame)
self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.setTransformationAnchor(QtGui.QGraphicsView.NoAnchor)
self.setResizeAnchor(QtGui.QGraphicsView.AnchorViewCenter)
self.setViewportUpdateMode(QtGui.QGraphicsView.MinimalViewportUpdate)
self.lockedViewports = []
self.lastMousePos = None
self.setMouseTracking(True)
self.aspectLocked = False
self.range = QtCore.QRectF(0, 0, 1, 1)
self.autoPixelRange = True
self.currentItem = None
self.clearMouse()
self.updateMatrix()
self.sceneObj = GraphicsScene(parent=self)
self.setScene(self.sceneObj)
if USE_PYSIDE:
self.sceneObj._view_ref_workaround = self
self.centralWidget = None
self.setCentralItem(QtGui.QGraphicsWidget())
self.centralLayout = QtGui.QGraphicsGridLayout()
self.centralWidget.setLayout(self.centralLayout)
self.mouseEnabled = False
self.scaleCenter = False
self.clickAccepted = False
|
'Enable or disable default antialiasing.
Note that this will only affect items that do not specify their own antialiasing options.'
| def setAntialiasing(self, aa):
| if aa:
self.setRenderHints((self.renderHints() | QtGui.QPainter.Antialiasing))
else:
self.setRenderHints((self.renderHints() & (~ QtGui.QPainter.Antialiasing)))
|
'Set the background color of the GraphicsView.
To use the defaults specified py pyqtgraph.setConfigOption, use background=\'default\'.
To make the background transparent, use background=None.'
| def setBackground(self, background):
| self._background = background
if (background == 'default'):
background = getConfigOption('background')
brush = fn.mkBrush(background)
self.setBackgroundBrush(brush)
|
'Sets a QGraphicsWidget to automatically fill the entire view (the item will be automatically
resize whenever the GraphicsView is resized).'
| def setCentralWidget(self, item):
| if (self.centralWidget is not None):
self.scene().removeItem(self.centralWidget)
self.centralWidget = item
if (item is not None):
self.sceneObj.addItem(item)
self.resizeEvent(None)
|
'Return the boundaries of the view in scene coordinates'
| def viewRect(self):
| r = QtCore.QRectF(self.rect())
return self.viewportTransform().inverted()[0].mapRect(r)
|
'Scales such that pixels in image are the same size as screen pixels. This may result in a significant performance increase.'
| def scaleToImage(self, image):
| pxSize = image.pixelSize()
image.setPxMode(True)
try:
self.sigScaleChanged.disconnect(image.setScaledMode)
except (TypeError, RuntimeError):
pass
tl = image.sceneBoundingRect().topLeft()
w = (self.size().width() * pxSize[0])
h = (self.size().height() * pxSize[1])
range = QtCore.QRectF(tl.x(), tl.y(), w, h)
GraphicsView.setRange(self, range, padding=0)
self.sigScaleChanged.connect(image.setScaledMode)
|
'Return vector with the length and width of one view pixel in scene coordinates'
| def pixelSize(self):
| p0 = Point(0, 0)
p1 = Point(1, 1)
tr = self.transform().inverted()[0]
p01 = tr.map(p0)
p11 = tr.map(p1)
return Point((p11 - p01))
|
'Advance to next row for automatic widget placement'
| def nextRow(self):
| self.currentRow += 1
self.currentCol = 0
|
'Advance to next column, while returning the current column number
(generally only for internal use--called by addWidget)'
| def nextColumn(self, colspan=1):
| self.currentCol += colspan
return (self.currentCol - colspan)
|
'Alias of nextColumn'
| def nextCol(self, *args, **kargs):
| return self.nextColumn(*args, **kargs)
|
'Create a QLabel with *text* and place it in the next available cell (or in the cell specified)
All extra keyword arguments are passed to QLabel().
Returns the created widget.'
| def addLabel(self, text=' ', row=None, col=None, rowspan=1, colspan=1, **kargs):
| text = QtGui.QLabel(text, **kargs)
self.addItem(text, row, col, rowspan, colspan)
return text
|
'Create an empty LayoutWidget and place it in the next available cell (or in the cell specified)
All extra keyword arguments are passed to :func:`LayoutWidget.__init__ <pyqtgraph.LayoutWidget.__init__>`
Returns the created widget.'
| def addLayout(self, row=None, col=None, rowspan=1, colspan=1, **kargs):
| layout = LayoutWidget(**kargs)
self.addItem(layout, row, col, rowspan, colspan)
return layout
|
'Add a widget to the layout and place it in the next available cell (or in the cell specified).'
| def addWidget(self, item, row=None, col=None, rowspan=1, colspan=1):
| if (row == 'next'):
self.nextRow()
row = self.currentRow
elif (row is None):
row = self.currentRow
if (col is None):
col = self.nextCol(colspan)
if (row not in self.rows):
self.rows[row] = {}
self.rows[row][col] = item
self.items[item] = (row, col)
self.layout.addWidget(item, row, col, rowspan, colspan)
|
'Return the widget in (*row*, *col*)'
| def getWidget(self, row, col):
| return self.row[row][col]
|
'Set the list of field names/units to be processed.
The format of *fields* is the same as used by
:func:`ColorMapWidget.setFields <pyqtgraph.widgets.ColorMapWidget.ColorMapParameter.setFields>`'
| def setFields(self, fields, mouseOverField=None):
| self.fields = OrderedDict(fields)
self.mouseOverField = mouseOverField
self.fieldList.clear()
for (f, opts) in fields:
item = QtGui.QListWidgetItem(f)
item.opts = opts
item = self.fieldList.addItem(item)
self.filter.setFields(fields)
self.colorMap.setFields(fields)
|
'Set the data to be processed and displayed.
Argument must be a numpy record array.'
| def setData(self, data):
| self.data = data
self.filtered = None
self.updatePlot()
|
'Setting scaled=True will cause the entire image to be displayed within the boundaries of the widget. This also greatly reduces the speed at which it will draw frames.'
| def __init__(self, parent=None, scaled=False):
| QtGui.QWidget.__init__(self, parent=None)
self.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding))
self.scaled = scaled
self.opts = None
self.image = None
|
'img must be ndarray of shape (x,y), (x,y,3), or (x,y,4).
Extra arguments are sent to functions.makeARGB'
| def setImage(self, img, *args, **kargs):
| self.opts = (img, args, kargs)
self.image = None
self.update()
|
'**Arguments:**
labelText (required)
cancelText Text to display on cancel button, or None to disable it.
minimum
maximum
parent
wait Length of time (im ms) to wait before displaying dialog
busyCursor If True, show busy cursor until dialog finishes
disable If True, the progress dialog will not be displayed
and calls to wasCanceled() will always return False.
If ProgressDialog is entered from a non-gui thread, it will
always be disabled.'
| def __init__(self, labelText, minimum=0, maximum=100, cancelText='Cancel', parent=None, wait=250, busyCursor=False, disable=False):
| isGuiThread = (QtCore.QThread.currentThread() == QtCore.QCoreApplication.instance().thread())
self.disabled = (disable or (not isGuiThread))
if self.disabled:
return
noCancel = False
if (cancelText is None):
cancelText = ''
noCancel = True
self.busyCursor = busyCursor
QtGui.QProgressDialog.__init__(self, labelText, cancelText, minimum, maximum, parent)
self.setMinimumDuration(wait)
self.setWindowModality(QtCore.Qt.WindowModal)
self.setValue(self.minimum())
if noCancel:
self.setCancelButton(None)
|
'Use inplace-addition operator for easy incrementing.'
| def __iadd__(self, val):
| if self.disabled:
return self
self.setValue((self.value() + val))
return self
|
'**Arguments:**
parent Sets the parent widget for this SpinBox (optional). Default is None.
value (float/int) initial value. Default is 0.0.
All keyword arguments are passed to :func:`setOpts`.'
| def __init__(self, parent=None, value=0.0, **kwargs):
| QtGui.QAbstractSpinBox.__init__(self, parent)
self.lastValEmitted = None
self.lastText = ''
self.textValid = True
self.setMinimumWidth(0)
self._lastFontHeight = None
self.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred)
self.errorBox = ErrorBox(self.lineEdit())
self.opts = {'bounds': [None, None], 'wrapping': False, 'step': D('0.01'), 'log': False, 'dec': False, 'int': False, 'suffix': '', 'siPrefix': False, 'delay': 0.3, 'delayUntilEditFinished': True, 'decimals': 6, 'format': asUnicode('{scaledValue:.{decimals}g}{suffixGap}{siPrefix}{suffix}'), 'regex': fn.FLOAT_REGEX, 'evalFunc': D, 'compactHeight': True}
self.decOpts = ['step', 'minStep']
self.val = D(asUnicode(value))
self.updateText()
self.skipValidate = False
self.setCorrectionMode(self.CorrectToPreviousValue)
self.setKeyboardTracking(False)
self.setOpts(**kwargs)
self._updateHeight()
self.editingFinished.connect(self.editingFinishedEvent)
self.proxy = SignalProxy(self.sigValueChanging, slot=self.delayedChange, delay=self.opts['delay'])
|
'Set options affecting the behavior of the SpinBox.
**Arguments:**
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
wrapping (bool) If True and both bounds are not None, spin box has circular behavior.
decimals (int) Number of decimal values to display. Default is 6.
format (str) Formatting string used to generate the text shown. Formatting is
done with ``str.format()`` and makes use of several arguments:
* *value* - the unscaled value of the spin box
* *suffix* - the suffix string
* *scaledValue* - the scaled value to use when an SI prefix is present
* *siPrefix* - the SI prefix string (if any), or an empty string if
this feature has been disabled
* *suffixGap* - a single space if a suffix is present, or an empty
string otherwise.
regex (str or RegexObject) Regular expression used to parse the spinbox text.
May contain the following group names:
* *number* - matches the numerical portion of the string (mandatory)
* *siPrefix* - matches the SI prefix string
* *suffix* - matches the suffix string
Default is defined in ``pyqtgraph.functions.FLOAT_REGEX``.
evalFunc (callable) Fucntion that converts a numerical string to a number,
preferrably a Decimal instance. This function handles only the numerical
of the text; it does not have access to the suffix or SI prefix.
compactHeight (bool) if True, then set the maximum height of the spinbox based on the
height of its font. This allows more compact packing on platforms with
excessive widget decoration. Default is True.'
| def setOpts(self, **opts):
| for (k, v) in opts.items():
if (k == 'bounds'):
self.setMinimum(v[0], update=False)
self.setMaximum(v[1], update=False)
elif (k == 'min'):
self.setMinimum(v, update=False)
elif (k == 'max'):
self.setMaximum(v, update=False)
elif (k in ['step', 'minStep']):
self.opts[k] = D(asUnicode(v))
elif (k == 'value'):
pass
elif (k == 'format'):
self.opts[k] = asUnicode(v)
elif ((k == 'regex') and isinstance(v, basestring)):
self.opts[k] = re.compile(v)
elif (k in self.opts):
self.opts[k] = v
else:
raise TypeError(("Invalid keyword argument '%s'." % k))
if ('value' in opts):
self.setValue(opts['value'])
if (('bounds' in opts) and ('value' not in opts)):
self.setValue()
if self.opts['int']:
if ('step' in opts):
step = opts['step']
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()
|
'Set the maximum allowed value (or None for no limit)'
| def setMaximum(self, m, update=True):
| if (m is not None):
m = D(asUnicode(m))
self.opts['bounds'][1] = m
if update:
self.setValue()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.