some cleanup and suggested revisions

This commit is contained in:
Nils Nemitz 2021-05-12 03:19:06 +09:00
parent 05dc98c8c8
commit 9cb8986d90
14 changed files with 67 additions and 151 deletions

View File

@ -18,10 +18,11 @@ class MainWindow(QtWidgets.QMainWindow):
""" example application main window """ """ example application main window """
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs) super(MainWindow, self).__init__(*args, **kwargs)
pg.setConfigOption('imageAxisOrder', 'row-major')
main_wid = QtWidgets.QWidget() main_wid = QtWidgets.QWidget()
self.setCentralWidget(main_wid) self.setCentralWidget(main_wid)
self.setWindowTitle('pyqtgraph example: Palette application test') self.setWindowTitle('pyqtgraph example: Palette demonstration')
self.resize(600,600) self.resize(600,600)
# test_palette = pg.palette.get('system') # test_palette = pg.palette.get('system')
@ -45,7 +46,6 @@ class MainWindow(QtWidgets.QMainWindow):
('legacy fg/bg 2', 1,4, self.handle_button_leg2 ), ('legacy fg/bg 2', 1,4, self.handle_button_leg2 ),
('apply <mono green>', 2,2, self.handle_button_mono1 ), ('apply <mono green>', 2,2, self.handle_button_mono1 ),
('apply <mono amber>', 3,2, self.handle_button_mono2 ), ('apply <mono amber>', 3,2, self.handle_button_mono2 ),
# ('apply <mono blue>' , 2,4, self.handle_button_mono3 ),
('apply <relaxed-dark>' , 2,3, self.handle_button_pal2 ), ('apply <relaxed-dark>' , 2,3, self.handle_button_pal2 ),
('apply <relaxed-light>', 2,4, self.handle_button_pal3 ), ('apply <relaxed-light>', 2,4, self.handle_button_pal3 ),
('apply <pastels>' , 3,3, self.handle_button_pal4 ), ('apply <pastels>' , 3,3, self.handle_button_pal4 ),
@ -66,14 +66,9 @@ class MainWindow(QtWidgets.QMainWindow):
self.data1 = +3 + np.random.normal(size=(15)) #500)) self.data1 = +3 + np.random.normal(size=(15)) #500))
self.data2 = -3 + np.random.normal(size=(15)) #500)) self.data2 = -3 + np.random.normal(size=(15)) #500))
# self.curve1 = pg.PlotDataItem(
# pen='r',
# symbol='o', symbolSize=10, symbolPen='gr_fg', symbolBrush=('y',127),
# hoverable=True, hoverPen='w', hoverBrush='w')
self.curve1 = pg.ScatterPlotItem( self.curve1 = pg.ScatterPlotItem(
symbol='o', symbolSize=12, symbolPen='p1', symbolBrush=('p2',127), symbol='o', symbolSize=12, symbolPen='p1', symbolBrush=('p2',127),
hoverable=True, hoverPen='gr_acc', hoverBrush='gr_reg') hoverable=True, hoverPen='gr_acc', hoverBrush='gr_reg')
# self.curve1.setHoverable(True)
self.plt.addItem(self.curve1) self.plt.addItem(self.curve1)
self.curve2 = pg.PlotCurveItem(pen='p3', brush=('p3',128)) self.curve2 = pg.PlotCurveItem(pen='p3', brush=('p3',128))
@ -99,7 +94,6 @@ class MainWindow(QtWidgets.QMainWindow):
def testSignal(self, val): def testSignal(self, val):
""" demonstrate use of PaletteChanged signal """ """ demonstrate use of PaletteChanged signal """
print('"Palette changed" signal was received with value', val) print('"Palette changed" signal was received with value', val)
def handle_button_timer_on(self): def handle_button_timer_on(self):
""" (re-)activate timer """ """ (re-)activate timer """
@ -169,9 +163,9 @@ class MainWindow(QtWidgets.QMainWindow):
self.plt.setTitle('%0.2f fps' % self.fps) self.plt.setTitle('%0.2f fps' % self.fps)
QtWidgets.QApplication.processEvents() ## force complete redraw for every plot QtWidgets.QApplication.processEvents() ## force complete redraw for every plot
mkQApp("Palette test application") mkQApp("Palette test and design application")
main_window = MainWindow() main_window = MainWindow()
## Start Qt event loop ## Start Qt event loop
if __name__ == '__main__': if __name__ == '__main__':
QtWidgets.QApplication.instance().exec_() pg.mkQApp().exec_()

View File

