general cleanup

This commit is contained in:
Nils Nemitz 2021-03-11 04:07:40 +09:00
parent 34140615fb
commit 7d19711559
10 changed files with 89 additions and 49 deletions

View File

@ -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 """

View File

@ -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'),

View File

@ -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:

View File

@ -5,6 +5,8 @@ from .functions import mkColor, eq
from os import path, listdir
import collections
__all__ = ['ColorMap']
_mapCache = {}
def listMaps(source=None):

View File

@ -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:

View File

@ -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)
if DEBUG: print(' GraphicsObject: redraw after style change:', self)

View File

@ -1,5 +1,4 @@
from ..Qt import QtGui, QtCore
from ..GraphicsScene import GraphicsScene
from .GraphicsItem import GraphicsItem
from .. import functions as fn

View File

@ -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:

View File

@ -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:

View File

@ -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 )