From 7d1971155945e9a8fec619aea7fbf45bce81fd7c Mon Sep 17 00:00:00 2001 From: Nils Nemitz Date: Thu, 11 Mar 2021 04:07:40 +0900 Subject: [PATCH] general cleanup --- examples/PaletteApplicationExample.py | 26 ++++++--- examples/utils.py | 2 +- pyqtgraph/__init__.py | 66 ++++++++++++++++------- pyqtgraph/colormap.py | 2 + pyqtgraph/functions.py | 3 +- pyqtgraph/graphicsItems/GraphicsObject.py | 2 +- pyqtgraph/graphicsItems/GraphicsWidget.py | 1 - pyqtgraph/graphicsItems/LabelItem.py | 2 +- pyqtgraph/namedColorManager.py | 26 +++++---- pyqtgraph/palette.py | 8 +-- 10 files changed, 89 insertions(+), 49 deletions(-) diff --git a/examples/PaletteApplicationExample.py b/examples/PaletteApplicationExample.py index 680b8916..761422bc 100644 --- a/examples/PaletteApplicationExample.py +++ b/examples/PaletteApplicationExample.py @@ -7,13 +7,11 @@ Update a simple plot as rapidly as possible to measure speed. ## Add path to library (just for examples; you do not need this) import initExample - import numpy as np -import pyqtgraph as pg -from pyqtgraph.Qt import mkQApp, QtGui, QtCore, QtWidgets +from pyqtgraph.Qt import mkQApp, QtCore, QtWidgets from pyqtgraph.ptime import time -from pyqtgraph import functions as fn +import pyqtgraph as pg class MainWindow(QtWidgets.QMainWindow): @@ -26,7 +24,6 @@ class MainWindow(QtWidgets.QMainWindow): self.setWindowTitle('pyqtgraph example: Palette application test') self.resize(600,600) - # pg.functions.SIGNAL_SOURCE.paletteChangedSignal.connect(self.testSignal) # test link pg.palette.get('monogreen').apply() main_layout = QtWidgets.QGridLayout( main_wid ) @@ -57,8 +54,13 @@ class MainWindow(QtWidgets.QMainWindow): btn.clicked.connect(self.handle_button_pal4) main_layout.addWidget(btn, 2,3, 1,1 ) - # self.manager = pg.fn.NAMED_COLOR_MANAGER - # self.pen1 = pg.NamedPen('p1') #,width=0.5) + btn = QtWidgets.QPushButton('legacy fg/bg override 1') + btn.clicked.connect(self.handle_button_leg1) + main_layout.addWidget(btn, 3,2, 1,1 ) + + btn = QtWidgets.QPushButton('legacy fg/bg override 2') + btn.clicked.connect(self.handle_button_leg2) + main_layout.addWidget(btn, 3,3, 1,1 ) self.plt = gr_wid.addPlot() self.plt.enableAutoRange(False) @@ -122,6 +124,16 @@ class MainWindow(QtWidgets.QMainWindow): """ apply palette 1 on request """ print('--> relax(light)') self.pal_4.apply() + + def handle_button_leg1(self): + """ test legacy background / foreground overrides """ + pg.setConfigOption('background', '#ff0000') + pg.setConfigOption('foreground', '#0000ff') + + def handle_button_leg2(self): + """ test legacy background / foreground overrides """ + pg.setConfigOption('background', '#0000ff') + pg.setConfigOption('foreground', '#ff0000') def timed_update(self): """ update loop, called by timer """ diff --git a/examples/utils.py b/examples/utils.py index b6fcf05a..94f91771 100644 --- a/examples/utils.py +++ b/examples/utils.py @@ -20,6 +20,7 @@ examples = OrderedDict([ ('Auto-range', 'PlotAutoRange.py'), ('Remote Plotting', 'RemoteSpeedTest.py'), ('Scrolling plots', 'scrollingPlots.py'), + ('Color Maps', 'colorMaps.py'), ('Palette adjustment','PaletteApplicationExample.py'), ('HDF5 big data', 'hdf5.py'), ('Demos', OrderedDict([ @@ -102,7 +103,6 @@ others = dict([ ('DiffTreeWidget', 'DiffTreeWidget.py'), ('MultiPlotWidget', 'MultiPlotWidget.py'), ('RemoteGraphicsView', 'RemoteGraphicsView.py'), - ('colorMaps', 'colorMaps.py'), ('contextMenu', 'contextMenu.py'), ('designerExample', 'designerExample.py'), ('DateAxisItem_QtDesigner', 'DateAxisItem_QtDesigner.py'), diff --git a/pyqtgraph/__init__.py b/pyqtgraph/__init__.py index ecb40d8b..69dc118a 100644 --- a/pyqtgraph/__init__.py +++ b/pyqtgraph/__init__.py @@ -62,26 +62,26 @@ CONFIG_OPTIONS = { 'useCupy': False, # When True, attempt to use cupy ( currently only with ImageItem and related functions ) } -def setConfigOption(opt, value): - if opt not in CONFIG_OPTIONS: - raise KeyError('Unknown configuration option "%s"' % opt) - if opt == 'imageAxisOrder' and value not in ('row-major', 'col-major'): - raise ValueError('imageAxisOrder must be either "row-major" or "col-major"') - # setConfigOption should be relocated to have access to functions.py - # Then background / foreground updates can be intercepted and applied to the palette - # if opt == 'background': - # functions.Colors['gr_bg'] = functions.Colors[value] - # if opt == 'foreground': - # functions.Colors['gr_fg'] = functions.Colors[value] - CONFIG_OPTIONS[opt] = value +# def setConfigOption(opt, value): +# if opt not in CONFIG_OPTIONS: +# raise KeyError('Unknown configuration option "%s"' % opt) +# if opt == 'imageAxisOrder' and value not in ('row-major', 'col-major'): +# raise ValueError('imageAxisOrder must be either "row-major" or "col-major"') +# # setConfigOption should be relocated to have access to functions.py +# # Then background / foreground updates can be intercepted and applied to the palette +# if opt == 'background': +# functions.Colors['gr_bg'] = functions.Colors[value] +# if opt == 'foreground': +# functions.Colors['gr_fg'] = functions.Colors[value] +# CONFIG_OPTIONS[opt] = value -def setConfigOptions(**opts): - """Set global configuration options. +# def setConfigOptions(**opts): +# """Set global configuration options. - Each keyword argument sets one global option. - """ - for k,v in opts.items(): - setConfigOption(k, v) +# Each keyword argument sets one global option. +# """ +# for k,v in opts.items(): +# setConfigOption(k, v) def getConfigOption(opt): """Return the value of a single global configuration option. @@ -290,6 +290,36 @@ from .palette import * from . import namedColorManager +def setConfigOption(opt, value): + if opt not in CONFIG_OPTIONS: + raise KeyError('Unknown configuration option "%s"' % opt) + if opt == 'imageAxisOrder' and value not in ('row-major', 'col-major'): + raise ValueError('imageAxisOrder must be either "row-major" or "col-major"') + + # Intercept background / foreground updates and manually apply them to the palette: + if opt in ('background', 'foreground'): + color_dict = functions.NAMED_COLOR_MANAGER.colors() + if value in color_dict: + qcol = color_dict[value] + else: + qcol = functions.mkColor(value) + if opt == 'background': + color_dict['gr_bg'] = qcol + elif opt == 'foreground': + color_dict['gr_fg'] = qcol + functions.NAMED_COLOR_MANAGER.redefinePalette(colors=None) + + CONFIG_OPTIONS[opt] = value + +def setConfigOptions(**opts): + """Set global configuration options. + + Each keyword argument sets one global option. + """ + for k,v in opts.items(): + setConfigOption(k, v) + + ############################################################## ## PyQt and PySide both are prone to crashing on exit. ## There are two general approaches to dealing with this: diff --git a/pyqtgraph/colormap.py b/pyqtgraph/colormap.py index 2ca414a8..89282ee6 100644 --- a/pyqtgraph/colormap.py +++ b/pyqtgraph/colormap.py @@ -5,6 +5,8 @@ from .functions import mkColor, eq from os import path, listdir import collections +__all__ = ['ColorMap'] + _mapCache = {} def listMaps(source=None): diff --git a/pyqtgraph/functions.py b/pyqtgraph/functions.py index 00547602..3a46b2fb 100644 --- a/pyqtgraph/functions.py +++ b/pyqtgraph/functions.py @@ -379,7 +379,7 @@ def mkBrush(*args, **kargs): return QtGui.QBrush( QtCore.Qt.NoBrush ) # explicit None means "no brush" if args == () or args == []: print(' functions: returning default color NamedBrush') - qpen = NamedBrush( 'gr_fg', manager=NAMED_COLOR_MANAGER ) # default foreground color + qbrush = NamedBrush( 'gr_fg', manager=NAMED_COLOR_MANAGER ) # default foreground color else: result = parseNamedColorSpecification(args) if result is not None: # make a NamedBrush @@ -446,7 +446,6 @@ def mkPen(*args, **kargs): qpen = QtGui.QPen(QtGui.QBrush(qcol), width) # now apply styles according to kw arguments: style = kargs.get('style', None) - width = kargs.get('width', 1) # collect remaining kargs to define properties dash = kargs.get('dash', None) cosmetic = kargs.get('cosmetic', True) if qpen is None: diff --git a/pyqtgraph/graphicsItems/GraphicsObject.py b/pyqtgraph/graphicsItems/GraphicsObject.py index 80c410fc..71095622 100644 --- a/pyqtgraph/graphicsItems/GraphicsObject.py +++ b/pyqtgraph/graphicsItems/GraphicsObject.py @@ -59,4 +59,4 @@ class GraphicsObject(GraphicsItem, QtGui.QGraphicsObject): """ called to trigger redraw after all named colors have been updated """ # self._boundingRect = None self.update() - if DEBUG: print(' GrpahicsObject: redraw after style change:', self) \ No newline at end of file + if DEBUG: print(' GraphicsObject: redraw after style change:', self) \ No newline at end of file diff --git a/pyqtgraph/graphicsItems/GraphicsWidget.py b/pyqtgraph/graphicsItems/GraphicsWidget.py index d4cfb184..415359d0 100644 --- a/pyqtgraph/graphicsItems/GraphicsWidget.py +++ b/pyqtgraph/graphicsItems/GraphicsWidget.py @@ -1,5 +1,4 @@ from ..Qt import QtGui, QtCore -from ..GraphicsScene import GraphicsScene from .GraphicsItem import GraphicsItem from .. import functions as fn diff --git a/pyqtgraph/graphicsItems/LabelItem.py b/pyqtgraph/graphicsItems/LabelItem.py index 9014d355..cda3e27f 100644 --- a/pyqtgraph/graphicsItems/LabelItem.py +++ b/pyqtgraph/graphicsItems/LabelItem.py @@ -54,7 +54,7 @@ class LabelItem(GraphicsWidget, GraphicsWidgetAnchor): self.text = text if 'color' in args: # temporary override for color: - col = fn.mkColor(opts['color']) + col = fn.mkColor(args['color']) self._hex_color_override = col.name() color_opt = self._hex_color_override else: diff --git a/pyqtgraph/namedColorManager.py b/pyqtgraph/namedColorManager.py index 59385cbf..628075f4 100644 --- a/pyqtgraph/namedColorManager.py +++ b/pyqtgraph/namedColorManager.py @@ -39,15 +39,11 @@ for idx, col in enumerate( ( # twelve predefined plot colors # functions.py initializes and maintains NAMED_COLOR_MANAGER for this purpose. class NamedColorManager(QtCore.QObject): """ - Singleton QObject that provides palette change signals + Provides palette change signals and maintains color name dictionary + Typically instantiated by functions.py as NAMED_COLOR_MANAGER Instantiated by 'functions.py' and retrievable as functions.NAMED_COLOR_MANAGER """ - try: # generic name used by pyside: - paletteChangeSignal = QtCore.Signal(dict) - paletteHasChangedSignal = QtCore.Signal() - except AttributeError: # fall back to the PyQt naming scheme - paletteChangeSignal = QtCore.pyqtSignal(dict) - paletteHasChangedSignal = QtCore.pyqtSignal() + paletteHasChangedSignal = QtCore.Signal() # equated to pyqtSignal in qt.py for PyQt def __init__(self, color_dic): """ initialization """ @@ -67,17 +63,19 @@ class NamedColorManager(QtCore.QObject): self.registered_objects.add( obj ) # if DEBUG: print(' NamedColorManager: New list', self.registered_objects ) - def redefinePalette(self, color_dic): - """ update list of named colors, emitsignals to color objects and widgets """ - if color_dic is not None: + def redefinePalette(self, colors=None): + """ + Update list of named colors if 'colors' dictionary is given + Emits paletteHasChanged signals to color objects and widgets, even if color_dict is None """ + if colors is not None: # self.color_dic.clear() # self.color_dic.update( DEFAULT_COLORS) for key in DEFAULT_COLORS: - if key not in color_dic: + if key not in colors: raise ValueError("Palette definition is missing '"+str(key)+"'") - if DEBUG: print(' NCM: confirmed all color definitions are present, setting palette') - self.color_dic.clear() - self.color_dic.update(color_dic) + if DEBUG: print(' NCM: confirmed all color definitions are present, setting palette') + self.color_dic.clear() + self.color_dic.update(colors) # notifies named color objects of new assignments: for obj in self.registered_objects: diff --git a/pyqtgraph/palette.py b/pyqtgraph/palette.py index def1cc46..b7099192 100644 --- a/pyqtgraph/palette.py +++ b/pyqtgraph/palette.py @@ -188,14 +188,14 @@ def get(name): pal = assemble_palette( MONOGREEN_RAW, MONOGREEN_FUNC, MONOGREEN_PLOT ) else: pal = DEFAULT_PALETTE - return Palette( pal ) + return Palette( colors=pal ) class Palette(object): # minimum colors to be defined: - def __init__(self, color_dic=None): + def __init__(self, colors=None): super().__init__() - self.palette = color_dic + self.palette = colors # needs: addColors # needs to be aware of number of plot colors @@ -207,4 +207,4 @@ class Palette(object): """ provides palette to NamedColorManager, which triggers a global refresh of named colors """ - fn.NAMED_COLOR_MANAGER.redefinePalette( self.palette ) + fn.NAMED_COLOR_MANAGER.redefinePalette( colors=self.palette )