@ -1,7 +1,7 @@
#!/usr/bin/python #!/usr/bin/python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
""" """
Update a simple plot as rapidly as possible to measure speed. Adjust color palettes and apply them to a running plot
""" """
## Add path to library (just for examples; you do not need this) ## Add path to library (just for examples; you do not need this)
@ -13,19 +13,18 @@ from pyqtgraph.Qt import mkQApp, QtCore, QtGui, QtWidgets
from pyqtgraph.ptime import time from pyqtgraph.ptime import time
import pyqtgraph as pg import pyqtgraph as pg
class MainWindow(QtWidgets.QMainWindow): class MainWindow(QtWidgets.QMainWindow):
""" example application main window """ """ example application main window """
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs) super(MainWindow, self).__init__(*args, **kwargs)
pg.setConfigOption('imageAxisOrder', 'row-major')
force_dark = True # start in dark mode on Windows force_dark = False # start in forced dark mode?
self.setWindowTitle('pyqtgraph example: Palette editor')
self.setWindowTitle('pyqtgraph example: Palette application test')
self.resize(600,600) self.resize(600,600)
self.palette_options = ( self.palette_options = (
('system', 'system', []), ('system (reapply to update)', 'system', []),
('legacy', 'legacy', []), ('legacy', 'legacy', []),
('relaxed (dark)' , 'relaxed_dark', []), ('relaxed (dark)' , 'relaxed_dark', []),
('relaxed (light)', 'relaxed_light', []), ('relaxed (light)', 'relaxed_light', []),
@ -38,8 +37,7 @@ class MainWindow(QtWidgets.QMainWindow):
self.colormap_options = ( self.colormap_options = (
'CET-C1', 'CET-C2','CET-C6','CET-C7', 'CET-R2', 'CET-R4', 'CET-C1', 'CET-C2','CET-C6','CET-C7', 'CET-R2', 'CET-R4',
'CET-L8', 'CET-L16', 'none' 'CET-L8', 'CET-L16', 'CET-CBC1', 'CET-CBC2', 'none'
# , 'none', 'CET-C1', 'CET-C2', 'CET-C3', 'CET-C4', 'CET-C5', 'CET-C6', 'CET-C7', 'CET-CBC1', 'CET-CBC2'
) )
app = QtWidgets.QApplication.instance() app = QtWidgets.QApplication.instance()
@ -50,10 +48,7 @@ class MainWindow(QtWidgets.QMainWindow):
app.setStyle("Fusion") app.setStyle("Fusion")
self.ui = self.prepare_ui() # relocate long-winded window layout self.ui = self.prepare_ui() # relocate long-winded window layout
# dictionary self.ui contains references to: # dictionary self.ui contains references to UI elements
# 'sample_start' QLineEdit for start of colormap sampling
# 'sample_step' QLineEdit for step of colormap sampling
# 'dark' QPushButton for toggling dark / standard GUI
if force_dark: if force_dark:
self.ui['dark'].setChecked(True) self.ui['dark'].setChecked(True)
@ -63,8 +58,7 @@ class MainWindow(QtWidgets.QMainWindow):
self.open_palette.apply() self.open_palette.apply()
self.update_color_fields( self.open_palette ) self.update_color_fields( self.open_palette )
self.num_points = 30 self.num_points = 30
# configure overview plot with four colors: # configure overview plot with four colors:
plt = self.ui['plot1'] plt = self.ui['plot1']
plt.enableAutoRange(False) plt.enableAutoRange(False)
@ -81,8 +75,8 @@ class MainWindow(QtWidgets.QMainWindow):
self.curves.append( (1, 1, curve) ) # dataset 1, vertical offset 3 self.curves.append( (1, 1, curve) ) # dataset 1, vertical offset 3
plt.addItem(curve) plt.addItem(curve)
curve = pg.ScatterPlotItem( curve = pg.ScatterPlotItem(
symbol='o', size=5, pen='p0', brush='p0', # ('p0',127), symbol='o', size=5, pen='p0', brush=('p0',127),
hoverable=True, hoverPen='gr_acc', hoverBrush='gr_reg') hoverable=True, hoverPen='gr_acc', hoverBrush='p0')
self.curves.append( (1, 1, curve) ) # dataset 1, vertical offset 2 self.curves.append( (1, 1, curve) ) # dataset 1, vertical offset 2
plt.addItem(curve) plt.addItem(curve)
@ -110,6 +104,7 @@ class MainWindow(QtWidgets.QMainWindow):
item = pg.LinearRegionItem( values=(4, 8), orientation='vertical' ) item = pg.LinearRegionItem( values=(4, 8), orientation='vertical' )
plt.addItem(item) plt.addItem(item)
# show off some color text:
col_list = [ col_list = [
('k','black'),('b','blue'),('c','cyan'),('g','green'),('y','yellow'), ('k','black'),('b','blue'),('c','cyan'),('g','green'),('y','yellow'),
('r','red'),('m','magenta'),('w','white')] ('r','red'),('m','magenta'),('w','white')]
@ -136,7 +131,6 @@ class MainWindow(QtWidgets.QMainWindow):
self.phases = np.zeros(9) self.phases = np.zeros(9)
self.timed_update() self.timed_update()
### handle GUI interaction ############################################### ### handle GUI interaction ###############################################
def update_color_fields(self, pal): def update_color_fields(self, pal):
""" update line edit fields for selected palette """ """ update line edit fields for selected palette """
@ -240,7 +234,6 @@ class MainWindow(QtWidgets.QMainWindow):
self.phases += self.speed * np.random.normal(1, 1, size=9) self.phases += self.speed * np.random.normal(1, 1, size=9)
for idx in range(1, self.data.shape[0]): for idx in range(1, self.data.shape[0]):
self.data[idx, :-1] = self.data[idx, 1:] # roll self.data[idx, :-1] = self.data[idx, 1:] # roll
# self.data[idx, -1] = np.random.normal()
self.data[1:, -1] = 0.5 * np.sin( self.phases[1:] ) self.data[1:, -1] = 0.5 * np.sin( self.phases[1:] )
xdata = self.data[0,:] xdata = self.data[0,:]
for idx, offset, curve in self.curves: for idx, offset, curve in self.curves:
@ -254,23 +247,20 @@ class MainWindow(QtWidgets.QMainWindow):
else: else:
s = np.clip(dt*3., 0, 1) s = np.clip(dt*3., 0, 1)
self.fps = self.fps * (1-s) + (1.0/dt) * s self.fps = self.fps * (1-s) + (1.0/dt) * s
self.ui['plot2'].setTitle('%0.2f fps' % self.fps) self.ui['plot2'].setTitle('%0.1f fps' % self.fps)
QtWidgets.QApplication.processEvents() ## force complete redraw for every plot QtWidgets.QApplication.processEvents() ## force complete redraw for every plot
### Qt color definitions for dark palette on Windows ##################### ### Qt color definitions for dark palette on Windows #####################
def make_dark_QPalette(self): def make_dark_QPalette(self):
# color definitions match QDarkstyle """ manually define a dark mode palette """
BLACK = QtGui.QColor('#000000') BLACK = QtGui.QColor('#000000')
# BG_LIGHT = QtGui.QColor('#505F69') BG_LIGHT = QtGui.QColor('#505354')
# BG_NORMAL = QtGui.QColor('#32414B') BG_NORMAL = QtGui.QColor('#2e3132')
# BG_DARK = QtGui.QColor('#19232D') BG_DARK = QtGui.QColor('#0e1112')
BG_LIGHT = QtGui.QColor('#505354') # #32414B FG_LIGHT = QtGui.QColor('#f0f4f5')
BG_NORMAL = QtGui.QColor('#2e3132') # #212a31 FG_NORMAL = QtGui.QColor('#d4d8d9')
BG_DARK = QtGui.QColor('#0e1112') # #10151 FG_DARK = QtGui.QColor('#b8bcbd')
FG_LIGHT = QtGui.QColor('#f0f4f5') # #F0F0F0
FG_NORMAL = QtGui.QColor('#d4d8d9') # #AAAAAA
FG_DARK = QtGui.QColor('#b8bcbd') # #787878
SEL_LIGHT = QtGui.QColor('#148CD2') SEL_LIGHT = QtGui.QColor('#148CD2')
SEL_NORMAL = QtGui.QColor('#1464A0') SEL_NORMAL = QtGui.QColor('#1464A0')
SEL_DARK = QtGui.QColor('#14506E') SEL_DARK = QtGui.QColor('#14506E')
@ -331,14 +321,14 @@ class MainWindow(QtWidgets.QMainWindow):
l_layout.setSpacing(1) l_layout.setSpacing(1)
row_idx = 0 row_idx = 0
label = QtWidgets.QLabel('System style:') label = QtWidgets.QLabel('Override system style:')
l_layout.addWidget( label, row_idx,0, 1,2 ) l_layout.addWidget( label, row_idx,0, 1,2 )
label = QtWidgets.QLabel('Select a palette:') label = QtWidgets.QLabel('Select a palette:')
l_layout.addWidget( label, row_idx,2, 1,2 ) l_layout.addWidget( label, row_idx,2, 1,2 )
row_idx += 1 row_idx += 1
btn = QtWidgets.QPushButton('dark GUI') btn = QtWidgets.QPushButton('Apply dark GUI')
btn.setCheckable(True) btn.setCheckable(True)
btn.setChecked(False) btn.setChecked(False)
btn.clicked.connect(self.handle_dark_button) btn.clicked.connect(self.handle_dark_button)
@ -423,11 +413,9 @@ class MainWindow(QtWidgets.QMainWindow):
return ui return ui
mkQApp("Palette editor")
mkQApp("Palette test application")
main_window = MainWindow() main_window = MainWindow()
## Start Qt event loop ## Start Qt event loop
if __name__ == '__main__': if __name__ == '__main__':
QtWidgets.QApplication.instance().exec_() pg.mkQApp().exec_()

View File

@ -23,8 +23,8 @@ examples = OrderedDict([
('Remote Plotting', 'RemoteSpeedTest.py'), ('Remote Plotting', 'RemoteSpeedTest.py'),
('Scrolling plots', 'scrollingPlots.py'), ('Scrolling plots', 'scrollingPlots.py'),
('Color Maps', 'colorMaps.py'), ('Color Maps', 'colorMaps.py'),
('Palette tester','PaletteTestAndEdit.py'), ('Palette demonstration','PaletteDemonstration.py'),
('Palette adjustment','PaletteApplicationExample.py'), ('Palette editor','PaletteEditor.py'),
('HDF5 big data', 'hdf5.py'), ('HDF5 big data', 'hdf5.py'),
('Demos', OrderedDict([ ('Demos', OrderedDict([
('Optics', 'optics_demos.py'), ('Optics', 'optics_demos.py'),

View File

@ -7,7 +7,6 @@ import collections
import warnings import warnings
__all__ = ['ColorRegistry'] __all__ = ['ColorRegistry']
DEBUG = False
DEFAULT_COLORS = { DEFAULT_COLORS = {
'b': QtGui.QColor( 0, 0,255,255), 'b': QtGui.QColor( 0, 0,255,255),
@ -17,8 +16,6 @@ DEFAULT_COLORS = {
'm': QtGui.QColor(255, 0,255,255), 'm': QtGui.QColor(255, 0,255,255),
'y': QtGui.QColor(255,255, 0,255), 'y': QtGui.QColor(255,255, 0,255),
'k': QtGui.QColor( 0, 0, 0,255), 'k': QtGui.QColor( 0, 0, 0,255),
# 'd': QtGui.QColor(150,150,150,255),
# 'l': QtGui.QColor(200,200,200,255),
'w': QtGui.QColor(255,255,255,255), 'w': QtGui.QColor(255,255,255,255),
's': QtGui.QColor(100,100,150,255), 's': QtGui.QColor(100,100,150,255),
'gr_acc':QtGui.QColor(200,200,100,255), # graphical accent color: pastel yellow 'gr_acc':QtGui.QColor(200,200,100,255), # graphical accent color: pastel yellow
@ -53,11 +50,10 @@ for key, col in [ # add functional colors
del key, col # let the linter know that we are done with these del key, col # let the linter know that we are done with these
def _expand_rgba_hex_string(hex): def _expand_rgba_hex_string(hex):
""" normalize hex string formats and extract alpha when present """ """ normalize hex string formats and extract alpha when present """
length = len(hex) length = len(hex)
if length < 4: return None, None if length < 4 : return None, None
if hex[0] != '#': return None, None if hex[0] != '#': return None, None
if length == 4: if length == 4:
alpha = 255 alpha = 255
@ -83,7 +79,6 @@ class ColorRegistry(QtCore.QObject):
Instantiated by 'functions.py' and retrievable as functions.COLOR_REGISTRY Instantiated by 'functions.py' and retrievable as functions.COLOR_REGISTRY
""" """
paletteHasChangedSignal = QtCore.Signal() # equated to pyqtSignal in qt.py for PyQt paletteHasChangedSignal = QtCore.Signal() # equated to pyqtSignal in qt.py for PyQt
_registrationGenerator = itertools.count() _registrationGenerator = itertools.count()
def __init__(self, color_dic): def __init__(self, color_dic):
@ -106,12 +101,11 @@ class ColorRegistry(QtCore.QObject):
name = alpha = None name = alpha = None
if color is None or isinstance( color, str): if color is None or isinstance( color, str):
name = color name = color
# elif hasattr( color, '__len__'):
elif isinstance( color, (collections.abc.Sequence, np.ndarray) ): # list-like, not a dictionary elif isinstance( color, (collections.abc.Sequence, np.ndarray) ): # list-like, not a dictionary
length = len(color) length = len(color)
if length == 0: if length == 0:
return False return False
if length >= 1: if length >= 1:
name = color[0] name = color[0]
# if color id is list-like, the first element needs to be str or None # if color id is list-like, the first element needs to be str or None
if not ( color is None or isinstance(name,str) ): return False if not ( color is None or isinstance(name,str) ): return False
@ -121,7 +115,6 @@ class ColorRegistry(QtCore.QObject):
if name is not None: if name is not None:
# if not isinstance(name,str): return False # pen id has to be str or a list-like starting with str # if not isinstance(name,str): return False # pen id has to be str or a list-like starting with str
if len(name) < 1: name = None # map '' to None if len(name) < 1: name = None # map '' to None
# elif name[0] == '#': return False # strings that start with # are explicit rgb codes
if alpha is not None: alpha = int(alpha) if alpha is not None: alpha = int(alpha)
return (name, alpha) return (name, alpha)
@ -133,7 +126,6 @@ class ColorRegistry(QtCore.QObject):
name = width = alpha = None name = width = alpha = None
if pen is None or isinstance( pen, str): if pen is None or isinstance( pen, str):
name = pen name = pen
# elif hasattr( pen, '__len__'):
elif isinstance( pen, (collections.abc.Sequence, np.ndarray) ): # list-like, not a dictionary elif isinstance( pen, (collections.abc.Sequence, np.ndarray) ): # list-like, not a dictionary
length = len(pen) length = len(pen)
if length == 0: if length == 0:
@ -149,7 +141,6 @@ class ColorRegistry(QtCore.QObject):
if name is not None: if name is not None:
if type(name) != str: return False # pen id has to be str or a list-like starting with str if type(name) != str: return False # pen id has to be str or a list-like starting with str
if len(name) < 1 : name = None # map '' to None if len(name) < 1 : name = None # map '' to None
# elif name[0] == '#' : return False # strings that start with # are explicit rgb codes
if width is not None: width = int(width) if width is not None: width = int(width)
if alpha is not None: alpha = int(alpha) if alpha is not None: alpha = int(alpha)
return (name, width, alpha) return (name, width, alpha)
@ -171,7 +162,8 @@ class ColorRegistry(QtCore.QObject):
name, alpha_from_hex = _expand_rgba_hex_string( name ) name, alpha_from_hex = _expand_rgba_hex_string( name )
if name is None: return None if name is None: return None
if alpha is None and alpha_from_hex is not None: if alpha is None and alpha_from_hex is not None:
alpha = alpha_from_hex # alpha = alpha_from_hex
desc = (name, alpha_from_hex) # handle extended 4 bytes rgba hex strings
# print('preparing hex color:',name) # print('preparing hex color:',name)
skipCache = True skipCache = True
register = False register = False
@ -204,7 +196,8 @@ class ColorRegistry(QtCore.QObject):
name, alpha_from_hex = _expand_rgba_hex_string( name ) name, alpha_from_hex = _expand_rgba_hex_string( name )
if name is None: return None if name is None: return None
if alpha is None and alpha_from_hex is not None: if alpha is None and alpha_from_hex is not None:
alpha = alpha_from_hex # alpha = alpha_from_hex
desc = (name, width, alpha_from_hex) # handle extended 4 bytes rgba hex strings
# print('preparing hex pen:',name) # print('preparing hex pen:',name)
skipCache = True skipCache = True
register = False register = False
@ -232,19 +225,20 @@ class ColorRegistry(QtCore.QObject):
if desc is False: return None # not a valid brush id if desc is False: return None # not a valid brush id
name, alpha = desc name, alpha = desc
if name is None: if name is None:
# print('returning blank brush!')
return QtGui.QBrush( QtCore.Qt.NoBrush ) return QtGui.QBrush( QtCore.Qt.NoBrush )
if name[0] == '#': # skip cache and registry for fixed hex colors if name[0] == '#': # skip cache and registry for fixed hex colors
# print('preparing hex brush:',name) name, alpha_from_hex = _expand_rgba_hex_string( name )
if name is None: return None
if alpha is None and alpha_from_hex is not None:
# alpha = alpha_from_hex
desc = (name, alpha_from_hex) # handle extended 4 bytes rgba hex strings
skipCache = True skipCache = True
register = False register = False
elif name not in self.color_dic: elif name not in self.color_dic:
warnings.warn('Unknown color identifier '+str(name)+' enocuntered in brush descriptor.') warnings.warn('Unknown color identifier '+str(name)+' enocuntered in brush descriptor.')
return None # unknown color identifier return None # unknown color identifier
if not skipCache and desc in self.brush_cache: if not skipCache and desc in self.brush_cache:
# print('using cached brush', desc)
return self.brush_cache[desc] return self.brush_cache[desc]
# print('making brush!')
qbrush = QtGui.QBrush(QtCore.Qt.SolidPattern) # make sure this brush fills once color is set qbrush = QtGui.QBrush(QtCore.Qt.SolidPattern) # make sure this brush fills once color is set
self._update_QBrush(qbrush,desc) self._update_QBrush(qbrush,desc)
if register: self.register( qbrush, desc ) # register for updates on palette change if register: self.register( qbrush, desc ) # register for updates on palette change
@ -298,7 +292,6 @@ class ColorRegistry(QtCore.QObject):
if alpha is not None: qcol.setAlpha(alpha) if alpha is not None: qcol.setAlpha(alpha)
qbrush.setColor(qcol) qbrush.setColor(qcol)
# print('= hex:', qbrush.color().name(), qbrush.color().alpha() ) # print('= hex:', qbrush.color().name(), qbrush.color().alpha() )
def register(self, obj, desc): def register(self, obj, desc):
""" """
@ -323,7 +316,6 @@ class ColorRegistry(QtCore.QObject):
del self.registered_objects[registration] del self.registered_objects[registration]
del obj, desc del obj, desc
def colors(self): def colors(self):
""" return current list of colors """ """ return current list of colors """
return self.color_dic # it would be safer (but slower) to provide only a copy return self.color_dic # it would be safer (but slower) to provide only a copy
@ -331,7 +323,6 @@ class ColorRegistry(QtCore.QObject):
def defaultColors(self): def defaultColors(self):
""" return a copy of the default color dictionary """ """ return a copy of the default color dictionary """
return DEFAULT_COLORS.copy() return DEFAULT_COLORS.copy()
def redefinePalette(self, colors=None): def redefinePalette(self, colors=None):
""" """
@ -342,13 +333,13 @@ class ColorRegistry(QtCore.QObject):
for key in DEFAULT_COLORS: for key in DEFAULT_COLORS:
if key not in colors: if key not in colors:
raise ValueError("Palette definition is missing '"+str(key)+"'") raise ValueError("Palette definition is missing '"+str(key)+"'")
if DEBUG: print(' ColorRegistry: Setting palette, all color definitions are present.')
self.color_dic.clear() self.color_dic.clear()
self.color_dic.update(colors) self.color_dic.update(colors)
# notifies named color objects of new assignments: # notifies named color objects of new assignments:
for key in self.registered_objects: # for key in self.registered_objects:
ref, desc = self.registered_objects[key] for ref, desc in self.registered_objects.values():
# ref, desc = self.registered_objects[key]
obj = ref() obj = ref()
# print('updating', obj) # print('updating', obj)
if obj is None: if obj is None:

View File

@ -222,44 +222,10 @@ class Color(QtGui.QColor):
def colorRegistry(): def colorRegistry():
""" Returns the ColorRegistry object managing registered colors """ """ Returns the ColorRegistry object managing registered colors """
return COLOR_REGISTRY return COLOR_REGISTRY
# def parseNamedColorSpecification(*args):
# """
# check if args specify a NamedColor, looking for
# 'name' or ('name', alpha) information.
# Returns:
# ('name', alpha) if a valid name and alpha value is given
# ('name', None) if no alpha value is available
# ('', None) if an empty name is given, indicating a blank color
# None if the specification does not match a NamedColor
# """
# while len(args) <= 1:
# if len(args) == 0:
# return None
# if len(args) == 1:
# arg = args[0]
# if isinstance(arg, str):
# if len(arg) == 0:
# return ('', None) # valid, but blank
# if arg[0] == '#':
# return None # hexadecimal string not handled as NamedColor
# if arg in Colors:
# return (arg, None) # valid name, no alpha given
# if isinstance(arg, (tuple, list)):
# args = arg # promote to top level
# else:
# return None #numerical values not handled as NamedColor
# if len(args) == 2:
# if isinstance(arg[0], str):
# alpha = arg[1]
# if isinstance(alpha, float):
# alpha = int(alpha*255) # convert to 0-255 integer
# return (arg[0], arg[1]) # return ('name', alpha) tuple
# return None # all other cases not handled as NamedColor
def mkColor(*args): def mkColor(*args):
""" """
Convenience function for constructing QColor from a variety of argument Convenience function for constructing QColor from a variety of argument
types. Accepted arguments are: types. Accepted arguments are:
================ =========================================================== ================ ===========================================================
@ -423,7 +389,7 @@ def mkBrush(*args, **kargs):
def mkPen(*args, **kargs): def mkPen(*args, **kargs):
""" """
Convenience function for constructing QPen. Convenience function for constructing QPen.
Examples:: Examples::
mkPen(QPen) mkPen(QPen)

View File

@ -984,7 +984,7 @@ class AxisItem(GraphicsWidget):
raise TypeError("Line Alpha should be of type None, float or int") raise TypeError("Line Alpha should be of type None, float or int")
# tickColor.setAlpha(int(lineAlpha)) # independent copy of color # tickColor.setAlpha(int(lineAlpha)) # independent copy of color
tickPen = QtGui.QPen ( self.pen() ) tickPen = QtGui.QPen( self.pen() )
tickColor = tickPen.color() tickColor = tickPen.color()
tickColor.setAlpha( int(lineAlpha) ) tickColor.setAlpha( int(lineAlpha) )
tickPen.setColor( tickColor ) tickPen.setColor( tickColor )

View File

@ -5,7 +5,7 @@ from .GraphicsItem import GraphicsItem
from .. import functions as fn from .. import functions as fn
__all__ = ['GraphicsObject'] __all__ = ['GraphicsObject']
DEBUG = False DEBUG_REDRAW = False
class GraphicsObject(GraphicsItem, QtGui.QGraphicsObject): class GraphicsObject(GraphicsItem, QtGui.QGraphicsObject):
""" """
@ -19,7 +19,6 @@ class GraphicsObject(GraphicsItem, QtGui.QGraphicsObject):
QtGui.QGraphicsObject.__init__(self, *args) QtGui.QGraphicsObject.__init__(self, *args)
self.setFlag(self.ItemSendsGeometryChanges) self.setFlag(self.ItemSendsGeometryChanges)
GraphicsItem.__init__(self) GraphicsItem.__init__(self)
# fn.NAMED_COLOR_MANAGER.paletteChangeSignal.connect(self.styleChange)
fn.COLOR_REGISTRY.paletteHasChangedSignal.connect(self.styleHasChanged) fn.COLOR_REGISTRY.paletteHasChangedSignal.connect(self.styleHasChanged)
def itemChange(self, change, value): def itemChange(self, change, value):
@ -43,15 +42,9 @@ class GraphicsObject(GraphicsItem, QtGui.QGraphicsObject):
return ret return ret
# @QT_CORE_SLOT(dict)
# def styleChange(self, color_dict):
# """ stub function called after Palette.apply(), specific reactions to palette redefinitions execute here """
# print('style change request:', self, type(color_dict))
@QtCore.Slot() # qt.py equates this to pyqtSlot for PyQt @QtCore.Slot() # qt.py equates this to pyqtSlot for PyQt
def styleHasChanged(self): def styleHasChanged(self):
""" called to trigger redraw after all named colors have been updated """ """ called to trigger redraw after all named colors have been updated """
# self._boundingRect = None # self._boundingRect = None
self.update() self.update()
if DEBUG: print(' GraphicsObject: redraw after style change:', self) if DEBUG_REDRAW: print(' GraphicsObject: redraw after style change:', self)

View File

@ -3,7 +3,7 @@ from .GraphicsItem import GraphicsItem
from .. import functions as fn from .. import functions as fn
__all__ = ['GraphicsWidget'] __all__ = ['GraphicsWidget']
DEBUG = False DEBUG_REDRAW = False
class GraphicsWidget(GraphicsItem, QtGui.QGraphicsWidget): class GraphicsWidget(GraphicsItem, QtGui.QGraphicsWidget):
@ -63,4 +63,4 @@ class GraphicsWidget(GraphicsItem, QtGui.QGraphicsWidget):
""" called to trigger redraw after all named colors have been updated """ """ called to trigger redraw after all named colors have been updated """
# self._boundingRect = None # self._boundingRect = None
self.update() self.update()
if DEBUG: print(' GraphicsWidget: redraw after style change:', self) if DEBUG_REDRAW: print(' GraphicsWidget: redraw after style change:', self)

View File

@ -529,7 +529,7 @@ class PlotCurveItem(GraphicsObject):
p.setPen(sp) p.setPen(sp)
p.drawPath(path) p.drawPath(path)
if isinstance(self.opts.get('pen'), QtGui.QPen): # subclass NamedPen also triggers this if isinstance(self.opts.get('pen'), QtGui.QPen):
cp = self.opts['pen'] cp = self.opts['pen']
else: else:
cp = fn.mkPen(self.opts['pen']) cp = fn.mkPen(self.opts['pen'])

View File

@ -21,8 +21,6 @@ from ..python2_3 import basestring
__all__ = ['ScatterPlotItem', 'SpotItem'] __all__ = ['ScatterPlotItem', 'SpotItem']
DEBUG = False
# When pxMode=True for ScatterPlotItem, QPainter.drawPixmap is used for drawing, which # When pxMode=True for ScatterPlotItem, QPainter.drawPixmap is used for drawing, which
# has multiple type signatures. One takes int coordinates of source and target # has multiple type signatures. One takes int coordinates of source and target
@ -267,7 +265,7 @@ class SymbolAtlas(object):
images = [] images = []
data = [] data = []
for key, style in styles.items(): for key, style in styles.items():
if DEBUG: print('\nrender:', style[2].color().name(), style[3].color().name(), style) # print('\nrender:', style[2].color().name(), style[3].color().name(), style)
img = renderSymbol(*style) img = renderSymbol(*style)
arr = fn.imageToArray(img, copy=False, transpose=False) arr = fn.imageToArray(img, copy=False, transpose=False)
images.append(img) # keep these to delay garbage collection images.append(img) # keep these to delay garbage collection
@ -1273,11 +1271,6 @@ class ScatterPlotItem(GraphicsObject):
def styleHasChanged(self): def styleHasChanged(self):
""" overridden to trigger symbol atlas refresh """ """ overridden to trigger symbol atlas refresh """
if DEBUG:
print(' ScatterPlotItem: style update!')
print(' pens:',self.data['pen'] )
print(' default pen :', self.opts[ 'pen' ].color().name(), self.opts[ 'pen' ] )
print(' default brush:', self.opts['brush'].color().name(), self.opts['brush'] )
self.fragmentAtlas.clear() self.fragmentAtlas.clear()
self.data['sourceRect'] = (0, 0, 0, 0) self.data['sourceRect'] = (0, 0, 0, 0)
self.updateSpots(self.data) self.updateSpots(self.data)

View File

@ -50,10 +50,9 @@ class TextItem(GraphicsObject):
self._lastTransform = None self._lastTransform = None
self._lastScene = None self._lastScene = None
self._bounds = QtCore.QRectF() self._bounds = QtCore.QRectF()
# self.color = None self._color = None
self.setColor(color) self.setColor(color)
if html is None: if html is None:
# self.setColor(color)
self.setText(text) self.setText(text)
else: else:
self.setHtml(html) self.setHtml(html)
@ -68,7 +67,7 @@ class TextItem(GraphicsObject):
This method sets the plain text of the item; see also setHtml(). This method sets the plain text of the item; see also setHtml().
""" """
if color is not None: if color is not None:
self.color = color self._color = color
self.setColor(color) self.setColor(color)
self.setPlainText(text) self.setPlainText(text)
@ -140,8 +139,12 @@ class TextItem(GraphicsObject):
See QtGui.QGraphicsItem.setDefaultTextColor(). See QtGui.QGraphicsItem.setDefaultTextColor().
""" """
self.color = fn.mkColor(color) self._color = fn.mkColor(color)
self.textItem.setDefaultTextColor(self.color) self.textItem.setDefaultTextColor(self._color)
def color(self):
""" returns the current text color """
return self._color
def updateTextPos(self): def updateTextPos(self):
# update text position to obey anchor # update text position to obey anchor
@ -220,6 +223,6 @@ class TextItem(GraphicsObject):
def styleHasChanged(self): def styleHasChanged(self):
""" overridden to mnanually refresh color """ """ overridden to mnanually refresh color """
if self.color is not None: if self._color is not None:
self.textItem.setDefaultTextColor(self.color) self.textItem.setDefaultTextColor(self._color)
super().styleHasChanged() super().styleHasChanged()

View File

@ -2,7 +2,6 @@ from . import Qt
from .Qt import QtCore, QtGui, QtWidgets from .Qt import QtCore, QtGui, QtWidgets
import numpy as np import numpy as np
import math
from . import functions as fn # namedColorManager from . import functions as fn # namedColorManager
from . import colormap from . import colormap

View File

@ -1,6 +1,6 @@
import pyqtgraph as pg import pyqtgraph as pg
from pyqtgraph import functions as fn from pyqtgraph import functions as fn
from pyqtgraph.Qt import QtCore, QtGui from pyqtgraph.Qt import QtGui
import pytest import pytest

View File

@ -14,8 +14,6 @@ from .. import getConfigOption
__all__ = ['GraphicsView'] __all__ = ['GraphicsView']
DEBUG = False
class GraphicsView(QtGui.QGraphicsView): class GraphicsView(QtGui.QGraphicsView):
"""Re-implementation of QGraphicsView that removes scrollbars and allows unambiguous control of the """Re-implementation of QGraphicsView that removes scrollbars and allows unambiguous control of the
@ -143,13 +141,8 @@ class GraphicsView(QtGui.QGraphicsView):
# background = getConfigOption('background') # background = getConfigOption('background')
background = 'gr_bg' # default graphics background color background = 'gr_bg' # default graphics background color
self._background = background # maintained for compatibility self._background = background # maintained for compatibility
if DEBUG: print(' GraphicsView: Generating BG brush for', self._background)
self._bgBrush = fn.mkBrush(self._background) self._bgBrush = fn.mkBrush(self._background)
if DEBUG: print(' GraphicsView: Background color: ',self._bgBrush.color().name(), self._bgBrush.color().alpha())
self.setBackgroundBrush( self._bgBrush ) self.setBackgroundBrush( self._bgBrush )
# testBrush = QtGui.QBrush( QtGui.QColor('#000000') )
# print(' test brush style:',testBrush.style() )
# self.setBackgroundBrush( testBrush )
def paintEvent(self, ev): def paintEvent(self, ev):
self.scene().prepareForPaint() self.scene().prepareForPaint()
@ -158,8 +151,7 @@ class GraphicsView(QtGui.QGraphicsView):
def render(self, *args, **kwds): def render(self, *args, **kwds):
self.scene().prepareForPaint() self.scene().prepareForPaint()
return super().render(*args, **kwds) return super().render(*args, **kwds)
def close(self): def close(self):
self.centralWidget = None self.centralWidget = None
self.scene().clear() self.scene().clear()
@ -184,8 +176,7 @@ class GraphicsView(QtGui.QGraphicsView):
def keyPressEvent(self, ev): def keyPressEvent(self, ev):
self.scene().keyPressEvent(ev) ## bypass view, hand event directly to scene self.scene().keyPressEvent(ev) ## bypass view, hand event directly to scene
## (view likes to eat arrow key events) ## (view likes to eat arrow key events)
def setCentralItem(self, item): def setCentralItem(self, item):
return self.setCentralWidget(item) return self.setCentralWidget(item)
@ -306,9 +297,8 @@ class GraphicsView(QtGui.QGraphicsView):
range = QtCore.QRectF(tl.x(), tl.y(), w, h) range = QtCore.QRectF(tl.x(), tl.y(), w, h)
GraphicsView.setRange(self, range, padding=0) GraphicsView.setRange(self, range, padding=0)
self.sigScaleChanged.connect(image.setScaledMode) self.sigScaleChanged.connect(image.setScaledMode)
def lockXRange(self, v1): def lockXRange(self, v1):
if not v1 in self.lockedViewports: if not v1 in self.lockedViewports:
self.lockedViewports.append(v1) self.lockedViewports.append(v1)
@ -415,4 +405,3 @@ class GraphicsView(QtGui.QGraphicsView):
""" called to trigger redraw after all named colors have been updated """ """ called to trigger redraw after all named colors have been updated """
self.setBackgroundBrush( self._bgBrush ) self.setBackgroundBrush( self._bgBrush )
# self.update() # self.update()
if DEBUG: print(' Background update and redraw after style change:', self)