repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
titusjan/argos
argos/application.py
ArgosApplication.raiseAllWindows
def raiseAllWindows(self): """ Raises all application windows. """ logger.debug("raiseAllWindows called") for mainWindow in self.mainWindows: logger.debug("Raising {}".format(mainWindow._instanceNr)) mainWindow.raise_()
python
def raiseAllWindows(self): """ Raises all application windows. """ logger.debug("raiseAllWindows called") for mainWindow in self.mainWindows: logger.debug("Raising {}".format(mainWindow._instanceNr)) mainWindow.raise_()
Raises all application windows.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/application.py#L365-L371
titusjan/argos
argos/application.py
ArgosApplication.quit
def quit(self): """ Quits the application (called when the last window is closed) """ logger.debug("ArgosApplication.quit called") assert len(self.mainWindows) == 0, \ "Bug: still {} windows present at application quit!".format(len(self.mainWindows)) self.qApplication.quit()
python
def quit(self): """ Quits the application (called when the last window is closed) """ logger.debug("ArgosApplication.quit called") assert len(self.mainWindows) == 0, \ "Bug: still {} windows present at application quit!".format(len(self.mainWindows)) self.qApplication.quit()
Quits the application (called when the last window is closed)
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/application.py#L382-L388
titusjan/argos
argos/application.py
ArgosApplication.execute
def execute(self): """ Executes all main windows by starting the Qt main application """ logger.info("Starting Argos event loop...") exitCode = self.qApplication.exec_() logger.info("Argos event loop finished with exit code: {}".format(exitCode)) return exitCode
python
def execute(self): """ Executes all main windows by starting the Qt main application """ logger.info("Starting Argos event loop...") exitCode = self.qApplication.exec_() logger.info("Argos event loop finished with exit code: {}".format(exitCode)) return exitCode
Executes all main windows by starting the Qt main application
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/application.py#L391-L397
titusjan/argos
argos/repo/rtiplugins/pillowio.py
PillowFileRti._openResources
def _openResources(self): """ Uses open the underlying file """ with Image.open(self._fileName) as image: self._array = np.asarray(image) self._bands = image.getbands() # Fill attributes. For now assume that the info item are not overridden by # the Image items. self._attributes = dict(image.info) self._attributes['Format'] = image.format self._attributes['Mode'] = image.mode self._attributes['Size'] = image.size self._attributes['Width'] = image.width self._attributes['Height'] = image.height
python
def _openResources(self): """ Uses open the underlying file """ with Image.open(self._fileName) as image: self._array = np.asarray(image) self._bands = image.getbands() # Fill attributes. For now assume that the info item are not overridden by # the Image items. self._attributes = dict(image.info) self._attributes['Format'] = image.format self._attributes['Mode'] = image.mode self._attributes['Size'] = image.size self._attributes['Width'] = image.width self._attributes['Height'] = image.height
Uses open the underlying file
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/pillowio.py#L84-L98
titusjan/argos
argos/repo/rtiplugins/pillowio.py
PillowFileRti._fetchAllChildren
def _fetchAllChildren(self): """ Adds the bands as separate fields so they can be inspected easily. """ bands = self._bands if len(bands) != self._array.shape[-1]: logger.warn("No bands added, bands != last_dim_lenght ({} !: {})" .format(len(bands), self._array.shape[-1])) return [] childItems = [] for bandNr, band in enumerate(bands): bandItem = PillowBandRti(self._array[..., bandNr], nodeName=band, fileName=self.fileName, iconColor=self.iconColor, attributes=self._attributes) childItems.append(bandItem) return childItems
python
def _fetchAllChildren(self): """ Adds the bands as separate fields so they can be inspected easily. """ bands = self._bands if len(bands) != self._array.shape[-1]: logger.warn("No bands added, bands != last_dim_lenght ({} !: {})" .format(len(bands), self._array.shape[-1])) return [] childItems = [] for bandNr, band in enumerate(bands): bandItem = PillowBandRti(self._array[..., bandNr], nodeName=band, fileName=self.fileName, iconColor=self.iconColor, attributes=self._attributes) childItems.append(bandItem) return childItems
Adds the bands as separate fields so they can be inspected easily.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/pillowio.py#L109-L124
titusjan/argos
argos/repo/rtiplugins/pillowio.py
PillowFileRti.dimensionNames
def dimensionNames(self): """ Returns ['Y', 'X', 'Band']. The underlying array is expected to be 3-dimensional. If this is not the case we fall back on the default dimension names ['Dim-0', 'Dim-1', ...] """ if self._array is None: return [] if self._array.ndim == 2: return ['Y', 'X'] elif self._array.ndim == 3: return ['Y', 'X', 'Band'] else: # Defensive programming: fall back on default names msg = "Expected 3D image. Got: {}".format(self._array.ndim) if DEBUGGING: raise ValueError(msg) logger.warn(msg) return super(PillowFileRti, self).dimensionNames
python
def dimensionNames(self): """ Returns ['Y', 'X', 'Band']. The underlying array is expected to be 3-dimensional. If this is not the case we fall back on the default dimension names ['Dim-0', 'Dim-1', ...] """ if self._array is None: return [] if self._array.ndim == 2: return ['Y', 'X'] elif self._array.ndim == 3: return ['Y', 'X', 'Band'] else: # Defensive programming: fall back on default names msg = "Expected 3D image. Got: {}".format(self._array.ndim) if DEBUGGING: raise ValueError(msg) logger.warn(msg) return super(PillowFileRti, self).dimensionNames
Returns ['Y', 'X', 'Band']. The underlying array is expected to be 3-dimensional. If this is not the case we fall back on the default dimension names ['Dim-0', 'Dim-1', ...]
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/pillowio.py#L135-L153
titusjan/argos
argos/config/untypedcti.py
UntypedCti.createEditor
def createEditor(self, delegate, parent, option): """ Creates an UntypedCtiEditor. For the parameters see the AbstractCti constructor documentation. Note: since the item is not editable this will never be called. """ return UntypedCtiEditor(self, delegate, parent=parent)
python
def createEditor(self, delegate, parent, option): """ Creates an UntypedCtiEditor. For the parameters see the AbstractCti constructor documentation. Note: since the item is not editable this will never be called. """ return UntypedCtiEditor(self, delegate, parent=parent)
Creates an UntypedCtiEditor. For the parameters see the AbstractCti constructor documentation. Note: since the item is not editable this will never be called.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/untypedcti.py#L48-L53
titusjan/argos
argos/qt/labeledwidget.py
labelTextWidth
def labelTextWidth(label): """ Returns the width of label text of the label in pixels. IMPORTANT: does not work when the labels are styled using style sheets. Unfortunately it is possible to retrieve the settings (e.g. padding) that were set by the style sheet without parsing the style sheet as text. """ # The Qt source shows that fontMetrics().size calls fontMetrics().boundingRect with # the TextLongestVariant included in the flags. TextLongestVariant is an internal flag # which is used to force selecting the longest string in a multi-length string. # See: http://stackoverflow.com/a/8638114/625350 fontMetrics = label.fontMetrics() #contentsWidth = label.fontMetrics().boundingRect(label.text()).width() contentsWidth = fontMetrics.size(label.alignment(), label.text()).width() # If indent is negative, or if no indent has been set, the label computes the effective indent # as follows: If frameWidth() is 0, the effective indent becomes 0. If frameWidth() is greater # than 0, the effective indent becomes half the width of the "x" character of the widget's # current font(). # See http://doc.qt.io/qt-4.8/qlabel.html#indent-prop if label.indent() < 0 and label.frameWidth(): # no indent, but we do have a frame indent = fontMetrics.width('x') / 2 - label.margin() indent *= 2 # the indent seems to be added to the other side as well else: indent = label.indent() result = contentsWidth + indent + 2 * label.frameWidth() + 2 * label.margin() if 1: #print ("contentsMargins: {}".format(label.getContentsMargins())) #print ("contentsRect: {}".format(label.contentsRect())) #print ("frameRect: {}".format(label.frameRect())) print ("contentsWidth: {}".format(contentsWidth)) print ("lineWidth: {}".format(label.lineWidth())) print ("midLineWidth: {}".format(label.midLineWidth())) print ("frameWidth: {}".format(label.frameWidth())) print ("margin: {}".format(label.margin())) print ("indent: {}".format(label.indent())) print ("actual indent: {}".format(indent)) print ("RESULT: {}".format(result)) print () return result
python
def labelTextWidth(label): """ Returns the width of label text of the label in pixels. IMPORTANT: does not work when the labels are styled using style sheets. Unfortunately it is possible to retrieve the settings (e.g. padding) that were set by the style sheet without parsing the style sheet as text. """ # The Qt source shows that fontMetrics().size calls fontMetrics().boundingRect with # the TextLongestVariant included in the flags. TextLongestVariant is an internal flag # which is used to force selecting the longest string in a multi-length string. # See: http://stackoverflow.com/a/8638114/625350 fontMetrics = label.fontMetrics() #contentsWidth = label.fontMetrics().boundingRect(label.text()).width() contentsWidth = fontMetrics.size(label.alignment(), label.text()).width() # If indent is negative, or if no indent has been set, the label computes the effective indent # as follows: If frameWidth() is 0, the effective indent becomes 0. If frameWidth() is greater # than 0, the effective indent becomes half the width of the "x" character of the widget's # current font(). # See http://doc.qt.io/qt-4.8/qlabel.html#indent-prop if label.indent() < 0 and label.frameWidth(): # no indent, but we do have a frame indent = fontMetrics.width('x') / 2 - label.margin() indent *= 2 # the indent seems to be added to the other side as well else: indent = label.indent() result = contentsWidth + indent + 2 * label.frameWidth() + 2 * label.margin() if 1: #print ("contentsMargins: {}".format(label.getContentsMargins())) #print ("contentsRect: {}".format(label.contentsRect())) #print ("frameRect: {}".format(label.frameRect())) print ("contentsWidth: {}".format(contentsWidth)) print ("lineWidth: {}".format(label.lineWidth())) print ("midLineWidth: {}".format(label.midLineWidth())) print ("frameWidth: {}".format(label.frameWidth())) print ("margin: {}".format(label.margin())) print ("indent: {}".format(label.indent())) print ("actual indent: {}".format(indent)) print ("RESULT: {}".format(result)) print () return result
Returns the width of label text of the label in pixels. IMPORTANT: does not work when the labels are styled using style sheets. Unfortunately it is possible to retrieve the settings (e.g. padding) that were set by the style sheet without parsing the style sheet as text.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/labeledwidget.py#L66-L108
titusjan/argos
argos/qt/labeledwidget.py
harmonizeLabelsTextWidth
def harmonizeLabelsTextWidth(labels, width=None): """ Sets the the maximum width of the labels If width is None, the maximum width is calculated using labelsMaxTextWidth() """ if width is None: width = labelsMaxTextWidth(labels) for label in labels: #label.setFixedWidth(width) label.setMinimumWidth(width)
python
def harmonizeLabelsTextWidth(labels, width=None): """ Sets the the maximum width of the labels If width is None, the maximum width is calculated using labelsMaxTextWidth() """ if width is None: width = labelsMaxTextWidth(labels) for label in labels: #label.setFixedWidth(width) label.setMinimumWidth(width)
Sets the the maximum width of the labels If width is None, the maximum width is calculated using labelsMaxTextWidth()
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/labeledwidget.py#L118-L127
titusjan/argos
argos/config/abstractcti.py
jsonAsCti
def jsonAsCti(dct): """ Config tree item JSON decoding function. Returns a CTI given a dictionary of attributes. The full class name of desired CTI class should be in dct['_class_'']. """ if '_class_'in dct: full_class_name = dct['_class_'] # TODO: how to handle the full_class_name? cls = import_symbol(full_class_name) return cls.createFromJsonDict(dct) else: return dct
python
def jsonAsCti(dct): """ Config tree item JSON decoding function. Returns a CTI given a dictionary of attributes. The full class name of desired CTI class should be in dct['_class_'']. """ if '_class_'in dct: full_class_name = dct['_class_'] # TODO: how to handle the full_class_name? cls = import_symbol(full_class_name) return cls.createFromJsonDict(dct) else: return dct
Config tree item JSON decoding function. Returns a CTI given a dictionary of attributes. The full class name of desired CTI class should be in dct['_class_''].
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/abstractcti.py#L64-L73
titusjan/argos
argos/config/abstractcti.py
AbstractCti.enableBranch
def enableBranch(self, enabled): """ Sets the enabled member to True or False for a node and all it's children """ self.enabled = enabled for child in self.childItems: child.enableBranch(enabled)
python
def enableBranch(self, enabled): """ Sets the enabled member to True or False for a node and all it's children """ self.enabled = enabled for child in self.childItems: child.enableBranch(enabled)
Sets the enabled member to True or False for a node and all it's children
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/abstractcti.py#L291-L296
titusjan/argos
argos/config/abstractcti.py
AbstractCti.resetToDefault
def resetToDefault(self, resetChildren=True): """ Resets the data to the default data. By default the children will be reset as well """ self.data = self.defaultData if resetChildren: for child in self.childItems: child.resetToDefault(resetChildren=True)
python
def resetToDefault(self, resetChildren=True): """ Resets the data to the default data. By default the children will be reset as well """ self.data = self.defaultData if resetChildren: for child in self.childItems: child.resetToDefault(resetChildren=True)
Resets the data to the default data. By default the children will be reset as well
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/abstractcti.py#L299-L305
titusjan/argos
argos/config/abstractcti.py
AbstractCti.refreshFromTarget
def refreshFromTarget(self, level=0): """ Refreshes the configuration tree from the target it monitors (if present). Recursively call _refreshNodeFromTarget for itself and all children. Subclasses should typically override _refreshNodeFromTarget instead of this function. During updateTarget's execution refreshFromTarget is blocked to avoid loops. """ if self.getRefreshBlocked(): logger.debug("_refreshNodeFromTarget blocked") return if False and level == 0: logger.debug("refreshFromTarget: {}".format(self.nodePath)) self._refreshNodeFromTarget() for child in self.childItems: child.refreshFromTarget(level=level + 1)
python
def refreshFromTarget(self, level=0): """ Refreshes the configuration tree from the target it monitors (if present). Recursively call _refreshNodeFromTarget for itself and all children. Subclasses should typically override _refreshNodeFromTarget instead of this function. During updateTarget's execution refreshFromTarget is blocked to avoid loops. """ if self.getRefreshBlocked(): logger.debug("_refreshNodeFromTarget blocked") return if False and level == 0: logger.debug("refreshFromTarget: {}".format(self.nodePath)) self._refreshNodeFromTarget() for child in self.childItems: child.refreshFromTarget(level=level + 1)
Refreshes the configuration tree from the target it monitors (if present). Recursively call _refreshNodeFromTarget for itself and all children. Subclasses should typically override _refreshNodeFromTarget instead of this function. During updateTarget's execution refreshFromTarget is blocked to avoid loops.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/abstractcti.py#L316-L331
titusjan/argos
argos/config/abstractcti.py
AbstractCti.updateTarget
def updateTarget(self, level=0): """ Applies the configuration to the target it monitors (if present). Recursively call _updateTargetFromNode for itself and all children. Subclasses should typically override _updateTargetFromNode instead of this function. :param level: the level of recursion. """ #if level == 0: # logger.debug("updateTarget: {}".format(self.nodePath)) self._updateTargetFromNode() for child in self.childItems: child.updateTarget(level = level + 1)
python
def updateTarget(self, level=0): """ Applies the configuration to the target it monitors (if present). Recursively call _updateTargetFromNode for itself and all children. Subclasses should typically override _updateTargetFromNode instead of this function. :param level: the level of recursion. """ #if level == 0: # logger.debug("updateTarget: {}".format(self.nodePath)) self._updateTargetFromNode() for child in self.childItems: child.updateTarget(level = level + 1)
Applies the configuration to the target it monitors (if present). Recursively call _updateTargetFromNode for itself and all children. Subclasses should typically override _updateTargetFromNode instead of this function. :param level: the level of recursion.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/abstractcti.py#L343-L355
titusjan/argos
argos/config/abstractcti.py
AbstractCti._nodeGetNonDefaultsDict
def _nodeGetNonDefaultsDict(self): """ Retrieves this nodes` values as a dictionary to be used for persistence. A dictionary with the data value will be returned if the data is not equal to the defaultData, the node is enabled and the node is editable. Otherwise and empty dictionary is returned. Non-recursive auxiliary function for getNonDefaultsDict """ dct = {} isEditable = bool(int(self.valueColumnItemFlags) and Qt.ItemIsEditable) if (self.data != self.defaultData and self.enabled and isEditable): dct['data'] = self.data return dct
python
def _nodeGetNonDefaultsDict(self): """ Retrieves this nodes` values as a dictionary to be used for persistence. A dictionary with the data value will be returned if the data is not equal to the defaultData, the node is enabled and the node is editable. Otherwise and empty dictionary is returned. Non-recursive auxiliary function for getNonDefaultsDict """ dct = {} isEditable = bool(int(self.valueColumnItemFlags) and Qt.ItemIsEditable) if (self.data != self.defaultData and self.enabled and isEditable): dct['data'] = self.data return dct
Retrieves this nodes` values as a dictionary to be used for persistence. A dictionary with the data value will be returned if the data is not equal to the defaultData, the node is enabled and the node is editable. Otherwise and empty dictionary is returned. Non-recursive auxiliary function for getNonDefaultsDict
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/abstractcti.py#L400-L412
titusjan/argos
argos/config/abstractcti.py
AbstractCti.getNonDefaultsDict
def getNonDefaultsDict(self): """ Recursively retrieves values as a dictionary to be used for persistence. Does not save defaultData and other properties, only stores values if they differ from the defaultData. If the CTI and none of its children differ from their default, a completely empty dictionary is returned. This is to achieve a smaller json representation. Typically descendants should override _nodeGetNonDefaultsDict instead of this function. """ dct = self._nodeGetNonDefaultsDict() childList = [] for childCti in self.childItems: childDct = childCti.getNonDefaultsDict() if childDct: childList.append(childDct) if childList: dct['childItems'] = childList if dct: dct['nodeName'] = self.nodeName return dct
python
def getNonDefaultsDict(self): """ Recursively retrieves values as a dictionary to be used for persistence. Does not save defaultData and other properties, only stores values if they differ from the defaultData. If the CTI and none of its children differ from their default, a completely empty dictionary is returned. This is to achieve a smaller json representation. Typically descendants should override _nodeGetNonDefaultsDict instead of this function. """ dct = self._nodeGetNonDefaultsDict() childList = [] for childCti in self.childItems: childDct = childCti.getNonDefaultsDict() if childDct: childList.append(childDct) if childList: dct['childItems'] = childList if dct: dct['nodeName'] = self.nodeName return dct
Recursively retrieves values as a dictionary to be used for persistence. Does not save defaultData and other properties, only stores values if they differ from the defaultData. If the CTI and none of its children differ from their default, a completely empty dictionary is returned. This is to achieve a smaller json representation. Typically descendants should override _nodeGetNonDefaultsDict instead of this function.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/abstractcti.py#L417-L439
titusjan/argos
argos/config/abstractcti.py
AbstractCti.setValuesFromDict
def setValuesFromDict(self, dct): """ Recursively sets values from a dictionary created by getNonDefaultsDict. Does not raise exceptions (logs warnings instead) so that we can remove/rename node names in future Argos versions (or remove them) without breaking the application. Typically descendants should override _nodeSetValuesFromDict instead of this function. """ if 'nodeName' not in dct: return nodeName = dct['nodeName'] if nodeName != self.nodeName: msg = "nodeName mismatch: expected {!r}, got {!r}".format(self.nodeName, nodeName) if DEBUGGING: raise ValueError(msg) else: logger.warn(msg) return self._nodeSetValuesFromDict(dct) for childDct in dct.get('childItems', []): key = childDct['nodeName'] try: childCti = self.childByNodeName(key) except IndexError as _ex: logger.warn("Unable to set values for: {}".format(key)) else: childCti.setValuesFromDict(childDct)
python
def setValuesFromDict(self, dct): """ Recursively sets values from a dictionary created by getNonDefaultsDict. Does not raise exceptions (logs warnings instead) so that we can remove/rename node names in future Argos versions (or remove them) without breaking the application. Typically descendants should override _nodeSetValuesFromDict instead of this function. """ if 'nodeName' not in dct: return nodeName = dct['nodeName'] if nodeName != self.nodeName: msg = "nodeName mismatch: expected {!r}, got {!r}".format(self.nodeName, nodeName) if DEBUGGING: raise ValueError(msg) else: logger.warn(msg) return self._nodeSetValuesFromDict(dct) for childDct in dct.get('childItems', []): key = childDct['nodeName'] try: childCti = self.childByNodeName(key) except IndexError as _ex: logger.warn("Unable to set values for: {}".format(key)) else: childCti.setValuesFromDict(childDct)
Recursively sets values from a dictionary created by getNonDefaultsDict. Does not raise exceptions (logs warnings instead) so that we can remove/rename node names in future Argos versions (or remove them) without breaking the application. Typically descendants should override _nodeSetValuesFromDict instead of this function.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/abstractcti.py#L449-L478
titusjan/argos
argos/config/abstractcti.py
AbstractCtiEditor.finalize
def finalize(self): """ Called at clean up, when the editor is closed. Can be used to disconnect signals. This is often called after the client (e.g. the inspector) is updated. If you want to take action before the update, override prepareCommit instead. Be sure to call the finalize of the super class if you override this function. """ for subEditor in self._subEditors: self.removeSubEditor(subEditor) self.cti.model.sigItemChanged.disconnect(self.modelItemChanged) self.resetButton.clicked.disconnect(self.resetEditorValue) self.cti = None # just to make sure it's not used again. self.delegate = None
python
def finalize(self): """ Called at clean up, when the editor is closed. Can be used to disconnect signals. This is often called after the client (e.g. the inspector) is updated. If you want to take action before the update, override prepareCommit instead. Be sure to call the finalize of the super class if you override this function. """ for subEditor in self._subEditors: self.removeSubEditor(subEditor) self.cti.model.sigItemChanged.disconnect(self.modelItemChanged) self.resetButton.clicked.disconnect(self.resetEditorValue) self.cti = None # just to make sure it's not used again. self.delegate = None
Called at clean up, when the editor is closed. Can be used to disconnect signals. This is often called after the client (e.g. the inspector) is updated. If you want to take action before the update, override prepareCommit instead. Be sure to call the finalize of the super class if you override this function.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/abstractcti.py#L567-L579
titusjan/argos
argos/config/abstractcti.py
AbstractCtiEditor.addSubEditor
def addSubEditor(self, subEditor, isFocusProxy=False): """ Adds a sub editor to the layout (at the right but before the reset button) Will add the necessary event filter to handle tabs and sets the strong focus so that events will not propagate to the tree view. If isFocusProxy is True the sub editor will be the focus proxy of the CTI. """ self.hBoxLayout.insertWidget(len(self._subEditors), subEditor) self._subEditors.append(subEditor) subEditor.installEventFilter(self) subEditor.setFocusPolicy(Qt.StrongFocus) if isFocusProxy: self.setFocusProxy(subEditor) return subEditor
python
def addSubEditor(self, subEditor, isFocusProxy=False): """ Adds a sub editor to the layout (at the right but before the reset button) Will add the necessary event filter to handle tabs and sets the strong focus so that events will not propagate to the tree view. If isFocusProxy is True the sub editor will be the focus proxy of the CTI. """ self.hBoxLayout.insertWidget(len(self._subEditors), subEditor) self._subEditors.append(subEditor) subEditor.installEventFilter(self) subEditor.setFocusPolicy(Qt.StrongFocus) if isFocusProxy: self.setFocusProxy(subEditor) return subEditor
Adds a sub editor to the layout (at the right but before the reset button) Will add the necessary event filter to handle tabs and sets the strong focus so that events will not propagate to the tree view. If isFocusProxy is True the sub editor will be the focus proxy of the CTI.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/abstractcti.py#L590-L606
titusjan/argos
argos/config/abstractcti.py
AbstractCtiEditor.removeSubEditor
def removeSubEditor(self, subEditor): """ Removes the subEditor from the layout and removes the event filter. """ if subEditor is self.focusProxy(): self.setFocusProxy(None) subEditor.removeEventFilter(self) self._subEditors.remove(subEditor) self.hBoxLayout.removeWidget(subEditor)
python
def removeSubEditor(self, subEditor): """ Removes the subEditor from the layout and removes the event filter. """ if subEditor is self.focusProxy(): self.setFocusProxy(None) subEditor.removeEventFilter(self) self._subEditors.remove(subEditor) self.hBoxLayout.removeWidget(subEditor)
Removes the subEditor from the layout and removes the event filter.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/abstractcti.py#L609-L617
titusjan/argos
argos/config/abstractcti.py
AbstractCtiEditor.eventFilter
def eventFilter(self, watchedObject, event): """ Calls commitAndClose when the tab and back-tab are pressed. This is necessary because, normally the event filter of QStyledItemDelegate does this for us. However, that event filter works on this object, not on the sub editor. """ if event.type() == QtCore.QEvent.KeyPress: key = event.key() if key in (Qt.Key_Tab, Qt.Key_Backtab): self.commitAndClose() return True else: return False return super(AbstractCtiEditor, self).eventFilter(watchedObject, event)
python
def eventFilter(self, watchedObject, event): """ Calls commitAndClose when the tab and back-tab are pressed. This is necessary because, normally the event filter of QStyledItemDelegate does this for us. However, that event filter works on this object, not on the sub editor. """ if event.type() == QtCore.QEvent.KeyPress: key = event.key() if key in (Qt.Key_Tab, Qt.Key_Backtab): self.commitAndClose() return True else: return False return super(AbstractCtiEditor, self).eventFilter(watchedObject, event)
Calls commitAndClose when the tab and back-tab are pressed. This is necessary because, normally the event filter of QStyledItemDelegate does this for us. However, that event filter works on this object, not on the sub editor.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/abstractcti.py#L634-L647
titusjan/argos
argos/config/abstractcti.py
AbstractCtiEditor.modelItemChanged
def modelItemChanged(self, cti): """ Called when the an Config Tree Item (CTI) in the model has changed. If the CTI is a different one than the CTI that belongs to this editor, the editor is closed. This can happen if the user has checked a checkbox. Qt does not close other editors in the view in that case, so this is why we do it here. If the cti parameter is the CTI belonging to this editor, nothing is done. We don't close the editor because the user may want to continue editing. """ if cti is not self.cti: logger.debug("Another config tree item has changed: {}. Closing editor for {}" .format(cti, self.cti)) self.delegate.closeEditor.emit(self, QtWidgets.QAbstractItemDelegate.NoHint) # CLOSES SELF! else: logger.debug("Cti of this editor has changed: {}".format(cti))
python
def modelItemChanged(self, cti): """ Called when the an Config Tree Item (CTI) in the model has changed. If the CTI is a different one than the CTI that belongs to this editor, the editor is closed. This can happen if the user has checked a checkbox. Qt does not close other editors in the view in that case, so this is why we do it here. If the cti parameter is the CTI belonging to this editor, nothing is done. We don't close the editor because the user may want to continue editing. """ if cti is not self.cti: logger.debug("Another config tree item has changed: {}. Closing editor for {}" .format(cti, self.cti)) self.delegate.closeEditor.emit(self, QtWidgets.QAbstractItemDelegate.NoHint) # CLOSES SELF! else: logger.debug("Cti of this editor has changed: {}".format(cti))
Called when the an Config Tree Item (CTI) in the model has changed. If the CTI is a different one than the CTI that belongs to this editor, the editor is closed. This can happen if the user has checked a checkbox. Qt does not close other editors in the view in that case, so this is why we do it here. If the cti parameter is the CTI belonging to this editor, nothing is done. We don't close the editor because the user may want to continue editing.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/abstractcti.py#L651-L666
titusjan/argos
argos/config/abstractcti.py
AbstractCtiEditor.commitAndClose
def commitAndClose(self): """ Commits the data of the sub editor and instructs the delegate to close this ctiEditor. The delegate will emit the closeEditor signal which is connected to the closeEditor method of the ConfigTreeView class. This, in turn will, call the finalize method of this object so that signals can be disconnected and resources can be freed. This is complicated but I don't see a simpler solution. """ if self.delegate: self.delegate.commitData.emit(self) self.delegate.closeEditor.emit(self, QtWidgets.QAbstractItemDelegate.NoHint) # CLOSES SELF! else: # QAbstractItemView.closeEditor is sometimes called directly, without the # QAbstractItemDelegate.closeEditor signal begin emitted, e.g when the currentItem # changes. Therefore the commitAndClose method can be called twice, if we call it # explicitly as well (e.g. in FontCtiEditor.execFontDialog(). We guard against this. logger.debug("AbstractCtiEditor.commitAndClose: editor already closed (ignored).")
python
def commitAndClose(self): """ Commits the data of the sub editor and instructs the delegate to close this ctiEditor. The delegate will emit the closeEditor signal which is connected to the closeEditor method of the ConfigTreeView class. This, in turn will, call the finalize method of this object so that signals can be disconnected and resources can be freed. This is complicated but I don't see a simpler solution. """ if self.delegate: self.delegate.commitData.emit(self) self.delegate.closeEditor.emit(self, QtWidgets.QAbstractItemDelegate.NoHint) # CLOSES SELF! else: # QAbstractItemView.closeEditor is sometimes called directly, without the # QAbstractItemDelegate.closeEditor signal begin emitted, e.g when the currentItem # changes. Therefore the commitAndClose method can be called twice, if we call it # explicitly as well (e.g. in FontCtiEditor.execFontDialog(). We guard against this. logger.debug("AbstractCtiEditor.commitAndClose: editor already closed (ignored).")
Commits the data of the sub editor and instructs the delegate to close this ctiEditor. The delegate will emit the closeEditor signal which is connected to the closeEditor method of the ConfigTreeView class. This, in turn will, call the finalize method of this object so that signals can be disconnected and resources can be freed. This is complicated but I don't see a simpler solution.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/abstractcti.py#L670-L686
titusjan/argos
argos/config/abstractcti.py
AbstractCtiEditor.resetEditorValue
def resetEditorValue(self, checked=False): """ Resets the editor to the default value. Also resets the children. """ # Block all signals to prevent duplicate inspector updates. # No need to restore, the editors will be deleted after the reset. for subEditor in self._subEditors: subEditor.blockSignals(True) self.cti.resetToDefault(resetChildren=True) # This will commit the children as well. self.setData(self.cti.defaultData) self.commitAndClose()
python
def resetEditorValue(self, checked=False): """ Resets the editor to the default value. Also resets the children. """ # Block all signals to prevent duplicate inspector updates. # No need to restore, the editors will be deleted after the reset. for subEditor in self._subEditors: subEditor.blockSignals(True) self.cti.resetToDefault(resetChildren=True) # This will commit the children as well. self.setData(self.cti.defaultData) self.commitAndClose()
Resets the editor to the default value. Also resets the children.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/abstractcti.py#L690-L701
titusjan/argos
argos/config/abstractcti.py
AbstractCtiEditor.paintEvent
def paintEvent(self, event): """ Reimplementation of paintEvent to allow for style sheets See: http://qt-project.org/wiki/How_to_Change_the_Background_Color_of_QWidget """ opt = QtWidgets.QStyleOption() opt.initFrom(self) painter = QtGui.QPainter(self) self.style().drawPrimitive(QtWidgets.QStyle.PE_Widget, opt, painter, self) painter.end()
python
def paintEvent(self, event): """ Reimplementation of paintEvent to allow for style sheets See: http://qt-project.org/wiki/How_to_Change_the_Background_Color_of_QWidget """ opt = QtWidgets.QStyleOption() opt.initFrom(self) painter = QtGui.QPainter(self) self.style().drawPrimitive(QtWidgets.QStyle.PE_Widget, opt, painter, self) painter.end()
Reimplementation of paintEvent to allow for style sheets See: http://qt-project.org/wiki/How_to_Change_the_Background_Color_of_QWidget
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/abstractcti.py#L704-L712
titusjan/argos
argos/widgets/display.py
MessageDisplay.setError
def setError(self, msg=None, title=None): """ Shows and error message """ if msg is not None: self.messageLabel.setText(msg) if title is not None: self.titleLabel.setText(title)
python
def setError(self, msg=None, title=None): """ Shows and error message """ if msg is not None: self.messageLabel.setText(msg) if title is not None: self.titleLabel.setText(title)
Shows and error message
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/display.py#L66-L73
titusjan/argos
argos/inspector/qtplugins/table.py
resizeAllSections
def resizeAllSections(header, sectionSize): """ Sets all sections (columns or rows) of a header to the same section size. :param header: a QHeaderView :param sectionSize: the new size of the header section in pixels """ for idx in range(header.length()): header.resizeSection(idx, sectionSize)
python
def resizeAllSections(header, sectionSize): """ Sets all sections (columns or rows) of a header to the same section size. :param header: a QHeaderView :param sectionSize: the new size of the header section in pixels """ for idx in range(header.length()): header.resizeSection(idx, sectionSize)
Sets all sections (columns or rows) of a header to the same section size. :param header: a QHeaderView :param sectionSize: the new size of the header section in pixels
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/qtplugins/table.py#L48-L55
titusjan/argos
argos/inspector/qtplugins/table.py
makeReplacementField
def makeReplacementField(formatSpec, altFormatSpec='', testValue=None): """ Prepends a colon and wraps the formatSpec in curly braces to yield a replacement field. The format specification is part of a replacement field, which can be used in new-style string formatting. See: https://docs.python.org/3/library/string.html#format-string-syntax https://docs.python.org/3/library/string.html#format-specification-mini-language If the formatSpec does not contain a a color or exclamation mark, a colon is prepended. If the formatSpec starts and end in quotes (single or double) only the quotes are removed, no curly braces or colon charactes are added. This allows users to define a format spec. :param formatSpec: e.g. '5.2f' will return '{:5.2f}' :param altFormatSpec: alternative that will be used if the formatSpec evaluates to False :param testValue: if not None, result.format(testValue) will be evaluated as a test. :return: string """ check_is_a_string(formatSpec) check_is_a_string(altFormatSpec) fmt = altFormatSpec if not formatSpec else formatSpec if is_quoted(fmt): fmt = fmt[1:-1] # remove quotes else: if fmt and ':' not in fmt and '!' not in fmt: fmt = ':' + fmt fmt = '{' + fmt + '}' # Test resulting replacement field if testValue is not None: try: _dummy = fmt.format(testValue) except Exception: msg = ("Format specifier failed: replacement-field={!r}, test-value={!r}" .format(fmt, testValue)) logger.error(msg) raise ValueError(msg) logger.debug("Resulting replacement field: {!r}".format(fmt)) return fmt
python
def makeReplacementField(formatSpec, altFormatSpec='', testValue=None): """ Prepends a colon and wraps the formatSpec in curly braces to yield a replacement field. The format specification is part of a replacement field, which can be used in new-style string formatting. See: https://docs.python.org/3/library/string.html#format-string-syntax https://docs.python.org/3/library/string.html#format-specification-mini-language If the formatSpec does not contain a a color or exclamation mark, a colon is prepended. If the formatSpec starts and end in quotes (single or double) only the quotes are removed, no curly braces or colon charactes are added. This allows users to define a format spec. :param formatSpec: e.g. '5.2f' will return '{:5.2f}' :param altFormatSpec: alternative that will be used if the formatSpec evaluates to False :param testValue: if not None, result.format(testValue) will be evaluated as a test. :return: string """ check_is_a_string(formatSpec) check_is_a_string(altFormatSpec) fmt = altFormatSpec if not formatSpec else formatSpec if is_quoted(fmt): fmt = fmt[1:-1] # remove quotes else: if fmt and ':' not in fmt and '!' not in fmt: fmt = ':' + fmt fmt = '{' + fmt + '}' # Test resulting replacement field if testValue is not None: try: _dummy = fmt.format(testValue) except Exception: msg = ("Format specifier failed: replacement-field={!r}, test-value={!r}" .format(fmt, testValue)) logger.error(msg) raise ValueError(msg) logger.debug("Resulting replacement field: {!r}".format(fmt)) return fmt
Prepends a colon and wraps the formatSpec in curly braces to yield a replacement field. The format specification is part of a replacement field, which can be used in new-style string formatting. See: https://docs.python.org/3/library/string.html#format-string-syntax https://docs.python.org/3/library/string.html#format-specification-mini-language If the formatSpec does not contain a a color or exclamation mark, a colon is prepended. If the formatSpec starts and end in quotes (single or double) only the quotes are removed, no curly braces or colon charactes are added. This allows users to define a format spec. :param formatSpec: e.g. '5.2f' will return '{:5.2f}' :param altFormatSpec: alternative that will be used if the formatSpec evaluates to False :param testValue: if not None, result.format(testValue) will be evaluated as a test. :return: string
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/qtplugins/table.py#L58-L98
titusjan/argos
argos/inspector/qtplugins/table.py
TableInspectorCti._refreshNodeFromTarget
def _refreshNodeFromTarget(self): """ Refreshes the TableInspectorCti from the TableInspector target it monitors. Disables auto-sizing of the header sizes for very large headers (> 10000 elements). Otherwise the resizing may take to long and the program will hang. """ tableModel = self.tableInspector.model # Disable row height and column with settings for large headers (too slow otherwise) if tableModel.rowCount() >= RESET_HEADERS_AT_SIZE: self.autoRowHeightCti.data = False self.model.emitDataChanged(self.autoRowHeightCti) self.autoRowHeightCti.enable = False else: self.autoRowHeightCti.enable = True if tableModel.columnCount() >= RESET_HEADERS_AT_SIZE: self.autoColWidthCti.data = False self.model.emitDataChanged(self.autoColWidthCti) self.autoColWidthCti.enable = False else: self.autoColWidthCti.enable = True
python
def _refreshNodeFromTarget(self): """ Refreshes the TableInspectorCti from the TableInspector target it monitors. Disables auto-sizing of the header sizes for very large headers (> 10000 elements). Otherwise the resizing may take to long and the program will hang. """ tableModel = self.tableInspector.model # Disable row height and column with settings for large headers (too slow otherwise) if tableModel.rowCount() >= RESET_HEADERS_AT_SIZE: self.autoRowHeightCti.data = False self.model.emitDataChanged(self.autoRowHeightCti) self.autoRowHeightCti.enable = False else: self.autoRowHeightCti.enable = True if tableModel.columnCount() >= RESET_HEADERS_AT_SIZE: self.autoColWidthCti.data = False self.model.emitDataChanged(self.autoColWidthCti) self.autoColWidthCti.enable = False else: self.autoColWidthCti.enable = True
Refreshes the TableInspectorCti from the TableInspector target it monitors. Disables auto-sizing of the header sizes for very large headers (> 10000 elements). Otherwise the resizing may take to long and the program will hang.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/qtplugins/table.py#L187-L208
titusjan/argos
argos/inspector/qtplugins/table.py
TableInspector._drawContents
def _drawContents(self, reason=None, initiator=None): """ Draws the table contents from the sliced array of the collected repo tree item. See AbstractInspector.updateContents for the reason and initiator description. """ logger.debug("TableInspector._drawContents: {}".format(self)) oldTableIndex = self.tableView.currentIndex() if oldTableIndex.isValid(): selectionWasValid = True # Defensive programming, keep old value just in case oldRow = oldTableIndex.row() oldCol = oldTableIndex.column() else: selectionWasValid = False oldRow = 0 oldCol = 0 self.model.updateState(self.collector.getSlicedArray(), self.collector.rtiInfo, self.configValue('separate fields')) self.model.encoding = self.config.encodingCti.configValue self.model.horAlignment = self.config.horAlignCti.configValue self.model.verAlignment = self.config.verAlignCti.configValue self.model.dataColor = self.config.dataColorCti.configValue self.model.missingColor = self.config.missingColorCti.configValue self.model.strFormat = makeReplacementField(self.config.strFormatCti.configValue, testValue='my_string') self.model.intFormat = makeReplacementField(self.config.intFormatCti.configValue, testValue=0) self.model.numFormat = makeReplacementField(self.config.numFormatCti.configValue, testValue=0.0) self.model.otherFormat = makeReplacementField(self.config.otherFormatCti.configValue, testValue=None) self.model.maskFormat = makeReplacementField(self.config.maskFormatCti.configValue, testValue=None) scrollMode = self.configValue("scroll") self.tableView.setHorizontalScrollMode(scrollMode) self.tableView.setVerticalScrollMode(scrollMode) self.tableView.setWordWrap(self.configValue('word wrap')) # Update the model font from the font config item (will call self.setFont) self.config.updateTarget() verHeader = self.tableView.verticalHeader() if (self.config.autoRowHeightCti.configValue and self.model.rowCount() < RESET_HEADERS_AT_SIZE): numCells = self.model.rowCount() * self.model.columnCount() if numCells <= OPTIMIZE_RESIZE_AT_SIZE: logger.debug("Setting vertical resize mode to ResizeToContents") verHeader.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents) else: # ResizeToContents can be very slow because it gets all rows. # Work around: resize only first row and columns and apply this to all rows/cols # TODO: perhaps use SizeHintRole? logger.warning("Performance work around: for tables with more than 1000 cells " + "only the current row is resized and the others use that size.") verHeader.setSectionResizeMode(QtWidgets.QHeaderView.Interactive) self.tableView.resizeRowToContents(oldRow) resizeAllSections(verHeader, self.tableView.rowHeight(oldRow)) else: logger.debug("Setting vertical resize mode to Interactive and reset header") verHeader.setSectionResizeMode(QtWidgets.QHeaderView.Interactive) verHeader.setDefaultSectionSize(self.config.defaultRowHeightCti.configValue) verHeader.reset() horHeader = self.tableView.horizontalHeader() if (self.config.autoColWidthCti.configValue and self.model.columnCount() < RESET_HEADERS_AT_SIZE): numCells = self.model.rowCount() * self.model.columnCount() if numCells <= OPTIMIZE_RESIZE_AT_SIZE: logger.debug("setting horizontal resize mode to ResizeToContents") horHeader.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents) else: # ResizeToContents can be very slow because it gets all rows. # Work around: resize only first row and columns and apply this to all rows/cols # TODO: perhaps use SizeHintRole? logger.warning("Performance work around: for tables with more than 1000 cells " + "only the current column is resized and the others use that size.") horHeader.setSectionResizeMode(QtWidgets.QHeaderView.Interactive) self.tableView.resizeColumnToContents(oldCol) resizeAllSections(horHeader, self.tableView.columnWidth(oldCol)) else: logger.debug("Setting horizontal resize mode to Interactive and reset header") horHeader.setSectionResizeMode(QtWidgets.QHeaderView.Interactive) resizeAllSections(horHeader, self.config.defaultColWidthCti.configValue) horHeader.reset() # Restore selection after select if selectionWasValid: newIndex = self.model.index(oldRow, oldCol) if newIndex.isValid(): logger.debug("Restoring selection: row={}, col={}".format(oldRow, oldCol)) self.tableView.setCurrentIndex(newIndex) else: logger.debug("Can't restore selection")
python
def _drawContents(self, reason=None, initiator=None): """ Draws the table contents from the sliced array of the collected repo tree item. See AbstractInspector.updateContents for the reason and initiator description. """ logger.debug("TableInspector._drawContents: {}".format(self)) oldTableIndex = self.tableView.currentIndex() if oldTableIndex.isValid(): selectionWasValid = True # Defensive programming, keep old value just in case oldRow = oldTableIndex.row() oldCol = oldTableIndex.column() else: selectionWasValid = False oldRow = 0 oldCol = 0 self.model.updateState(self.collector.getSlicedArray(), self.collector.rtiInfo, self.configValue('separate fields')) self.model.encoding = self.config.encodingCti.configValue self.model.horAlignment = self.config.horAlignCti.configValue self.model.verAlignment = self.config.verAlignCti.configValue self.model.dataColor = self.config.dataColorCti.configValue self.model.missingColor = self.config.missingColorCti.configValue self.model.strFormat = makeReplacementField(self.config.strFormatCti.configValue, testValue='my_string') self.model.intFormat = makeReplacementField(self.config.intFormatCti.configValue, testValue=0) self.model.numFormat = makeReplacementField(self.config.numFormatCti.configValue, testValue=0.0) self.model.otherFormat = makeReplacementField(self.config.otherFormatCti.configValue, testValue=None) self.model.maskFormat = makeReplacementField(self.config.maskFormatCti.configValue, testValue=None) scrollMode = self.configValue("scroll") self.tableView.setHorizontalScrollMode(scrollMode) self.tableView.setVerticalScrollMode(scrollMode) self.tableView.setWordWrap(self.configValue('word wrap')) # Update the model font from the font config item (will call self.setFont) self.config.updateTarget() verHeader = self.tableView.verticalHeader() if (self.config.autoRowHeightCti.configValue and self.model.rowCount() < RESET_HEADERS_AT_SIZE): numCells = self.model.rowCount() * self.model.columnCount() if numCells <= OPTIMIZE_RESIZE_AT_SIZE: logger.debug("Setting vertical resize mode to ResizeToContents") verHeader.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents) else: # ResizeToContents can be very slow because it gets all rows. # Work around: resize only first row and columns and apply this to all rows/cols # TODO: perhaps use SizeHintRole? logger.warning("Performance work around: for tables with more than 1000 cells " + "only the current row is resized and the others use that size.") verHeader.setSectionResizeMode(QtWidgets.QHeaderView.Interactive) self.tableView.resizeRowToContents(oldRow) resizeAllSections(verHeader, self.tableView.rowHeight(oldRow)) else: logger.debug("Setting vertical resize mode to Interactive and reset header") verHeader.setSectionResizeMode(QtWidgets.QHeaderView.Interactive) verHeader.setDefaultSectionSize(self.config.defaultRowHeightCti.configValue) verHeader.reset() horHeader = self.tableView.horizontalHeader() if (self.config.autoColWidthCti.configValue and self.model.columnCount() < RESET_HEADERS_AT_SIZE): numCells = self.model.rowCount() * self.model.columnCount() if numCells <= OPTIMIZE_RESIZE_AT_SIZE: logger.debug("setting horizontal resize mode to ResizeToContents") horHeader.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents) else: # ResizeToContents can be very slow because it gets all rows. # Work around: resize only first row and columns and apply this to all rows/cols # TODO: perhaps use SizeHintRole? logger.warning("Performance work around: for tables with more than 1000 cells " + "only the current column is resized and the others use that size.") horHeader.setSectionResizeMode(QtWidgets.QHeaderView.Interactive) self.tableView.resizeColumnToContents(oldCol) resizeAllSections(horHeader, self.tableView.columnWidth(oldCol)) else: logger.debug("Setting horizontal resize mode to Interactive and reset header") horHeader.setSectionResizeMode(QtWidgets.QHeaderView.Interactive) resizeAllSections(horHeader, self.config.defaultColWidthCti.configValue) horHeader.reset() # Restore selection after select if selectionWasValid: newIndex = self.model.index(oldRow, oldCol) if newIndex.isValid(): logger.debug("Restoring selection: row={}, col={}".format(oldRow, oldCol)) self.tableView.setCurrentIndex(newIndex) else: logger.debug("Can't restore selection")
Draws the table contents from the sliced array of the collected repo tree item. See AbstractInspector.updateContents for the reason and initiator description.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/qtplugins/table.py#L267-L366
titusjan/argos
argos/inspector/qtplugins/table.py
TableInspectorModel.updateState
def updateState(self, slicedArray, rtiInfo, separateFields): """ Sets the slicedArray and rtiInfo and other members. This will reset the model. Will be called from the tableInspector._drawContents. """ self.beginResetModel() try: # The sliced array can be a masked array or a (regular) numpy array. # The table works fine with masked arrays, no need to replace the masked values. self._slicedArray = slicedArray if slicedArray is None: self._nRows = 0 self._nCols = 0 self._fieldNames = [] else: self._nRows, self._nCols = self._slicedArray.shape if self._slicedArray.data.dtype.names: self._fieldNames = self._slicedArray.data.dtype.names else: self._fieldNames = [] self._rtiInfo = rtiInfo self._separateFields = separateFields # Don't put numbers in the header if the record is of structured type, fields are # placed in separate cells and the fake dimension is selected (combo index 0) if self._separateFields and self._fieldNames: if self._rtiInfo['x-dim'] == FAKE_DIM_NAME: self._separateFieldOrientation = Qt.Horizontal self._numbersInHeader = False elif self._rtiInfo['y-dim'] == FAKE_DIM_NAME: self._separateFieldOrientation = Qt.Vertical self._numbersInHeader = False else: self._separateFieldOrientation = Qt.Horizontal self._numbersInHeader = True else: self._separateFieldOrientation = None self._numbersInHeader = True finally: self.endResetModel()
python
def updateState(self, slicedArray, rtiInfo, separateFields): """ Sets the slicedArray and rtiInfo and other members. This will reset the model. Will be called from the tableInspector._drawContents. """ self.beginResetModel() try: # The sliced array can be a masked array or a (regular) numpy array. # The table works fine with masked arrays, no need to replace the masked values. self._slicedArray = slicedArray if slicedArray is None: self._nRows = 0 self._nCols = 0 self._fieldNames = [] else: self._nRows, self._nCols = self._slicedArray.shape if self._slicedArray.data.dtype.names: self._fieldNames = self._slicedArray.data.dtype.names else: self._fieldNames = [] self._rtiInfo = rtiInfo self._separateFields = separateFields # Don't put numbers in the header if the record is of structured type, fields are # placed in separate cells and the fake dimension is selected (combo index 0) if self._separateFields and self._fieldNames: if self._rtiInfo['x-dim'] == FAKE_DIM_NAME: self._separateFieldOrientation = Qt.Horizontal self._numbersInHeader = False elif self._rtiInfo['y-dim'] == FAKE_DIM_NAME: self._separateFieldOrientation = Qt.Vertical self._numbersInHeader = False else: self._separateFieldOrientation = Qt.Horizontal self._numbersInHeader = True else: self._separateFieldOrientation = None self._numbersInHeader = True finally: self.endResetModel()
Sets the slicedArray and rtiInfo and other members. This will reset the model. Will be called from the tableInspector._drawContents.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/qtplugins/table.py#L404-L446
titusjan/argos
argos/inspector/qtplugins/table.py
TableInspectorModel._cellValue
def _cellValue(self, index): """ Returns the data value of the cell at the index (without any string conversion) """ row = index.row() col = index.column() if (row < 0 or row >= self.rowCount() or col < 0 or col >= self.columnCount()): return None # The check above should have returned None if the sliced array is None assert self._slicedArray is not None, "Sanity check failed." nFields = len(self._fieldNames) data = self._slicedArray.data if self._separateFieldOrientation == Qt.Horizontal: dataValue = data[row, col // nFields][self._fieldNames[col % nFields]] elif self._separateFieldOrientation == Qt.Vertical: dataValue = data[row // nFields, col][self._fieldNames[row % nFields]] else: dataValue = data[row, col] return dataValue
python
def _cellValue(self, index): """ Returns the data value of the cell at the index (without any string conversion) """ row = index.row() col = index.column() if (row < 0 or row >= self.rowCount() or col < 0 or col >= self.columnCount()): return None # The check above should have returned None if the sliced array is None assert self._slicedArray is not None, "Sanity check failed." nFields = len(self._fieldNames) data = self._slicedArray.data if self._separateFieldOrientation == Qt.Horizontal: dataValue = data[row, col // nFields][self._fieldNames[col % nFields]] elif self._separateFieldOrientation == Qt.Vertical: dataValue = data[row // nFields, col][self._fieldNames[row % nFields]] else: dataValue = data[row, col] return dataValue
Returns the data value of the cell at the index (without any string conversion)
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/qtplugins/table.py#L449-L470
titusjan/argos
argos/inspector/qtplugins/table.py
TableInspectorModel._cellMask
def _cellMask(self, index): """ Returns the data mask of the cell at the index (without any string conversion) """ row = index.row() col = index.column() if (row < 0 or row >= self.rowCount() or col < 0 or col >= self.columnCount()): return None # The check above should have returned None if the sliced array is None assert self._slicedArray is not None, "Sanity check failed." nFields = len(self._fieldNames) mask = self._slicedArray.mask if is_an_array(mask): if self._separateFieldOrientation == Qt.Horizontal: maskValue = mask[row, col // nFields][self._fieldNames[col % nFields]] elif self._separateFieldOrientation == Qt.Vertical: maskValue = mask[row // nFields, col][self._fieldNames[row % nFields]] else: maskValue = mask[row, col] else: maskValue = mask # Here maskValue can still be a list in case of structured arrays. It can even still be # a numpy array in case of a structured array with sub arrays as fields if is_an_array(maskValue): allMasked = np.all(maskValue) else: try: allMasked = all(maskValue) except TypeError as ex: allMasked = bool(maskValue) return allMasked
python
def _cellMask(self, index): """ Returns the data mask of the cell at the index (without any string conversion) """ row = index.row() col = index.column() if (row < 0 or row >= self.rowCount() or col < 0 or col >= self.columnCount()): return None # The check above should have returned None if the sliced array is None assert self._slicedArray is not None, "Sanity check failed." nFields = len(self._fieldNames) mask = self._slicedArray.mask if is_an_array(mask): if self._separateFieldOrientation == Qt.Horizontal: maskValue = mask[row, col // nFields][self._fieldNames[col % nFields]] elif self._separateFieldOrientation == Qt.Vertical: maskValue = mask[row // nFields, col][self._fieldNames[row % nFields]] else: maskValue = mask[row, col] else: maskValue = mask # Here maskValue can still be a list in case of structured arrays. It can even still be # a numpy array in case of a structured array with sub arrays as fields if is_an_array(maskValue): allMasked = np.all(maskValue) else: try: allMasked = all(maskValue) except TypeError as ex: allMasked = bool(maskValue) return allMasked
Returns the data mask of the cell at the index (without any string conversion)
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/qtplugins/table.py#L473-L506
titusjan/argos
argos/inspector/qtplugins/table.py
TableInspectorModel.data
def data(self, index, role = Qt.DisplayRole): """ Returns the data at an index for a certain role """ try: if role == Qt.DisplayRole: return to_string(self._cellValue(index), masked=self._cellMask(index), decode_bytes=self.encoding, maskFormat=self.maskFormat, strFormat=self.strFormat, intFormat=self.intFormat, numFormat=self.numFormat, otherFormat=self.otherFormat) elif role == Qt.FontRole: #assert self._font, "Font undefined" return self._font elif role == Qt.TextColorRole: masked = self._cellMask(index) if not is_an_array(masked) and masked: return self.missingColor else: return self.dataColor elif role == Qt.TextAlignmentRole: if self.horAlignment == ALIGN_SMART: cellContainsNumber = isinstance(self._cellValue(index), numbers.Number) horAlign = Qt.AlignRight if cellContainsNumber else Qt.AlignLeft return horAlign | self.verAlignment else: return self.horAlignment | self.verAlignment else: return None except Exception as ex: logger.error("Slot is not exception-safe.") logger.exception(ex) if DEBUGGING: raise
python
def data(self, index, role = Qt.DisplayRole): """ Returns the data at an index for a certain role """ try: if role == Qt.DisplayRole: return to_string(self._cellValue(index), masked=self._cellMask(index), decode_bytes=self.encoding, maskFormat=self.maskFormat, strFormat=self.strFormat, intFormat=self.intFormat, numFormat=self.numFormat, otherFormat=self.otherFormat) elif role == Qt.FontRole: #assert self._font, "Font undefined" return self._font elif role == Qt.TextColorRole: masked = self._cellMask(index) if not is_an_array(masked) and masked: return self.missingColor else: return self.dataColor elif role == Qt.TextAlignmentRole: if self.horAlignment == ALIGN_SMART: cellContainsNumber = isinstance(self._cellValue(index), numbers.Number) horAlign = Qt.AlignRight if cellContainsNumber else Qt.AlignLeft return horAlign | self.verAlignment else: return self.horAlignment | self.verAlignment else: return None except Exception as ex: logger.error("Slot is not exception-safe.") logger.exception(ex) if DEBUGGING: raise
Returns the data at an index for a certain role
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/qtplugins/table.py#L509-L544
titusjan/argos
argos/inspector/qtplugins/table.py
TableInspectorModel.headerData
def headerData(self, section, orientation, role): """ Returns the header for a section (row or column depending on orientation). Reimplemented from QAbstractTableModel to make the headers start at 0. """ if role == Qt.DisplayRole: if self._separateFieldOrientation == orientation: nFields = len(self._fieldNames) varNr = section // nFields fieldNr = section % nFields header = str(varNr) + ' : ' if self._numbersInHeader else '' header += self._fieldNames[fieldNr] return header else: return str(section) else: return None
python
def headerData(self, section, orientation, role): """ Returns the header for a section (row or column depending on orientation). Reimplemented from QAbstractTableModel to make the headers start at 0. """ if role == Qt.DisplayRole: if self._separateFieldOrientation == orientation: nFields = len(self._fieldNames) varNr = section // nFields fieldNr = section % nFields header = str(varNr) + ' : ' if self._numbersInHeader else '' header += self._fieldNames[fieldNr] return header else: return str(section) else: return None
Returns the header for a section (row or column depending on orientation). Reimplemented from QAbstractTableModel to make the headers start at 0.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/qtplugins/table.py#L553-L569
titusjan/argos
argos/inspector/qtplugins/table.py
TableInspectorModel.rowCount
def rowCount(self, parent=None): """ The number of rows of the sliced array. The 'parent' parameter can be a QModelIndex. It is ignored since the number of rows does not depend on the parent. """ if self._separateFieldOrientation == Qt.Vertical: return self._nRows * len(self._fieldNames) else: return self._nRows
python
def rowCount(self, parent=None): """ The number of rows of the sliced array. The 'parent' parameter can be a QModelIndex. It is ignored since the number of rows does not depend on the parent. """ if self._separateFieldOrientation == Qt.Vertical: return self._nRows * len(self._fieldNames) else: return self._nRows
The number of rows of the sliced array. The 'parent' parameter can be a QModelIndex. It is ignored since the number of rows does not depend on the parent.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/qtplugins/table.py#L572-L580
titusjan/argos
argos/inspector/qtplugins/table.py
TableInspectorModel.columnCount
def columnCount(self, parent=None): """ The number of columns of the sliced array. The 'parent' parameter can be a QModelIndex. It is ignored since the number of columns does not depend on the parent. """ if self._separateFieldOrientation == Qt.Horizontal: return self._nCols * len(self._fieldNames) else: return self._nCols
python
def columnCount(self, parent=None): """ The number of columns of the sliced array. The 'parent' parameter can be a QModelIndex. It is ignored since the number of columns does not depend on the parent. """ if self._separateFieldOrientation == Qt.Horizontal: return self._nCols * len(self._fieldNames) else: return self._nCols
The number of columns of the sliced array. The 'parent' parameter can be a QModelIndex. It is ignored since the number of columns does not depend on the parent.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/qtplugins/table.py#L583-L591
titusjan/argos
argos/inspector/qtplugins/table.py
TableInspectorModel.setFont
def setFont(self, font): """ Sets the font that will be returned when data() is called with the Qt.FontRole. Can be a QFont or None if no font is set. """ check_class(font, QtGui.QFont, allow_none=True) self._font = font
python
def setFont(self, font): """ Sets the font that will be returned when data() is called with the Qt.FontRole. Can be a QFont or None if no font is set. """ check_class(font, QtGui.QFont, allow_none=True) self._font = font
Sets the font that will be returned when data() is called with the Qt.FontRole. Can be a QFont or None if no font is set.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/qtplugins/table.py#L601-L606
titusjan/argos
argos/inspector/pgplugins/pgctis.py
viewBoxAxisRange
def viewBoxAxisRange(viewBox, axisNumber): """ Calculates the range of an axis of a viewBox. """ rect = viewBox.childrenBoundingRect() # taken from viewBox.autoRange() if rect is not None: if axisNumber == X_AXIS: return rect.left(), rect.right() elif axisNumber == Y_AXIS: return rect.bottom(), rect.top() else: raise ValueError("axisNumber should be 0 or 1, got: {}".format(axisNumber)) else: # Does this happen? Probably when the plot is empty. raise AssertionError("No children bbox. Plot range not updated.")
python
def viewBoxAxisRange(viewBox, axisNumber): """ Calculates the range of an axis of a viewBox. """ rect = viewBox.childrenBoundingRect() # taken from viewBox.autoRange() if rect is not None: if axisNumber == X_AXIS: return rect.left(), rect.right() elif axisNumber == Y_AXIS: return rect.bottom(), rect.top() else: raise ValueError("axisNumber should be 0 or 1, got: {}".format(axisNumber)) else: # Does this happen? Probably when the plot is empty. raise AssertionError("No children bbox. Plot range not updated.")
Calculates the range of an axis of a viewBox.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L113-L126
titusjan/argos
argos/inspector/pgplugins/pgctis.py
inspectorDataRange
def inspectorDataRange(inspector, percentage): """ Calculates the range from the inspectors' sliced array. Discards percentage of the minimum and percentage of the maximum values of the inspector.slicedArray Meant to be used with functools.partial for filling the autorange methods combobox. The first parameter is an inspector, it's not an array, because we would then have to regenerate the range function every time sliced array of an inspector changes. """ logger.debug("Discarding {}% from id: {}".format(percentage, id(inspector.slicedArray))) return maskedNanPercentile(inspector.slicedArray, (percentage, 100-percentage) )
python
def inspectorDataRange(inspector, percentage): """ Calculates the range from the inspectors' sliced array. Discards percentage of the minimum and percentage of the maximum values of the inspector.slicedArray Meant to be used with functools.partial for filling the autorange methods combobox. The first parameter is an inspector, it's not an array, because we would then have to regenerate the range function every time sliced array of an inspector changes. """ logger.debug("Discarding {}% from id: {}".format(percentage, id(inspector.slicedArray))) return maskedNanPercentile(inspector.slicedArray, (percentage, 100-percentage) )
Calculates the range from the inspectors' sliced array. Discards percentage of the minimum and percentage of the maximum values of the inspector.slicedArray Meant to be used with functools.partial for filling the autorange methods combobox. The first parameter is an inspector, it's not an array, because we would then have to regenerate the range function every time sliced array of an inspector changes.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L129-L138
titusjan/argos
argos/inspector/pgplugins/pgctis.py
defaultAutoRangeMethods
def defaultAutoRangeMethods(inspector, intialItems=None): """ Creates an ordered dict with default autorange methods for an inspector. :param inspector: the range methods will work on (the sliced array) of this inspector. :param intialItems: will be passed on to the OrderedDict constructor. """ rangeFunctions = OrderedDict({} if intialItems is None else intialItems) rangeFunctions['use all data'] = partial(inspectorDataRange, inspector, 0.0) for percentage in [0.1, 0.2, 0.5, 1, 2, 5, 10, 20]: label = "discard {}%".format(percentage) rangeFunctions[label] = partial(inspectorDataRange, inspector, percentage) return rangeFunctions
python
def defaultAutoRangeMethods(inspector, intialItems=None): """ Creates an ordered dict with default autorange methods for an inspector. :param inspector: the range methods will work on (the sliced array) of this inspector. :param intialItems: will be passed on to the OrderedDict constructor. """ rangeFunctions = OrderedDict({} if intialItems is None else intialItems) rangeFunctions['use all data'] = partial(inspectorDataRange, inspector, 0.0) for percentage in [0.1, 0.2, 0.5, 1, 2, 5, 10, 20]: label = "discard {}%".format(percentage) rangeFunctions[label] = partial(inspectorDataRange, inspector, percentage) return rangeFunctions
Creates an ordered dict with default autorange methods for an inspector. :param inspector: the range methods will work on (the sliced array) of this inspector. :param intialItems: will be passed on to the OrderedDict constructor.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L141-L152
titusjan/argos
argos/inspector/pgplugins/pgctis.py
setXYAxesAutoRangeOn
def setXYAxesAutoRangeOn(commonCti, xAxisRangeCti, yAxisRangeCti, axisNumber): """ Turns on the auto range of an X and Y axis simultaneously. It sets the autoRangeCti.data of the xAxisRangeCti and yAxisRangeCti to True. After that, it emits the sigItemChanged signal of the commonCti. Can be used with functools.partial to make a slot that atomically resets the X and Y axis. That is, only one sigItemChanged will be emitted. This function is necessary because, if one would call PgAxisRangeCti.sigItemChanged separately on the X and Y axes the sigItemChanged signal would be emitted twice. This in not only slower, but autoscaling one axis may slightly change the others range, so the second call to sigItemChanged may unset the autorange of the first. axisNumber must be one of: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes). """ assert axisNumber in VALID_AXIS_NUMBERS, \ "Axis number should be one of {}, got {}".format(VALID_AXIS_NUMBERS, axisNumber) logger.debug("setXYAxesAutoRangeOn, axisNumber: {}".format(axisNumber)) if axisNumber == X_AXIS or axisNumber == BOTH_AXES: xAxisRangeCti.autoRangeCti.data = True if axisNumber == Y_AXIS or axisNumber == BOTH_AXES: yAxisRangeCti.autoRangeCti.data = True commonCti.model.sigItemChanged.emit(commonCti)
python
def setXYAxesAutoRangeOn(commonCti, xAxisRangeCti, yAxisRangeCti, axisNumber): """ Turns on the auto range of an X and Y axis simultaneously. It sets the autoRangeCti.data of the xAxisRangeCti and yAxisRangeCti to True. After that, it emits the sigItemChanged signal of the commonCti. Can be used with functools.partial to make a slot that atomically resets the X and Y axis. That is, only one sigItemChanged will be emitted. This function is necessary because, if one would call PgAxisRangeCti.sigItemChanged separately on the X and Y axes the sigItemChanged signal would be emitted twice. This in not only slower, but autoscaling one axis may slightly change the others range, so the second call to sigItemChanged may unset the autorange of the first. axisNumber must be one of: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes). """ assert axisNumber in VALID_AXIS_NUMBERS, \ "Axis number should be one of {}, got {}".format(VALID_AXIS_NUMBERS, axisNumber) logger.debug("setXYAxesAutoRangeOn, axisNumber: {}".format(axisNumber)) if axisNumber == X_AXIS or axisNumber == BOTH_AXES: xAxisRangeCti.autoRangeCti.data = True if axisNumber == Y_AXIS or axisNumber == BOTH_AXES: yAxisRangeCti.autoRangeCti.data = True commonCti.model.sigItemChanged.emit(commonCti)
Turns on the auto range of an X and Y axis simultaneously. It sets the autoRangeCti.data of the xAxisRangeCti and yAxisRangeCti to True. After that, it emits the sigItemChanged signal of the commonCti. Can be used with functools.partial to make a slot that atomically resets the X and Y axis. That is, only one sigItemChanged will be emitted. This function is necessary because, if one would call PgAxisRangeCti.sigItemChanged separately on the X and Y axes the sigItemChanged signal would be emitted twice. This in not only slower, but autoscaling one axis may slightly change the others range, so the second call to sigItemChanged may unset the autorange of the first. axisNumber must be one of: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes).
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L155-L180
titusjan/argos
argos/inspector/pgplugins/pgctis.py
ViewBoxDebugCti._refreshNodeFromTarget
def _refreshNodeFromTarget(self): """ Updates the config settings """ for key, value in self.viewBox.state.items(): if key != "limits": childItem = self.childByNodeName(key) childItem.data = value else: # limits contains a dictionary as well for limitKey, limitValue in value.items(): limitChildItem = self.limitsItem.childByNodeName(limitKey) limitChildItem.data = limitValue
python
def _refreshNodeFromTarget(self): """ Updates the config settings """ for key, value in self.viewBox.state.items(): if key != "limits": childItem = self.childByNodeName(key) childItem.data = value else: # limits contains a dictionary as well for limitKey, limitValue in value.items(): limitChildItem = self.limitsItem.childByNodeName(limitKey) limitChildItem.data = limitValue
Updates the config settings
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L98-L109
titusjan/argos
argos/inspector/pgplugins/pgctis.py
AbstractRangeCti.autoRangeMethod
def autoRangeMethod(self): """ The currently selected auto range method. If there is no method child CTI, there will be only one method (which will be returned). """ if self.methodCti: return self.methodCti.configValue else: assert len(self._rangeFunctions) == 1, \ "Assumed only one _rangeFunctions. Got: {}".format(self._rangeFunctions) return list(self._rangeFunctions.keys())[0]
python
def autoRangeMethod(self): """ The currently selected auto range method. If there is no method child CTI, there will be only one method (which will be returned). """ if self.methodCti: return self.methodCti.configValue else: assert len(self._rangeFunctions) == 1, \ "Assumed only one _rangeFunctions. Got: {}".format(self._rangeFunctions) return list(self._rangeFunctions.keys())[0]
The currently selected auto range method. If there is no method child CTI, there will be only one method (which will be returned).
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L223-L232
titusjan/argos
argos/inspector/pgplugins/pgctis.py
AbstractRangeCti._forceRefreshMinMax
def _forceRefreshMinMax(self): """ Refreshes the min max config values from the axes' state. """ #logger.debug("_forceRefreshMinMax", stack_info=True) # Set the precision from by looking how many decimals are needed to show the difference # between the minimum and maximum, given the maximum. E.g. if min = 0.04 and max = 0.07, # we would only need zero decimals behind the point as we can write the range as # [4e-2, 7e-2]. However if min = 1.04 and max = 1.07, we need 2 decimals behind the point. # So, while the range is the same size we need more decimals because we are not zoomed in # around zero. rangeMin, rangeMax = self.getTargetRange() # [[xmin, xmax], [ymin, ymax]] maxOrder = np.log10(np.abs(max(rangeMax, rangeMin))) diffOrder = np.log10(np.abs(rangeMax - rangeMin)) extraDigits = 2 # add some extra digits to make each pan/zoom action show a new value. precisionF = np.clip(abs(maxOrder - diffOrder) + extraDigits, extraDigits + 1, 25) precision = int(precisionF) if np.isfinite(precisionF) else extraDigits + 1 #logger.debug("maxOrder: {}, diffOrder: {}, precision: {}" # .format(maxOrder, diffOrder, precision)) self.rangeMinCti.precision = precision self.rangeMaxCti.precision = precision self.rangeMinCti.data, self.rangeMaxCti.data = rangeMin, rangeMax # Update values in the tree self.model.emitDataChanged(self.rangeMinCti) self.model.emitDataChanged(self.rangeMaxCti)
python
def _forceRefreshMinMax(self): """ Refreshes the min max config values from the axes' state. """ #logger.debug("_forceRefreshMinMax", stack_info=True) # Set the precision from by looking how many decimals are needed to show the difference # between the minimum and maximum, given the maximum. E.g. if min = 0.04 and max = 0.07, # we would only need zero decimals behind the point as we can write the range as # [4e-2, 7e-2]. However if min = 1.04 and max = 1.07, we need 2 decimals behind the point. # So, while the range is the same size we need more decimals because we are not zoomed in # around zero. rangeMin, rangeMax = self.getTargetRange() # [[xmin, xmax], [ymin, ymax]] maxOrder = np.log10(np.abs(max(rangeMax, rangeMin))) diffOrder = np.log10(np.abs(rangeMax - rangeMin)) extraDigits = 2 # add some extra digits to make each pan/zoom action show a new value. precisionF = np.clip(abs(maxOrder - diffOrder) + extraDigits, extraDigits + 1, 25) precision = int(precisionF) if np.isfinite(precisionF) else extraDigits + 1 #logger.debug("maxOrder: {}, diffOrder: {}, precision: {}" # .format(maxOrder, diffOrder, precision)) self.rangeMinCti.precision = precision self.rangeMaxCti.precision = precision self.rangeMinCti.data, self.rangeMaxCti.data = rangeMin, rangeMax # Update values in the tree self.model.emitDataChanged(self.rangeMinCti) self.model.emitDataChanged(self.rangeMaxCti)
Refreshes the min max config values from the axes' state.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L248-L275
titusjan/argos
argos/inspector/pgplugins/pgctis.py
AbstractRangeCti.refreshMinMax
def refreshMinMax(self): """ Refreshes the min max config values from the axes' state. Does nothing when self.getRefreshBlocked() returns True. """ if self.getRefreshBlocked(): logger.debug("refreshMinMax blocked for {}".format(self.nodeName)) return self._forceRefreshMinMax()
python
def refreshMinMax(self): """ Refreshes the min max config values from the axes' state. Does nothing when self.getRefreshBlocked() returns True. """ if self.getRefreshBlocked(): logger.debug("refreshMinMax blocked for {}".format(self.nodeName)) return self._forceRefreshMinMax()
Refreshes the min max config values from the axes' state. Does nothing when self.getRefreshBlocked() returns True.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L278-L286
titusjan/argos
argos/inspector/pgplugins/pgctis.py
AbstractRangeCti._forceRefreshAutoRange
def _forceRefreshAutoRange(self): """ The min and max config items will be disabled if auto range is on. """ enabled = self.autoRangeCti and self.autoRangeCti.configValue self.rangeMinCti.enabled = not enabled self.rangeMaxCti.enabled = not enabled self.model.emitDataChanged(self)
python
def _forceRefreshAutoRange(self): """ The min and max config items will be disabled if auto range is on. """ enabled = self.autoRangeCti and self.autoRangeCti.configValue self.rangeMinCti.enabled = not enabled self.rangeMaxCti.enabled = not enabled self.model.emitDataChanged(self)
The min and max config items will be disabled if auto range is on.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L289-L295
titusjan/argos
argos/inspector/pgplugins/pgctis.py
AbstractRangeCti.setAutoRangeOff
def setAutoRangeOff(self): """ Turns off the auto range checkbox. Calls _refreshNodeFromTarget, not _updateTargetFromNode, because setting auto range off does not require a redraw of the target. """ # TODO: catch exceptions. How? # /argos/hdf-eos/DeepBlue-SeaWiFS-1.0_L3_20100101_v002-20110527T191319Z.h5/aerosol_optical_thickness_stddev_ocean if self.getRefreshBlocked(): logger.debug("setAutoRangeOff blocked for {}".format(self.nodeName)) return if self.autoRangeCti: self.autoRangeCti.data = False self._forceRefreshAutoRange()
python
def setAutoRangeOff(self): """ Turns off the auto range checkbox. Calls _refreshNodeFromTarget, not _updateTargetFromNode, because setting auto range off does not require a redraw of the target. """ # TODO: catch exceptions. How? # /argos/hdf-eos/DeepBlue-SeaWiFS-1.0_L3_20100101_v002-20110527T191319Z.h5/aerosol_optical_thickness_stddev_ocean if self.getRefreshBlocked(): logger.debug("setAutoRangeOff blocked for {}".format(self.nodeName)) return if self.autoRangeCti: self.autoRangeCti.data = False self._forceRefreshAutoRange()
Turns off the auto range checkbox. Calls _refreshNodeFromTarget, not _updateTargetFromNode, because setting auto range off does not require a redraw of the target.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L298-L312
titusjan/argos
argos/inspector/pgplugins/pgctis.py
AbstractRangeCti.setAutoRangeOn
def setAutoRangeOn(self): """ Turns on the auto range checkbox for the equivalent axes Emits the sigItemChanged signal so that the inspector may be updated. Use the setXYAxesAutoRangeOn stand-alone function if you want to set the autorange on for both axes of a viewport. """ if self.getRefreshBlocked(): logger.debug("Set autorange on blocked for {}".format(self.nodeName)) return if self.autoRangeCti: self.autoRangeCti.data = True self.model.sigItemChanged.emit(self)
python
def setAutoRangeOn(self): """ Turns on the auto range checkbox for the equivalent axes Emits the sigItemChanged signal so that the inspector may be updated. Use the setXYAxesAutoRangeOn stand-alone function if you want to set the autorange on for both axes of a viewport. """ if self.getRefreshBlocked(): logger.debug("Set autorange on blocked for {}".format(self.nodeName)) return if self.autoRangeCti: self.autoRangeCti.data = True self.model.sigItemChanged.emit(self)
Turns on the auto range checkbox for the equivalent axes Emits the sigItemChanged signal so that the inspector may be updated. Use the setXYAxesAutoRangeOn stand-alone function if you want to set the autorange on for both axes of a viewport.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L315-L328
titusjan/argos
argos/inspector/pgplugins/pgctis.py
AbstractRangeCti.calculateRange
def calculateRange(self): """ Calculates the range depending on the config settings. """ if not self.autoRangeCti or not self.autoRangeCti.configValue: return (self.rangeMinCti.data, self.rangeMaxCti.data) else: rangeFunction = self._rangeFunctions[self.autoRangeMethod] return rangeFunction()
python
def calculateRange(self): """ Calculates the range depending on the config settings. """ if not self.autoRangeCti or not self.autoRangeCti.configValue: return (self.rangeMinCti.data, self.rangeMaxCti.data) else: rangeFunction = self._rangeFunctions[self.autoRangeMethod] return rangeFunction()
Calculates the range depending on the config settings.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L331-L338
titusjan/argos
argos/inspector/pgplugins/pgctis.py
AbstractRangeCti._updateTargetFromNode
def _updateTargetFromNode(self): """ Applies the configuration to the target axis. """ if not self.autoRangeCti or not self.autoRangeCti.configValue: padding = 0 elif self.paddingCti.configValue == -1: # specialValueText # PyQtGraph dynamic padding: between 0.02 and 0.1 dep. on the size of the ViewBox padding = None else: padding = self.paddingCti.configValue / 100 targetRange = self.calculateRange() #logger.debug("axisRange: {}, padding={}".format(targetRange, padding)) if not np.all(np.isfinite(targetRange)): logger.warn("New target range is not finite. Plot range not updated") return self.setTargetRange(targetRange, padding=padding)
python
def _updateTargetFromNode(self): """ Applies the configuration to the target axis. """ if not self.autoRangeCti or not self.autoRangeCti.configValue: padding = 0 elif self.paddingCti.configValue == -1: # specialValueText # PyQtGraph dynamic padding: between 0.02 and 0.1 dep. on the size of the ViewBox padding = None else: padding = self.paddingCti.configValue / 100 targetRange = self.calculateRange() #logger.debug("axisRange: {}, padding={}".format(targetRange, padding)) if not np.all(np.isfinite(targetRange)): logger.warn("New target range is not finite. Plot range not updated") return self.setTargetRange(targetRange, padding=padding)
Applies the configuration to the target axis.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L341-L358
titusjan/argos
argos/inspector/pgplugins/pgctis.py
PgAxisRangeCti._closeResources
def _closeResources(self): """ Disconnects signals. Is called by self.finalize when the cti is deleted. """ self.viewBox.sigRangeChangedManually.disconnect(self.setAutoRangeOff) self.viewBox.sigRangeChanged.disconnect(self.refreshMinMax)
python
def _closeResources(self): """ Disconnects signals. Is called by self.finalize when the cti is deleted. """ self.viewBox.sigRangeChangedManually.disconnect(self.setAutoRangeOff) self.viewBox.sigRangeChanged.disconnect(self.refreshMinMax)
Disconnects signals. Is called by self.finalize when the cti is deleted.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L414-L419
titusjan/argos
argos/inspector/pgplugins/pgctis.py
PgAxisRangeCti.setTargetRange
def setTargetRange(self, targetRange, padding=None): """ Sets the range of the target. """ # viewBox.setRange doesn't accept an axis number :-( if self.axisNumber == X_AXIS: xRange, yRange = targetRange, None else: xRange, yRange = None, targetRange # Do not set disableAutoRange to True in setRange; it triggers 'one last' auto range. # This is why the viewBox' autorange must be False at construction. self.viewBox.setRange(xRange = xRange, yRange=yRange, padding=padding, update=False, disableAutoRange=False)
python
def setTargetRange(self, targetRange, padding=None): """ Sets the range of the target. """ # viewBox.setRange doesn't accept an axis number :-( if self.axisNumber == X_AXIS: xRange, yRange = targetRange, None else: xRange, yRange = None, targetRange # Do not set disableAutoRange to True in setRange; it triggers 'one last' auto range. # This is why the viewBox' autorange must be False at construction. self.viewBox.setRange(xRange = xRange, yRange=yRange, padding=padding, update=False, disableAutoRange=False)
Sets the range of the target.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L428-L440
titusjan/argos
argos/inspector/pgplugins/pgctis.py
PgHistLutColorRangeCti._closeResources
def _closeResources(self): """ Disconnects signals. Is called by self.finalize when the cti is deleted. """ self.histLutItem.sigLevelsChanged.disconnect(self.setAutoRangeOff) self.histLutItem.sigLevelsChanged.disconnect(self.refreshMinMax)
python
def _closeResources(self): """ Disconnects signals. Is called by self.finalize when the cti is deleted. """ self.histLutItem.sigLevelsChanged.disconnect(self.setAutoRangeOff) self.histLutItem.sigLevelsChanged.disconnect(self.refreshMinMax)
Disconnects signals. Is called by self.finalize when the cti is deleted.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L470-L475
titusjan/argos
argos/inspector/pgplugins/pgctis.py
PgHistLutColorRangeCti.setTargetRange
def setTargetRange(self, targetRange, padding=None): """ Sets the (color) range of the HistogramLUTItem The padding variable is ignored. """ rangeMin, rangeMax = targetRange self.histLutItem.setLevels(rangeMin, rangeMax)
python
def setTargetRange(self, targetRange, padding=None): """ Sets the (color) range of the HistogramLUTItem The padding variable is ignored. """ rangeMin, rangeMax = targetRange self.histLutItem.setLevels(rangeMin, rangeMax)
Sets the (color) range of the HistogramLUTItem The padding variable is ignored.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L484-L489
titusjan/argos
argos/inspector/pgplugins/pgctis.py
PgAspectRatioCti._updateTargetFromNode
def _updateTargetFromNode(self): """ Applies the configuration to its target axis """ self.viewBox.setAspectLocked(lock=self.configValue, ratio=self.aspectRatioCti.configValue)
python
def _updateTargetFromNode(self): """ Applies the configuration to its target axis """ self.viewBox.setAspectLocked(lock=self.configValue, ratio=self.aspectRatioCti.configValue)
Applies the configuration to its target axis
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L530-L533
titusjan/argos
argos/inspector/pgplugins/pgctis.py
PgAxisFlipCti._updateTargetFromNode
def _updateTargetFromNode(self): """ Applies the configuration to its target axis """ if self.axisNumber == X_AXIS: self.viewBox.invertX(self.configValue) else: self.viewBox.invertY(self.configValue)
python
def _updateTargetFromNode(self): """ Applies the configuration to its target axis """ if self.axisNumber == X_AXIS: self.viewBox.invertX(self.configValue) else: self.viewBox.invertY(self.configValue)
Applies the configuration to its target axis
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L552-L558
titusjan/argos
argos/inspector/pgplugins/pgctis.py
PgAxisLabelCti._updateTargetFromNode
def _updateTargetFromNode(self): """ Applies the configuration to the target axis it monitors. The axis label will be set to the configValue. If the configValue equals PgAxisLabelCti.NO_LABEL, the label will be hidden. """ rtiInfo = self.collector.rtiInfo self.plotItem.setLabel(self.axisPosition, self.configValue.format(**rtiInfo)) self.plotItem.showLabel(self.axisPosition, self.configValue != self.NO_LABEL)
python
def _updateTargetFromNode(self): """ Applies the configuration to the target axis it monitors. The axis label will be set to the configValue. If the configValue equals PgAxisLabelCti.NO_LABEL, the label will be hidden. """ rtiInfo = self.collector.rtiInfo self.plotItem.setLabel(self.axisPosition, self.configValue.format(**rtiInfo)) self.plotItem.showLabel(self.axisPosition, self.configValue != self.NO_LABEL)
Applies the configuration to the target axis it monitors. The axis label will be set to the configValue. If the configValue equals PgAxisLabelCti.NO_LABEL, the label will be hidden.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L586-L593
titusjan/argos
argos/inspector/pgplugins/pgctis.py
PgAxisShowCti._updateTargetFromNode
def _updateTargetFromNode(self): """ Applies the configuration to its target axis """ logger.debug("showAxis: {}, {}".format(self.axisPosition, self.configValue)) self.plotItem.showAxis(self.axisPosition, show=self.configValue)
python
def _updateTargetFromNode(self): """ Applies the configuration to its target axis """ logger.debug("showAxis: {}, {}".format(self.axisPosition, self.configValue)) self.plotItem.showAxis(self.axisPosition, show=self.configValue)
Applies the configuration to its target axis
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L615-L619
titusjan/argos
argos/inspector/pgplugins/pgctis.py
PgAxisLogModeCti._updateTargetFromNode
def _updateTargetFromNode(self): """ Applies the configuration to its target axis """ if self.axisNumber == X_AXIS: xMode, yMode = self.configValue, None else: xMode, yMode = None, self.configValue self.plotItem.setLogMode(x=xMode, y=yMode)
python
def _updateTargetFromNode(self): """ Applies the configuration to its target axis """ if self.axisNumber == X_AXIS: xMode, yMode = self.configValue, None else: xMode, yMode = None, self.configValue self.plotItem.setLogMode(x=xMode, y=yMode)
Applies the configuration to its target axis
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L634-L642
titusjan/argos
argos/inspector/pgplugins/pgctis.py
PgGridCti._updateTargetFromNode
def _updateTargetFromNode(self): """ Applies the configuration to the grid of the plot item. """ self.plotItem.showGrid(x=self.xGridCti.configValue, y=self.yGridCti.configValue, alpha=self.alphaCti.configValue) self.plotItem.updateGrid()
python
def _updateTargetFromNode(self): """ Applies the configuration to the grid of the plot item. """ self.plotItem.showGrid(x=self.xGridCti.configValue, y=self.yGridCti.configValue, alpha=self.alphaCti.configValue) self.plotItem.updateGrid()
Applies the configuration to the grid of the plot item.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L667-L672
titusjan/argos
argos/inspector/pgplugins/pgctis.py
PgPlotDataItemCti.createPlotDataItem
def createPlotDataItem(self): """ Creates a PyQtGraph PlotDataItem from the config values """ antialias = self.antiAliasCti.configValue color = self.penColor if self.lineCti.configValue: pen = QtGui.QPen() pen.setCosmetic(True) pen.setColor(color) pen.setWidthF(self.lineWidthCti.configValue) pen.setStyle(self.lineStyleCti.configValue) shadowCti = self.lineCti.findByNodePath('shadow') shadowPen = shadowCti.createPen(altStyle=pen.style(), altWidth=2.0 * pen.widthF()) else: pen = None shadowPen = None drawSymbols = self.symbolCti.configValue symbolShape = self.symbolShapeCti.configValue if drawSymbols else None symbolSize = self.symbolSizeCti.configValue if drawSymbols else 0.0 symbolPen = None # otherwise the symbols will also have dotted/solid line. symbolBrush = QtGui.QBrush(color) if drawSymbols else None plotDataItem = pg.PlotDataItem(antialias=antialias, pen=pen, shadowPen=shadowPen, symbol=symbolShape, symbolSize=symbolSize, symbolPen=symbolPen, symbolBrush=symbolBrush) return plotDataItem
python
def createPlotDataItem(self): """ Creates a PyQtGraph PlotDataItem from the config values """ antialias = self.antiAliasCti.configValue color = self.penColor if self.lineCti.configValue: pen = QtGui.QPen() pen.setCosmetic(True) pen.setColor(color) pen.setWidthF(self.lineWidthCti.configValue) pen.setStyle(self.lineStyleCti.configValue) shadowCti = self.lineCti.findByNodePath('shadow') shadowPen = shadowCti.createPen(altStyle=pen.style(), altWidth=2.0 * pen.widthF()) else: pen = None shadowPen = None drawSymbols = self.symbolCti.configValue symbolShape = self.symbolShapeCti.configValue if drawSymbols else None symbolSize = self.symbolSizeCti.configValue if drawSymbols else 0.0 symbolPen = None # otherwise the symbols will also have dotted/solid line. symbolBrush = QtGui.QBrush(color) if drawSymbols else None plotDataItem = pg.PlotDataItem(antialias=antialias, pen=pen, shadowPen=shadowPen, symbol=symbolShape, symbolSize=symbolSize, symbolPen=symbolPen, symbolBrush=symbolBrush) return plotDataItem
Creates a PyQtGraph PlotDataItem from the config values
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L721-L748
titusjan/argos
argos/repo/detailplugins/prop.py
PropertiesPane._drawContents
def _drawContents(self, currentRti=None): """ Draws the attributes of the currentRTI """ table = self.table table.setUpdatesEnabled(False) try: table.clearContents() verticalHeader = table.verticalHeader() verticalHeader.setSectionResizeMode(QtWidgets.QHeaderView.Fixed) if currentRti is None: return # Each column in the repo tree corresponds to a row in this detail pane. repoModel = self._repoTreeView.model() propNames = RepoTreeModel.HEADERS table.setRowCount(len(propNames)) for row, propName in enumerate(propNames): nameItem = QtWidgets.QTableWidgetItem(propName) nameItem.setToolTip(propName) table.setItem(row, self.COL_PROP_NAME, nameItem) propValue = repoModel.itemData(currentRti, row) propItem = QtWidgets.QTableWidgetItem(propValue) propItem.setToolTip(propValue) table.setItem(row, self.COL_VALUE, propItem) table.resizeRowToContents(row) verticalHeader.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents) finally: table.setUpdatesEnabled(True)
python
def _drawContents(self, currentRti=None): """ Draws the attributes of the currentRTI """ table = self.table table.setUpdatesEnabled(False) try: table.clearContents() verticalHeader = table.verticalHeader() verticalHeader.setSectionResizeMode(QtWidgets.QHeaderView.Fixed) if currentRti is None: return # Each column in the repo tree corresponds to a row in this detail pane. repoModel = self._repoTreeView.model() propNames = RepoTreeModel.HEADERS table.setRowCount(len(propNames)) for row, propName in enumerate(propNames): nameItem = QtWidgets.QTableWidgetItem(propName) nameItem.setToolTip(propName) table.setItem(row, self.COL_PROP_NAME, nameItem) propValue = repoModel.itemData(currentRti, row) propItem = QtWidgets.QTableWidgetItem(propValue) propItem.setToolTip(propValue) table.setItem(row, self.COL_VALUE, propItem) table.resizeRowToContents(row) verticalHeader.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents) finally: table.setUpdatesEnabled(True)
Draws the attributes of the currentRTI
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/detailplugins/prop.py#L52-L83
titusjan/argos
argos/repo/repotreemodel.py
RepoTreeModel.itemData
def itemData(self, treeItem, column, role=Qt.DisplayRole): """ Returns the data stored under the given role for the item. O """ if role == Qt.DisplayRole: if column == self.COL_NODE_NAME: return treeItem.nodeName elif column == self.COL_NODE_PATH: return treeItem.nodePath elif column == self.COL_SHAPE: if treeItem.isSliceable: return " x ".join(str(elem) for elem in treeItem.arrayShape) else: return "" elif column == self.COL_IS_OPEN: # Only show for RTIs that actually open resources. # TODO: this must be clearer. Use CanFetchChildren? Set is Open to None by default? if treeItem.hasChildren(): return str(treeItem.isOpen) else: return "" elif column == self.COL_ELEM_TYPE: return treeItem.elementTypeName elif column == self.COL_FILE_NAME: return treeItem.fileName if hasattr(treeItem, 'fileName') else '' elif column == self.COL_UNIT: return treeItem.unit elif column == self.COL_MISSING_DATA: return to_string(treeItem.missingDataValue, noneFormat='') # empty str for Nones elif column == self.COL_RTI_TYPE: return type_name(treeItem) elif column == self.COL_EXCEPTION: return str(treeItem.exception) if treeItem.exception else '' else: raise ValueError("Invalid column: {}".format(column)) elif role == Qt.ToolTipRole: if treeItem.exception: return str(treeItem.exception) if column == self.COL_NODE_NAME: return treeItem.nodePath # Also path when hovering over the name elif column == self.COL_NODE_PATH: return treeItem.nodePath elif column == self.COL_SHAPE: if treeItem.isSliceable: return " x ".join(str(elem) for elem in treeItem.arrayShape) else: return "" elif column == self.COL_UNIT: return treeItem.unit elif column == self.COL_MISSING_DATA: return to_string(treeItem.missingDataValue, noneFormat='') # empty str for Nones elif column == self.COL_RTI_TYPE: return type_name(treeItem) elif column == self.COL_ELEM_TYPE: return treeItem.elementTypeName elif column == self.COL_FILE_NAME: return treeItem.fileName if hasattr(treeItem, 'fileName') else '' else: return None else: return super(RepoTreeModel, self).itemData(treeItem, column, role=role)
python
def itemData(self, treeItem, column, role=Qt.DisplayRole): """ Returns the data stored under the given role for the item. O """ if role == Qt.DisplayRole: if column == self.COL_NODE_NAME: return treeItem.nodeName elif column == self.COL_NODE_PATH: return treeItem.nodePath elif column == self.COL_SHAPE: if treeItem.isSliceable: return " x ".join(str(elem) for elem in treeItem.arrayShape) else: return "" elif column == self.COL_IS_OPEN: # Only show for RTIs that actually open resources. # TODO: this must be clearer. Use CanFetchChildren? Set is Open to None by default? if treeItem.hasChildren(): return str(treeItem.isOpen) else: return "" elif column == self.COL_ELEM_TYPE: return treeItem.elementTypeName elif column == self.COL_FILE_NAME: return treeItem.fileName if hasattr(treeItem, 'fileName') else '' elif column == self.COL_UNIT: return treeItem.unit elif column == self.COL_MISSING_DATA: return to_string(treeItem.missingDataValue, noneFormat='') # empty str for Nones elif column == self.COL_RTI_TYPE: return type_name(treeItem) elif column == self.COL_EXCEPTION: return str(treeItem.exception) if treeItem.exception else '' else: raise ValueError("Invalid column: {}".format(column)) elif role == Qt.ToolTipRole: if treeItem.exception: return str(treeItem.exception) if column == self.COL_NODE_NAME: return treeItem.nodePath # Also path when hovering over the name elif column == self.COL_NODE_PATH: return treeItem.nodePath elif column == self.COL_SHAPE: if treeItem.isSliceable: return " x ".join(str(elem) for elem in treeItem.arrayShape) else: return "" elif column == self.COL_UNIT: return treeItem.unit elif column == self.COL_MISSING_DATA: return to_string(treeItem.missingDataValue, noneFormat='') # empty str for Nones elif column == self.COL_RTI_TYPE: return type_name(treeItem) elif column == self.COL_ELEM_TYPE: return treeItem.elementTypeName elif column == self.COL_FILE_NAME: return treeItem.fileName if hasattr(treeItem, 'fileName') else '' else: return None else: return super(RepoTreeModel, self).itemData(treeItem, column, role=role)
Returns the data stored under the given role for the item. O
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreemodel.py#L53-L113
titusjan/argos
argos/repo/repotreemodel.py
RepoTreeModel.canFetchMore
def canFetchMore(self, parentIndex): """ Returns true if there is more data available for parent; otherwise returns false. """ parentItem = self.getItem(parentIndex) if not parentItem: return False return parentItem.canFetchChildren()
python
def canFetchMore(self, parentIndex): """ Returns true if there is more data available for parent; otherwise returns false. """ parentItem = self.getItem(parentIndex) if not parentItem: return False return parentItem.canFetchChildren()
Returns true if there is more data available for parent; otherwise returns false.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreemodel.py#L116-L123
titusjan/argos
argos/repo/repotreemodel.py
RepoTreeModel.fetchMore
def fetchMore(self, parentIndex): # TODO: Make LazyLoadRepoTreeModel? """ Fetches any available data for the items with the parent specified by the parent index. """ parentItem = self.getItem(parentIndex) if not parentItem: return if not parentItem.canFetchChildren(): return # TODO: implement InsertItems to optimize? for childItem in parentItem.fetchChildren(): self.insertItem(childItem, parentIndex=parentIndex) # Check that Rti implementation correctly sets canFetchChildren assert not parentItem.canFetchChildren(), \ "not all children fetched: {}".format(parentItem)
python
def fetchMore(self, parentIndex): # TODO: Make LazyLoadRepoTreeModel? """ Fetches any available data for the items with the parent specified by the parent index. """ parentItem = self.getItem(parentIndex) if not parentItem: return if not parentItem.canFetchChildren(): return # TODO: implement InsertItems to optimize? for childItem in parentItem.fetchChildren(): self.insertItem(childItem, parentIndex=parentIndex) # Check that Rti implementation correctly sets canFetchChildren assert not parentItem.canFetchChildren(), \ "not all children fetched: {}".format(parentItem)
Fetches any available data for the items with the parent specified by the parent index.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreemodel.py#L126-L142
titusjan/argos
argos/repo/repotreemodel.py
RepoTreeModel.findFileRtiIndex
def findFileRtiIndex(self, childIndex): """ Traverses the tree upwards from the item at childIndex until the tree item is found that represents the file the item at childIndex """ parentIndex = childIndex.parent() if not parentIndex.isValid(): return childIndex else: parentItem = self.getItem(parentIndex) childItem = self.getItem(childIndex) if parentItem.fileName == childItem.fileName: return self.findFileRtiIndex(parentIndex) else: return childIndex
python
def findFileRtiIndex(self, childIndex): """ Traverses the tree upwards from the item at childIndex until the tree item is found that represents the file the item at childIndex """ parentIndex = childIndex.parent() if not parentIndex.isValid(): return childIndex else: parentItem = self.getItem(parentIndex) childItem = self.getItem(childIndex) if parentItem.fileName == childItem.fileName: return self.findFileRtiIndex(parentIndex) else: return childIndex
Traverses the tree upwards from the item at childIndex until the tree item is found that represents the file the item at childIndex
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreemodel.py#L145-L158
titusjan/argos
argos/repo/repotreemodel.py
RepoTreeModel.reloadFileAtIndex
def reloadFileAtIndex(self, itemIndex, rtiClass=None): """ Reloads the item at the index by removing the repo tree item and inserting a new one. The new item will have by of type rtiClass. If rtiClass is None (the default), the new rtiClass will be the same as the old one. """ fileRtiParentIndex = itemIndex.parent() fileRti = self.getItem(itemIndex) position = fileRti.childNumber() fileName = fileRti.fileName if rtiClass is None: rtiClass = type(fileRti) # Delete old RTI and Insert a new one instead. self.deleteItemAtIndex(itemIndex) # this will close the items resources. return self.loadFile(fileName, rtiClass, position=position, parentIndex=fileRtiParentIndex)
python
def reloadFileAtIndex(self, itemIndex, rtiClass=None): """ Reloads the item at the index by removing the repo tree item and inserting a new one. The new item will have by of type rtiClass. If rtiClass is None (the default), the new rtiClass will be the same as the old one. """ fileRtiParentIndex = itemIndex.parent() fileRti = self.getItem(itemIndex) position = fileRti.childNumber() fileName = fileRti.fileName if rtiClass is None: rtiClass = type(fileRti) # Delete old RTI and Insert a new one instead. self.deleteItemAtIndex(itemIndex) # this will close the items resources. return self.loadFile(fileName, rtiClass, position=position, parentIndex=fileRtiParentIndex)
Reloads the item at the index by removing the repo tree item and inserting a new one. The new item will have by of type rtiClass. If rtiClass is None (the default), the new rtiClass will be the same as the old one.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreemodel.py#L161-L177
titusjan/argos
argos/repo/repotreemodel.py
RepoTreeModel.loadFile
def loadFile(self, fileName, rtiClass=None, position=None, parentIndex=QtCore.QModelIndex()): """ Loads a file in the repository as a repo tree item of class rtiClass. Autodetects the RTI type if rtiClass is None. If position is None the child will be appended as the last child of the parent. Returns the index of the newly inserted RTI """ logger.info("Loading data from: {!r}".format(fileName)) if rtiClass is None: repoTreeItem = createRtiFromFileName(fileName) else: repoTreeItem = rtiClass.createFromFileName(fileName) assert repoTreeItem.parentItem is None, "repoTreeItem {!r}".format(repoTreeItem) return self.insertItem(repoTreeItem, position=position, parentIndex=parentIndex)
python
def loadFile(self, fileName, rtiClass=None, position=None, parentIndex=QtCore.QModelIndex()): """ Loads a file in the repository as a repo tree item of class rtiClass. Autodetects the RTI type if rtiClass is None. If position is None the child will be appended as the last child of the parent. Returns the index of the newly inserted RTI """ logger.info("Loading data from: {!r}".format(fileName)) if rtiClass is None: repoTreeItem = createRtiFromFileName(fileName) else: repoTreeItem = rtiClass.createFromFileName(fileName) assert repoTreeItem.parentItem is None, "repoTreeItem {!r}".format(repoTreeItem) return self.insertItem(repoTreeItem, position=position, parentIndex=parentIndex)
Loads a file in the repository as a repo tree item of class rtiClass. Autodetects the RTI type if rtiClass is None. If position is None the child will be appended as the last child of the parent. Returns the index of the newly inserted RTI
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreemodel.py#L180-L193
titusjan/argos
argos/repo/repotreeview.py
RepoTreeView.finalize
def finalize(self): """ Disconnects signals and frees resources """ self.model().sigItemChanged.disconnect(self.repoTreeItemChanged) selectionModel = self.selectionModel() # need to store reference to prevent crash in PySide selectionModel.currentChanged.disconnect(self.currentItemChanged)
python
def finalize(self): """ Disconnects signals and frees resources """ self.model().sigItemChanged.disconnect(self.repoTreeItemChanged) selectionModel = self.selectionModel() # need to store reference to prevent crash in PySide selectionModel.currentChanged.disconnect(self.currentItemChanged)
Disconnects signals and frees resources
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreeview.py#L127-L133
titusjan/argos
argos/repo/repotreeview.py
RepoTreeView.contextMenuEvent
def contextMenuEvent(self, event): """ Creates and executes the context menu for the tree view """ menu = QtWidgets.QMenu(self) for action in self.actions(): menu.addAction(action) openAsMenu = self.createOpenAsMenu(parent=menu) menu.insertMenu(self.closeItemAction, openAsMenu) menu.exec_(event.globalPos())
python
def contextMenuEvent(self, event): """ Creates and executes the context menu for the tree view """ menu = QtWidgets.QMenu(self) for action in self.actions(): menu.addAction(action) openAsMenu = self.createOpenAsMenu(parent=menu) menu.insertMenu(self.closeItemAction, openAsMenu) menu.exec_(event.globalPos())
Creates and executes the context menu for the tree view
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreeview.py#L136-L147
titusjan/argos
argos/repo/repotreeview.py
RepoTreeView.createOpenAsMenu
def createOpenAsMenu(self, parent=None): """ Creates the submenu for the Open As choice """ openAsMenu = QtWidgets.QMenu(parent=parent) openAsMenu.setTitle("Open Item As") registry = globalRtiRegistry() for rtiRegItem in registry.items: #rtiRegItem.tryImportClass() def createTrigger(): """Function to create a closure with the regItem""" _rtiRegItem = rtiRegItem # keep reference in closure return lambda: self.reloadFileOfCurrentItem(_rtiRegItem) action = QtWidgets.QAction("{}".format(rtiRegItem.name), self, enabled=bool(rtiRegItem.successfullyImported is not False), triggered=createTrigger()) openAsMenu.addAction(action) return openAsMenu
python
def createOpenAsMenu(self, parent=None): """ Creates the submenu for the Open As choice """ openAsMenu = QtWidgets.QMenu(parent=parent) openAsMenu.setTitle("Open Item As") registry = globalRtiRegistry() for rtiRegItem in registry.items: #rtiRegItem.tryImportClass() def createTrigger(): """Function to create a closure with the regItem""" _rtiRegItem = rtiRegItem # keep reference in closure return lambda: self.reloadFileOfCurrentItem(_rtiRegItem) action = QtWidgets.QAction("{}".format(rtiRegItem.name), self, enabled=bool(rtiRegItem.successfullyImported is not False), triggered=createTrigger()) openAsMenu.addAction(action) return openAsMenu
Creates the submenu for the Open As choice
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreeview.py#L150-L169
titusjan/argos
argos/repo/repotreeview.py
RepoTreeView.openCurrentItem
def openCurrentItem(self): """ Opens the current item in the repository. """ logger.debug("openCurrentItem") _currentItem, currentIndex = self.getCurrentItem() if not currentIndex.isValid(): return # Expanding the node will call indirectly call RepoTreeModel.fetchMore which will call # BaseRti.fetchChildren, which will call BaseRti.open and thus open the current RTI. # BaseRti.open will emit the self.model.sigItemChanged signal, which is connected to # RepoTreeView.onItemChanged. self.expand(currentIndex)
python
def openCurrentItem(self): """ Opens the current item in the repository. """ logger.debug("openCurrentItem") _currentItem, currentIndex = self.getCurrentItem() if not currentIndex.isValid(): return # Expanding the node will call indirectly call RepoTreeModel.fetchMore which will call # BaseRti.fetchChildren, which will call BaseRti.open and thus open the current RTI. # BaseRti.open will emit the self.model.sigItemChanged signal, which is connected to # RepoTreeView.onItemChanged. self.expand(currentIndex)
Opens the current item in the repository.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreeview.py#L201-L213
titusjan/argos
argos/repo/repotreeview.py
RepoTreeView.closeCurrentItem
def closeCurrentItem(self): """ Closes the current item in the repository. All its children will be unfetched and closed. """ logger.debug("closeCurrentItem") currentItem, currentIndex = self.getCurrentItem() if not currentIndex.isValid(): return # First we remove all the children, this will close them as well. self.model().removeAllChildrenAtIndex(currentIndex) # Close the current item. BaseRti.close will emit the self.model.sigItemChanged signal, # which is connected to RepoTreeView.onItemChanged. currentItem.close() self.dataChanged(currentIndex, currentIndex) self.collapse(currentIndex)
python
def closeCurrentItem(self): """ Closes the current item in the repository. All its children will be unfetched and closed. """ logger.debug("closeCurrentItem") currentItem, currentIndex = self.getCurrentItem() if not currentIndex.isValid(): return # First we remove all the children, this will close them as well. self.model().removeAllChildrenAtIndex(currentIndex) # Close the current item. BaseRti.close will emit the self.model.sigItemChanged signal, # which is connected to RepoTreeView.onItemChanged. currentItem.close() self.dataChanged(currentIndex, currentIndex) self.collapse(currentIndex)
Closes the current item in the repository. All its children will be unfetched and closed.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreeview.py#L217-L233
titusjan/argos
argos/repo/repotreeview.py
RepoTreeView.removeCurrentItem
def removeCurrentItem(self): """ Removes the current item from the repository tree. """ logger.debug("removeCurrentFile") currentIndex = self.getRowCurrentIndex() if not currentIndex.isValid(): return self.model().deleteItemAtIndex(currentIndex)
python
def removeCurrentItem(self): """ Removes the current item from the repository tree. """ logger.debug("removeCurrentFile") currentIndex = self.getRowCurrentIndex() if not currentIndex.isValid(): return self.model().deleteItemAtIndex(currentIndex)
Removes the current item from the repository tree.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreeview.py#L253-L261
titusjan/argos
argos/repo/repotreeview.py
RepoTreeView.reloadFileOfCurrentItem
def reloadFileOfCurrentItem(self, rtiRegItem=None): """ Finds the repo tree item that holds the file of the current item and reloads it. Reloading is done by removing the repo tree item and inserting a new one. The new item will have by of type rtiRegItem.cls. If rtiRegItem is None (the default), the new rtiClass will be the same as the old one. The rtiRegItem.cls will be imported. If this fails the old class will be used, and a warning will be logged. """ logger.debug("reloadFileOfCurrentItem, rtiClass={}".format(rtiRegItem)) currentIndex = self.getRowCurrentIndex() if not currentIndex.isValid(): return currentItem, _ = self.getCurrentItem() oldPath = currentItem.nodePath fileRtiIndex = self.model().findFileRtiIndex(currentIndex) isExpanded = self.isExpanded(fileRtiIndex) if rtiRegItem is None: rtiClass = None else: rtiRegItem.tryImportClass() rtiClass = rtiRegItem.cls newRtiIndex = self.model().reloadFileAtIndex(fileRtiIndex, rtiClass=rtiClass) try: # Expand and select the name with the old path _lastItem, lastIndex = self.expandPath(oldPath) self.setCurrentIndex(lastIndex) return lastIndex except Exception as ex: # The old path may not exist anymore. In that case select file RTI logger.warning("Unable to select {!r} beause of: {}".format(oldPath, ex)) self.setExpanded(newRtiIndex, isExpanded) self.setCurrentIndex(newRtiIndex) return newRtiIndex
python
def reloadFileOfCurrentItem(self, rtiRegItem=None): """ Finds the repo tree item that holds the file of the current item and reloads it. Reloading is done by removing the repo tree item and inserting a new one. The new item will have by of type rtiRegItem.cls. If rtiRegItem is None (the default), the new rtiClass will be the same as the old one. The rtiRegItem.cls will be imported. If this fails the old class will be used, and a warning will be logged. """ logger.debug("reloadFileOfCurrentItem, rtiClass={}".format(rtiRegItem)) currentIndex = self.getRowCurrentIndex() if not currentIndex.isValid(): return currentItem, _ = self.getCurrentItem() oldPath = currentItem.nodePath fileRtiIndex = self.model().findFileRtiIndex(currentIndex) isExpanded = self.isExpanded(fileRtiIndex) if rtiRegItem is None: rtiClass = None else: rtiRegItem.tryImportClass() rtiClass = rtiRegItem.cls newRtiIndex = self.model().reloadFileAtIndex(fileRtiIndex, rtiClass=rtiClass) try: # Expand and select the name with the old path _lastItem, lastIndex = self.expandPath(oldPath) self.setCurrentIndex(lastIndex) return lastIndex except Exception as ex: # The old path may not exist anymore. In that case select file RTI logger.warning("Unable to select {!r} beause of: {}".format(oldPath, ex)) self.setExpanded(newRtiIndex, isExpanded) self.setCurrentIndex(newRtiIndex) return newRtiIndex
Finds the repo tree item that holds the file of the current item and reloads it. Reloading is done by removing the repo tree item and inserting a new one. The new item will have by of type rtiRegItem.cls. If rtiRegItem is None (the default), the new rtiClass will be the same as the old one. The rtiRegItem.cls will be imported. If this fails the old class will be used, and a warning will be logged.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreeview.py#L265-L305
titusjan/argos
argos/repo/repotreeview.py
RepoTreeView.repoTreeItemChanged
def repoTreeItemChanged(self, rti): """ Called when repo tree item has changed (the item itself, not a new selection) If the item is the currently selected item, the the collector (inspector) and metadata widgets are updated. """ logger.debug("onItemChanged: {}".format(rti)) currentItem, _currentIndex = self.getCurrentItem() if rti == currentItem: self.currentRepoTreeItemChanged() else: logger.debug("Ignoring changed item as is not the current item: {}".format(rti))
python
def repoTreeItemChanged(self, rti): """ Called when repo tree item has changed (the item itself, not a new selection) If the item is the currently selected item, the the collector (inspector) and metadata widgets are updated. """ logger.debug("onItemChanged: {}".format(rti)) currentItem, _currentIndex = self.getCurrentItem() if rti == currentItem: self.currentRepoTreeItemChanged() else: logger.debug("Ignoring changed item as is not the current item: {}".format(rti))
Called when repo tree item has changed (the item itself, not a new selection) If the item is the currently selected item, the the collector (inspector) and metadata widgets are updated.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreeview.py#L320-L332
titusjan/argos
argos/repo/repotreeview.py
RepoTreeView.currentRepoTreeItemChanged
def currentRepoTreeItemChanged(self): """ Called to update the GUI when a repo tree item has changed or a new one was selected. """ # When the model is empty the current index may be invalid and the currentItem may be None. currentItem, currentIndex = self.getCurrentItem() hasCurrent = currentIndex.isValid() assert hasCurrent == (currentItem is not None), \ "If current idex is valid, currentIndex may not be None" # sanity check # Set the item in the collector, will will subsequently update the inspector. if hasCurrent: logger.info("Adding rti to collector: {}".format(currentItem.nodePath)) self.collector.setRti(currentItem) #if rti.asArray is not None: # TODO: maybe later, first test how robust it is now # self.collector.setRti(rti) # Update context menus in the repo tree self.currentItemActionGroup.setEnabled(hasCurrent) isTopLevel = hasCurrent and self.model().isTopLevelIndex(currentIndex) self.topLevelItemActionGroup.setEnabled(isTopLevel) self.openItemAction.setEnabled(currentItem is not None and currentItem.hasChildren() and not currentItem.isOpen) self.closeItemAction.setEnabled(currentItem is not None and currentItem.hasChildren() and currentItem.isOpen) # Emit sigRepoItemChanged signal so that, for example, details panes can update. logger.debug("Emitting sigRepoItemChanged: {}".format(currentItem)) self.sigRepoItemChanged.emit(currentItem)
python
def currentRepoTreeItemChanged(self): """ Called to update the GUI when a repo tree item has changed or a new one was selected. """ # When the model is empty the current index may be invalid and the currentItem may be None. currentItem, currentIndex = self.getCurrentItem() hasCurrent = currentIndex.isValid() assert hasCurrent == (currentItem is not None), \ "If current idex is valid, currentIndex may not be None" # sanity check # Set the item in the collector, will will subsequently update the inspector. if hasCurrent: logger.info("Adding rti to collector: {}".format(currentItem.nodePath)) self.collector.setRti(currentItem) #if rti.asArray is not None: # TODO: maybe later, first test how robust it is now # self.collector.setRti(rti) # Update context menus in the repo tree self.currentItemActionGroup.setEnabled(hasCurrent) isTopLevel = hasCurrent and self.model().isTopLevelIndex(currentIndex) self.topLevelItemActionGroup.setEnabled(isTopLevel) self.openItemAction.setEnabled(currentItem is not None and currentItem.hasChildren() and not currentItem.isOpen) self.closeItemAction.setEnabled(currentItem is not None and currentItem.hasChildren() and currentItem.isOpen) # Emit sigRepoItemChanged signal so that, for example, details panes can update. logger.debug("Emitting sigRepoItemChanged: {}".format(currentItem)) self.sigRepoItemChanged.emit(currentItem)
Called to update the GUI when a repo tree item has changed or a new one was selected.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreeview.py#L335-L365
titusjan/argos
argos/qt/misc.py
initQApplication
def initQApplication(): """ Initializes the QtWidgets.QApplication instance. Creates one if it doesn't exist. Sets Argos specific attributes, such as the OrganizationName, so that the application persistent settings are read/written to the correct settings file/winreg. It is therefore important to call this function at startup. The ArgosApplication constructor does this. Returns the application. """ # PyQtGraph recommends raster graphics system for OS-X. if 'darwin' in sys.platform: graphicsSystem = "raster" # raster, native or opengl os.environ.setdefault('QT_GRAPHICSSYSTEM', graphicsSystem) logger.info("Setting QT_GRAPHICSSYSTEM to: {}".format(graphicsSystem)) app = QtWidgets.QApplication(sys.argv) initArgosApplicationSettings(app) return app
python
def initQApplication(): """ Initializes the QtWidgets.QApplication instance. Creates one if it doesn't exist. Sets Argos specific attributes, such as the OrganizationName, so that the application persistent settings are read/written to the correct settings file/winreg. It is therefore important to call this function at startup. The ArgosApplication constructor does this. Returns the application. """ # PyQtGraph recommends raster graphics system for OS-X. if 'darwin' in sys.platform: graphicsSystem = "raster" # raster, native or opengl os.environ.setdefault('QT_GRAPHICSSYSTEM', graphicsSystem) logger.info("Setting QT_GRAPHICSSYSTEM to: {}".format(graphicsSystem)) app = QtWidgets.QApplication(sys.argv) initArgosApplicationSettings(app) return app
Initializes the QtWidgets.QApplication instance. Creates one if it doesn't exist. Sets Argos specific attributes, such as the OrganizationName, so that the application persistent settings are read/written to the correct settings file/winreg. It is therefore important to call this function at startup. The ArgosApplication constructor does this. Returns the application.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/misc.py#L116-L133
titusjan/argos
argos/qt/misc.py
initArgosApplicationSettings
def initArgosApplicationSettings(app): # TODO: this is Argos specific. Move somewhere else. """ Sets Argos specific attributes, such as the OrganizationName, so that the application persistent settings are read/written to the correct settings file/winreg. It is therefore important to call this function at startup. The ArgosApplication constructor does this. """ assert app, \ "app undefined. Call QtWidgets.QApplication.instance() or QtCor.QApplication.instance() first." logger.debug("Setting Argos QApplication settings.") app.setApplicationName(info.REPO_NAME) app.setApplicationVersion(info.VERSION) app.setOrganizationName(info.ORGANIZATION_NAME) app.setOrganizationDomain(info.ORGANIZATION_DOMAIN)
python
def initArgosApplicationSettings(app): # TODO: this is Argos specific. Move somewhere else. """ Sets Argos specific attributes, such as the OrganizationName, so that the application persistent settings are read/written to the correct settings file/winreg. It is therefore important to call this function at startup. The ArgosApplication constructor does this. """ assert app, \ "app undefined. Call QtWidgets.QApplication.instance() or QtCor.QApplication.instance() first." logger.debug("Setting Argos QApplication settings.") app.setApplicationName(info.REPO_NAME) app.setApplicationVersion(info.VERSION) app.setOrganizationName(info.ORGANIZATION_NAME) app.setOrganizationDomain(info.ORGANIZATION_DOMAIN)
Sets Argos specific attributes, such as the OrganizationName, so that the application persistent settings are read/written to the correct settings file/winreg. It is therefore important to call this function at startup. The ArgosApplication constructor does this.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/misc.py#L136-L148
titusjan/argos
argos/qt/misc.py
removeSettingsGroup
def removeSettingsGroup(groupName, settings=None): """ Removes a group from the persistent settings """ logger.debug("Removing settings group: {}".format(groupName)) settings = QtCore.QSettings() if settings is None else settings settings.remove(groupName)
python
def removeSettingsGroup(groupName, settings=None): """ Removes a group from the persistent settings """ logger.debug("Removing settings group: {}".format(groupName)) settings = QtCore.QSettings() if settings is None else settings settings.remove(groupName)
Removes a group from the persistent settings
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/misc.py#L217-L222
titusjan/argos
argos/qt/misc.py
containsSettingsGroup
def containsSettingsGroup(groupName, settings=None): """ Returns True if the settings contain a group with the name groupName. Works recursively when the groupName is a slash separated path. """ def _containsPath(path, settings): "Aux function for containsSettingsGroup. Does the actual recursive search." if len(path) == 0: return True else: head = path[0] tail = path[1:] if head not in settings.childGroups(): return False else: settings.beginGroup(head) try: return _containsPath(tail, settings) finally: settings.endGroup() # Body starts here path = os.path.split(groupName) logger.debug("Looking for path: {}".format(path)) settings = QtCore.QSettings() if settings is None else settings return _containsPath(path, settings)
python
def containsSettingsGroup(groupName, settings=None): """ Returns True if the settings contain a group with the name groupName. Works recursively when the groupName is a slash separated path. """ def _containsPath(path, settings): "Aux function for containsSettingsGroup. Does the actual recursive search." if len(path) == 0: return True else: head = path[0] tail = path[1:] if head not in settings.childGroups(): return False else: settings.beginGroup(head) try: return _containsPath(tail, settings) finally: settings.endGroup() # Body starts here path = os.path.split(groupName) logger.debug("Looking for path: {}".format(path)) settings = QtCore.QSettings() if settings is None else settings return _containsPath(path, settings)
Returns True if the settings contain a group with the name groupName. Works recursively when the groupName is a slash separated path.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/misc.py#L225-L249
titusjan/argos
argos/qt/misc.py
printChildren
def printChildren(obj, indent=""): """ Recursively prints the children of a QObject. Useful for debugging. """ children=obj.children() if children==None: return for child in children: try: childName = child.objectName() except AttributeError: childName = "<no-name>" #print ("{}{:10s}: {}".format(indent, childName, child.__class__)) print ("{}{!r}: {}".format(indent, childName, child.__class__)) printChildren(child, indent + " ")
python
def printChildren(obj, indent=""): """ Recursively prints the children of a QObject. Useful for debugging. """ children=obj.children() if children==None: return for child in children: try: childName = child.objectName() except AttributeError: childName = "<no-name>" #print ("{}{:10s}: {}".format(indent, childName, child.__class__)) print ("{}{!r}: {}".format(indent, childName, child.__class__)) printChildren(child, indent + " ")
Recursively prints the children of a QObject. Useful for debugging.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/misc.py#L255-L269
titusjan/argos
argos/qt/misc.py
printAllWidgets
def printAllWidgets(qApplication, ofType=None): """ Prints list of all widgets to stdout (for debugging) """ print ("Application's widgets {}".format(('of type: ' + str(ofType)) if ofType else '')) for widget in qApplication.allWidgets(): if ofType is None or isinstance(widget, ofType): print (" {!r}".format(widget))
python
def printAllWidgets(qApplication, ofType=None): """ Prints list of all widgets to stdout (for debugging) """ print ("Application's widgets {}".format(('of type: ' + str(ofType)) if ofType else '')) for widget in qApplication.allWidgets(): if ofType is None or isinstance(widget, ofType): print (" {!r}".format(widget))
Prints list of all widgets to stdout (for debugging)
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/misc.py#L272-L278
titusjan/argos
argos/qt/misc.py
widgetSubCheckBoxRect
def widgetSubCheckBoxRect(widget, option): """ Returns the rectangle of a check box drawn as a sub element of widget """ opt = QtWidgets.QStyleOption() opt.initFrom(widget) style = widget.style() return style.subElementRect(QtWidgets.QStyle.SE_ViewItemCheckIndicator, opt, widget)
python
def widgetSubCheckBoxRect(widget, option): """ Returns the rectangle of a check box drawn as a sub element of widget """ opt = QtWidgets.QStyleOption() opt.initFrom(widget) style = widget.style() return style.subElementRect(QtWidgets.QStyle.SE_ViewItemCheckIndicator, opt, widget)
Returns the rectangle of a check box drawn as a sub element of widget
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/misc.py#L286-L292
titusjan/argos
argos/qt/misc.py
ResizeDetailsMessageBox.resizeEvent
def resizeEvent(self, event): """ Resizes the details box if present (i.e. when 'Show Details' button was clicked) """ result = super(ResizeDetailsMessageBox, self).resizeEvent(event) details_box = self.findChild(QtWidgets.QTextEdit) if details_box is not None: #details_box.setFixedSize(details_box.sizeHint()) details_box.setFixedSize(QtCore.QSize(self.detailsBoxWidth, self.detailBoxHeight)) return result
python
def resizeEvent(self, event): """ Resizes the details box if present (i.e. when 'Show Details' button was clicked) """ result = super(ResizeDetailsMessageBox, self).resizeEvent(event) details_box = self.findChild(QtWidgets.QTextEdit) if details_box is not None: #details_box.setFixedSize(details_box.sizeHint()) details_box.setFixedSize(QtCore.QSize(self.detailsBoxWidth, self.detailBoxHeight)) return result
Resizes the details box if present (i.e. when 'Show Details' button was clicked)
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/misc.py#L173-L183
titusjan/argos
argos/repo/detailplugins/attr.py
AttributesPane._drawContents
def _drawContents(self, currentRti=None): """ Draws the attributes of the currentRTI """ #logger.debug("_drawContents: {}".format(currentRti)) table = self.table table.setUpdatesEnabled(False) try: table.clearContents() verticalHeader = table.verticalHeader() verticalHeader.setSectionResizeMode(QtWidgets.QHeaderView.Fixed) attributes = currentRti.attributes if currentRti is not None else {} table.setRowCount(len(attributes)) for row, (attrName, attrValue) in enumerate(sorted(attributes.items())): attrStr = to_string(attrValue, decode_bytes='utf-8') try: type_str = type_name(attrValue) except Exception as ex: logger.exception(ex) type_str = "<???>" nameItem = QtWidgets.QTableWidgetItem(attrName) nameItem.setToolTip(attrName) table.setItem(row, self.COL_ATTR_NAME, nameItem) valItem = QtWidgets.QTableWidgetItem(attrStr) valItem.setToolTip(attrStr) table.setItem(row, self.COL_VALUE, valItem) table.setItem(row, self.COL_ELEM_TYPE, QtWidgets.QTableWidgetItem(type_str)) table.resizeRowToContents(row) verticalHeader.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents) finally: table.setUpdatesEnabled(True)
python
def _drawContents(self, currentRti=None): """ Draws the attributes of the currentRTI """ #logger.debug("_drawContents: {}".format(currentRti)) table = self.table table.setUpdatesEnabled(False) try: table.clearContents() verticalHeader = table.verticalHeader() verticalHeader.setSectionResizeMode(QtWidgets.QHeaderView.Fixed) attributes = currentRti.attributes if currentRti is not None else {} table.setRowCount(len(attributes)) for row, (attrName, attrValue) in enumerate(sorted(attributes.items())): attrStr = to_string(attrValue, decode_bytes='utf-8') try: type_str = type_name(attrValue) except Exception as ex: logger.exception(ex) type_str = "<???>" nameItem = QtWidgets.QTableWidgetItem(attrName) nameItem.setToolTip(attrName) table.setItem(row, self.COL_ATTR_NAME, nameItem) valItem = QtWidgets.QTableWidgetItem(attrStr) valItem.setToolTip(attrStr) table.setItem(row, self.COL_VALUE, valItem) table.setItem(row, self.COL_ELEM_TYPE, QtWidgets.QTableWidgetItem(type_str)) table.resizeRowToContents(row) verticalHeader.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents) finally: table.setUpdatesEnabled(True)
Draws the attributes of the currentRTI
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/detailplugins/attr.py#L51-L86
titusjan/argos
argos/inspector/abstract.py
UpdateReason.checkValid
def checkValid(cls, reason): """ Raises ValueError if the reason is not one of the valid enumerations """ if reason not in cls.__VALID_REASONS: raise ValueError("reason must be one of {}, got {}".format(cls.__VALID_REASONS, reason))
python
def checkValid(cls, reason): """ Raises ValueError if the reason is not one of the valid enumerations """ if reason not in cls.__VALID_REASONS: raise ValueError("reason must be one of {}, got {}".format(cls.__VALID_REASONS, reason))
Raises ValueError if the reason is not one of the valid enumerations
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/abstract.py#L60-L64
titusjan/argos
argos/inspector/abstract.py
AbstractInspector.updateContents
def updateContents(self, reason=None, initiator=None): # TODO: reason mandatory? """ Tries to draw the widget contents with the updated RTI. Shows the error page in case an exception is raised while drawing the contents. Descendants should override _drawContents, not updateContents. During the call of _drawContents, the updating of the configuration tree is blocked to avoid circular effects. After that, a call to self.config.refreshFromTarget() is made to refresh the configuration tree with possible new values from the inspector (the inspector is the configuration's target, hence the name). The reason parameter is a string (one of the UpdateReason values) that indicates why the inspector contents whas updated. This can, for instance, be used to optimize drawing the inspector contents. Note that the reason may be undefined (None). The initiator may contain the object that initiated the updated. The type depends on the reason. At the moment the initiator is only implemented for the "config changed" reason. In this case the initiator will be the Config Tree Item (CTI that has changed). """ UpdateReason.checkValid(reason) logger.debug("---- Inspector updateContents, reason: {}, initiator: {}" .format(reason, initiator)) logger.debug("Inspector: {}".format(self)) logger.debug("RTI: {}".format(self.collector.rti)) try: self.setCurrentIndex(self.CONTENTS_PAGE_IDX) wasBlocked = self.config.model.setRefreshBlocked(True) try: self._drawContents(reason=reason, initiator=initiator) logger.debug("_drawContents finished successfully") # Update the config tree from the (possibly) new state of the PgLinePlot1d inspector, # e.g. the axis range may have changed while drawing. # self.config.updateTarget() # TODO: enable this here (instead of doing it in the inspector._drawContents when needed)? finally: self.config.model.setRefreshBlocked(wasBlocked) # Call refreshFromTarget in case the newly applied configuration resulted in a change # of the state of the configuration's target's (i.e. the inspector state) logger.debug("_drawContents finished successfully, calling refreshFromTarget...") self.config.refreshFromTarget() logger.debug("refreshFromTarget finished successfully") except InvalidDataError as ex: logger.info("Unable to draw the inspector contents: {}".format(ex)) except Exception as ex: if DEBUGGING: # TODO: enable raise logger.error("Error while drawing the inspector: {} ----".format(ex)) logger.exception(ex) self._clearContents() self.setCurrentIndex(self.ERROR_PAGE_IDX) self._showError(msg=str(ex), title=type_name(ex)) else: logger.debug("---- updateContents finished successfully")
python
def updateContents(self, reason=None, initiator=None): # TODO: reason mandatory? """ Tries to draw the widget contents with the updated RTI. Shows the error page in case an exception is raised while drawing the contents. Descendants should override _drawContents, not updateContents. During the call of _drawContents, the updating of the configuration tree is blocked to avoid circular effects. After that, a call to self.config.refreshFromTarget() is made to refresh the configuration tree with possible new values from the inspector (the inspector is the configuration's target, hence the name). The reason parameter is a string (one of the UpdateReason values) that indicates why the inspector contents whas updated. This can, for instance, be used to optimize drawing the inspector contents. Note that the reason may be undefined (None). The initiator may contain the object that initiated the updated. The type depends on the reason. At the moment the initiator is only implemented for the "config changed" reason. In this case the initiator will be the Config Tree Item (CTI that has changed). """ UpdateReason.checkValid(reason) logger.debug("---- Inspector updateContents, reason: {}, initiator: {}" .format(reason, initiator)) logger.debug("Inspector: {}".format(self)) logger.debug("RTI: {}".format(self.collector.rti)) try: self.setCurrentIndex(self.CONTENTS_PAGE_IDX) wasBlocked = self.config.model.setRefreshBlocked(True) try: self._drawContents(reason=reason, initiator=initiator) logger.debug("_drawContents finished successfully") # Update the config tree from the (possibly) new state of the PgLinePlot1d inspector, # e.g. the axis range may have changed while drawing. # self.config.updateTarget() # TODO: enable this here (instead of doing it in the inspector._drawContents when needed)? finally: self.config.model.setRefreshBlocked(wasBlocked) # Call refreshFromTarget in case the newly applied configuration resulted in a change # of the state of the configuration's target's (i.e. the inspector state) logger.debug("_drawContents finished successfully, calling refreshFromTarget...") self.config.refreshFromTarget() logger.debug("refreshFromTarget finished successfully") except InvalidDataError as ex: logger.info("Unable to draw the inspector contents: {}".format(ex)) except Exception as ex: if DEBUGGING: # TODO: enable raise logger.error("Error while drawing the inspector: {} ----".format(ex)) logger.exception(ex) self._clearContents() self.setCurrentIndex(self.ERROR_PAGE_IDX) self._showError(msg=str(ex), title=type_name(ex)) else: logger.debug("---- updateContents finished successfully")
Tries to draw the widget contents with the updated RTI. Shows the error page in case an exception is raised while drawing the contents. Descendants should override _drawContents, not updateContents. During the call of _drawContents, the updating of the configuration tree is blocked to avoid circular effects. After that, a call to self.config.refreshFromTarget() is made to refresh the configuration tree with possible new values from the inspector (the inspector is the configuration's target, hence the name). The reason parameter is a string (one of the UpdateReason values) that indicates why the inspector contents whas updated. This can, for instance, be used to optimize drawing the inspector contents. Note that the reason may be undefined (None). The initiator may contain the object that initiated the updated. The type depends on the reason. At the moment the initiator is only implemented for the "config changed" reason. In this case the initiator will be the Config Tree Item (CTI that has changed).
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/abstract.py#L167-L222
titusjan/argos
argos/inspector/abstract.py
AbstractInspector._showError
def _showError(self, msg="", title="Error"): """ Shows an error message. """ self.errorWidget.setError(msg=msg, title=title)
python
def _showError(self, msg="", title="Error"): """ Shows an error message. """ self.errorWidget.setError(msg=msg, title=title)
Shows an error message.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/abstract.py#L244-L247
titusjan/argos
argos/config/choicecti.py
ChoiceCti._enforceDataType
def _enforceDataType(self, data): """ Converts to int so that this CTI always stores that type. The data be set to a negative value, e.g. use -1 to select the last item by default. However, it will be converted to a positive by this method. """ idx = int(data) if idx < 0: idx += len(self._displayValues) assert 0 <= idx < len(self._displayValues), \ "Index should be >= 0 and < {}. Got {}".format(len(self._displayValues), idx) return idx
python
def _enforceDataType(self, data): """ Converts to int so that this CTI always stores that type. The data be set to a negative value, e.g. use -1 to select the last item by default. However, it will be converted to a positive by this method. """ idx = int(data) if idx < 0: idx += len(self._displayValues) assert 0 <= idx < len(self._displayValues), \ "Index should be >= 0 and < {}. Got {}".format(len(self._displayValues), idx) return idx
Converts to int so that this CTI always stores that type. The data be set to a negative value, e.g. use -1 to select the last item by default. However, it will be converted to a positive by this method.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/choicecti.py#L91-L102
titusjan/argos
argos/config/choicecti.py
ChoiceCti._nodeGetNonDefaultsDict
def _nodeGetNonDefaultsDict(self): """ Retrieves this nodes` values as a dictionary to be used for persistence. Non-recursive auxiliary function for getNonDefaultsDict """ dct = super(ChoiceCti, self)._nodeGetNonDefaultsDict() if self._configValues != self._defaultConfigValues: dct['choices'] = self._configValues return dct
python
def _nodeGetNonDefaultsDict(self): """ Retrieves this nodes` values as a dictionary to be used for persistence. Non-recursive auxiliary function for getNonDefaultsDict """ dct = super(ChoiceCti, self)._nodeGetNonDefaultsDict() if self._configValues != self._defaultConfigValues: dct['choices'] = self._configValues return dct
Retrieves this nodes` values as a dictionary to be used for persistence. Non-recursive auxiliary function for getNonDefaultsDict
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/choicecti.py#L133-L141
titusjan/argos
argos/config/choicecti.py
ChoiceCti._nodeSetValuesFromDict
def _nodeSetValuesFromDict(self, dct): """ Sets values from a dictionary in the current node. Non-recursive auxiliary function for setValuesFromDict """ if 'choices' in dct: self._configValues = list(dct['choices']) self._displayValues = list(dct['choices']) super(ChoiceCti, self)._nodeSetValuesFromDict(dct)
python
def _nodeSetValuesFromDict(self, dct): """ Sets values from a dictionary in the current node. Non-recursive auxiliary function for setValuesFromDict """ if 'choices' in dct: self._configValues = list(dct['choices']) self._displayValues = list(dct['choices']) super(ChoiceCti, self)._nodeSetValuesFromDict(dct)
Sets values from a dictionary in the current node. Non-recursive auxiliary function for setValuesFromDict
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/choicecti.py#L144-L151
titusjan/argos
argos/config/choicecti.py
ChoiceCti.createEditor
def createEditor(self, delegate, parent, option): """ Creates a ChoiceCtiEditor. For the parameters see the AbstractCti constructor documentation. """ return ChoiceCtiEditor(self, delegate, parent=parent)
python
def createEditor(self, delegate, parent, option): """ Creates a ChoiceCtiEditor. For the parameters see the AbstractCti constructor documentation. """ return ChoiceCtiEditor(self, delegate, parent=parent)
Creates a ChoiceCtiEditor. For the parameters see the AbstractCti constructor documentation.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/choicecti.py#L161-L165
titusjan/argos
argos/config/choicecti.py
ChoiceCti.insertValue
def insertValue(self, pos, configValue, displayValue=None): """ Will insert the configValue in the configValues and the displayValue in the displayValues list. If displayValue is None, the configValue is set in the displayValues as well """ self._configValues.insert(pos, configValue) self._displayValues.insert(pos, displayValue if displayValue is not None else configValue)
python
def insertValue(self, pos, configValue, displayValue=None): """ Will insert the configValue in the configValues and the displayValue in the displayValues list. If displayValue is None, the configValue is set in the displayValues as well """ self._configValues.insert(pos, configValue) self._displayValues.insert(pos, displayValue if displayValue is not None else configValue)
Will insert the configValue in the configValues and the displayValue in the displayValues list. If displayValue is None, the configValue is set in the displayValues as well
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/choicecti.py#L168-L174
titusjan/argos
argos/config/choicecti.py
ChoiceCtiEditor.finalize
def finalize(self): """ Is called when the editor is closed. Disconnect signals. """ self._comboboxListView.removeEventFilter(self) self.comboBox.model().rowsInserted.disconnect(self.comboBoxRowsInserted) self.comboBox.activated.disconnect(self.comboBoxActivated) super(ChoiceCtiEditor, self).finalize()
python
def finalize(self): """ Is called when the editor is closed. Disconnect signals. """ self._comboboxListView.removeEventFilter(self) self.comboBox.model().rowsInserted.disconnect(self.comboBoxRowsInserted) self.comboBox.activated.disconnect(self.comboBoxActivated) super(ChoiceCtiEditor, self).finalize()
Is called when the editor is closed. Disconnect signals.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/choicecti.py#L220-L226
titusjan/argos
argos/config/choicecti.py
ChoiceCtiEditor.comboBoxRowsInserted
def comboBoxRowsInserted(self, _parent, start, end): """ Called when the user has entered a new value in the combobox. Puts the combobox values back into the cti. """ assert start == end, "Bug, please report: more than one row inserted" configValue = self.comboBox.itemText(start) logger.debug("Inserting {!r} at position {} in {}" .format(configValue, start, self.cti.nodePath)) self.cti.insertValue(start, configValue)
python
def comboBoxRowsInserted(self, _parent, start, end): """ Called when the user has entered a new value in the combobox. Puts the combobox values back into the cti. """ assert start == end, "Bug, please report: more than one row inserted" configValue = self.comboBox.itemText(start) logger.debug("Inserting {!r} at position {} in {}" .format(configValue, start, self.cti.nodePath)) self.cti.insertValue(start, configValue)
Called when the user has entered a new value in the combobox. Puts the combobox values back into the cti.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/choicecti.py#L250-L258
titusjan/argos
argos/config/choicecti.py
ChoiceCtiEditor.eventFilter
def eventFilter(self, watchedObject, event): """ Deletes an item from an editable combobox when the delete or backspace key is pressed in the list of items, or when ctrl-delete or ctrl-back space is pressed in the line-edit. When the combobox is not editable the filter does nothing. """ if self.comboBox.isEditable() and event.type() == QtCore.QEvent.KeyPress: key = event.key() if key in (Qt.Key_Delete, Qt.Key_Backspace): if (watchedObject == self._comboboxListView or (watchedObject == self.comboBox and event.modifiers() == Qt.ControlModifier)): index = self._comboboxListView.currentIndex() if index.isValid(): row = index.row() logger.debug("Removing item {} from the combobox: {}" .format(row, self._comboboxListView.model().data(index))) self.cti.removeValueByIndex(row) self.comboBox.removeItem(row) return True # Calling parent event filter, which may filter out other events. return super(ChoiceCtiEditor, self).eventFilter(watchedObject, event)
python
def eventFilter(self, watchedObject, event): """ Deletes an item from an editable combobox when the delete or backspace key is pressed in the list of items, or when ctrl-delete or ctrl-back space is pressed in the line-edit. When the combobox is not editable the filter does nothing. """ if self.comboBox.isEditable() and event.type() == QtCore.QEvent.KeyPress: key = event.key() if key in (Qt.Key_Delete, Qt.Key_Backspace): if (watchedObject == self._comboboxListView or (watchedObject == self.comboBox and event.modifiers() == Qt.ControlModifier)): index = self._comboboxListView.currentIndex() if index.isValid(): row = index.row() logger.debug("Removing item {} from the combobox: {}" .format(row, self._comboboxListView.model().data(index))) self.cti.removeValueByIndex(row) self.comboBox.removeItem(row) return True # Calling parent event filter, which may filter out other events. return super(ChoiceCtiEditor, self).eventFilter(watchedObject, event)
Deletes an item from an editable combobox when the delete or backspace key is pressed in the list of items, or when ctrl-delete or ctrl-back space is pressed in the line-edit. When the combobox is not editable the filter does nothing.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/choicecti.py#L261-L285
titusjan/argos
argos/config/configtreemodel.py
ConfigTreeModel.debug
def debug(self, topLeftIndex, bottomRightIndex): """ Temporary debug to test the dataChanged signal. TODO: remove. """ if topLeftIndex.isValid() and bottomRightIndex.isValid(): topRow = topLeftIndex.row() bottomRow = bottomRightIndex.row() for row in range(topRow, bottomRow + 1): index = topLeftIndex.sibling(row, 0) childItem = self.getItem(index) logger.debug("Data changed in: {}".format(childItem.nodePath))
python
def debug(self, topLeftIndex, bottomRightIndex): """ Temporary debug to test the dataChanged signal. TODO: remove. """ if topLeftIndex.isValid() and bottomRightIndex.isValid(): topRow = topLeftIndex.row() bottomRow = bottomRightIndex.row() for row in range(topRow, bottomRow + 1): index = topLeftIndex.sibling(row, 0) childItem = self.getItem(index) logger.debug("Data changed in: {}".format(childItem.nodePath))
Temporary debug to test the dataChanged signal. TODO: remove.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/configtreemodel.py#L55-L64
titusjan/argos
argos/config/configtreemodel.py
ConfigTreeModel.flags
def flags(self, index): """ Returns the item flags for the given index. """ if not index.isValid(): return 0 cti = self.getItem(index) result = Qt.ItemIsSelectable if cti.enabled: result |= Qt.ItemIsEnabled if index.column() == self.COL_VALUE: result |= cti.valueColumnItemFlags return result
python
def flags(self, index): """ Returns the item flags for the given index. """ if not index.isValid(): return 0 cti = self.getItem(index) result = Qt.ItemIsSelectable if cti.enabled: result |= Qt.ItemIsEnabled if index.column() == self.COL_VALUE: result |= cti.valueColumnItemFlags return result
Returns the item flags for the given index.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/configtreemodel.py#L67-L83