Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 8f3baf0

Browse files
committed
Do all color conversion in one place, reuse MPL methods
1 parent 48b6c13 commit 8f3baf0

File tree

2 files changed

+30
-50
lines changed

2 files changed

+30
-50
lines changed

lib/matplotlib/backends/qt4_editor/figureoptions.py

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,6 @@ def get_icon(name):
3030

3131
MARKERS = markers.MarkerStyle.markers
3232

33-
COLORS = {'b': '#0000ff', 'g': '#00ff00', 'r': '#ff0000', 'c': '#ff00ff',
34-
'm': '#ff00ff', 'y': '#ffff00', 'k': '#000000', 'w': '#ffffff'}
35-
36-
def col2hex(color):
37-
"""Convert matplotlib color to hex"""
38-
return COLORS.get(color, color)
39-
4033
def figure_edit(axes, parent=None):
4134
"""Edit matplotlib figure options"""
4235
sep = (None, None) # separator
@@ -79,13 +72,13 @@ def figure_edit(axes, parent=None):
7972
(None, '<b>Line</b>'),
8073
('Style', [line.get_linestyle()] + linestyles),
8174
('Width', line.get_linewidth()),
82-
('Color', col2hex(line.get_color())),
75+
('Color', line.get_color()),
8376
sep,
8477
(None, '<b>Marker</b>'),
8578
('Style', [line.get_marker()] + markers),
8679
('Size', line.get_markersize()),
87-
('Facecolor', col2hex(line.get_markerfacecolor())),
88-
('Edgecolor', col2hex(line.get_markeredgecolor())),
80+
('Facecolor', line.get_markerfacecolor()),
81+
('Edgecolor', line.get_markeredgecolor()),
8982
]
9083
curves.append([curvedata, label, ""])
9184

lib/matplotlib/backends/qt4_editor/formlayout.py

Lines changed: 27 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,11 @@
4848
import sys
4949
STDERR = sys.stderr
5050

51-
from matplotlib.backends.qt4_compat import QtGui,QtCore
52-
if not hasattr(QtGui,'QFormLayout'):
53-
raise ImportError, "Warning: formlayout requires PyQt4 >v4.3 or PySide"
51+
from matplotlib.colors import is_color_like
52+
from matplotlib.colors import rgb2hex
53+
from matplotlib.colors import colorConverter
54+
55+
from matplotlib.backends.qt4_compat import QtGui, QtCore
5456

5557
(QWidget, QLineEdit, QComboBox, QLabel, QSpinBox, QIcon,QStyle,
5658
QDialogButtonBox, QHBoxLayout, QVBoxLayout, QDialog, QColor, QPushButton,
@@ -68,6 +70,8 @@
6870
(Qt, SIGNAL, SLOT, QObject, QSize,pyqtSignature, pyqtProperty) =\
6971
(QtCore.Qt, QtCore.SIGNAL, QtCore.SLOT, QtCore.QObject, QtCore.QSize,
7072
QtCore.Slot, QtCore.Property)
73+
if not hasattr(QtGui, 'QFormLayout'):
74+
raise ImportError("Warning: formlayout requires PyQt4 >v4.3 or PySide")
7175

7276
import datetime
7377

@@ -103,41 +107,24 @@ def set_color(self, color):
103107

104108
color = pyqtProperty("QColor", get_color, set_color)
105109

110+
def col2hex(color):
111+
"""Convert matplotlib color to hex before passing to Qt"""
112+
return rgb2hex(colorConverter.to_rgb(color))
106113

107-
def text_to_qcolor(text):
108-
"""
109-
Create a QColor from specified string
110-
Avoid warning from Qt when an invalid QColor is instantiated
111-
"""
112-
color = QColor()
114+
def to_qcolor(color):
115+
"""Create a QColor from a matplotlib color"""
116+
qcolor = QColor()
113117
if isinstance(text, QObject):
114118
# actually a QString, which is not provided by the new PyQt4 API:
115119
text = str(text)
116-
if not isinstance(text, (unicode, str)):
117-
return color
118-
if text.startswith('#') and len(text)==7:
119-
correct = '#0123456789abcdef'
120-
for char in text:
121-
if char.lower() not in correct:
122-
return color
123-
elif text not in list(QColor.colorNames()):
124-
return color
125-
color.setNamedColor(text)
126-
return color
127-
128-
def is_matplotlib_color(value):
129-
"""
130-
Check if value is a color passed to us from matplotlib.
131-
It could either be a valid color string or a 3-tuple of floats between 0. and 1.
132-
"""
133-
if text_to_qcolor(value).isValid():
134-
return True
135-
if isinstance(value,tuple) and len(value)==3 and all(map(lambda v: isinstance(v,float),value)):
136-
for c in value:
137-
if c < 0. or c > 1.:
138-
return False
139-
return True
140-
return False
120+
try:
121+
color = col2hex(color)
122+
except ValueError:
123+
#print('WARNING: ignoring invalid color %r' % color)
124+
return qcolor # return invalid QColor
125+
qcolor.setNamedColor(color) # set using hex color
126+
return qcolor # return valid QColor
127+
141128

142129
class ColorLayout(QHBoxLayout):
143130
"""Color-specialized QLineEdit layout"""
@@ -154,10 +141,10 @@ def __init__(self, color, parent=None):
154141
self.update_text)
155142
self.addWidget(self.colorbtn)
156143

157-
def update_color(self, text):
158-
color = text_to_qcolor(text)
144+
def update_color(self, color):
145+
qcolor = to_qcolor(color)
159146
if color.isValid():
160-
self.colorbtn.color = color
147+
self.colorbtn.color = qcolor
161148

162149
def update_text(self, color):
163150
self.lineedit.setText(color.name())
@@ -281,8 +268,8 @@ def setup(self):
281268
continue
282269
elif tuple_to_qfont(value) is not None:
283270
field = FontLayout(value, self)
284-
elif is_matplotlib_color(value):
285-
field = ColorLayout(QColor(value), self)
271+
elif is_color_like(value):
272+
field = ColorLayout(to_qcolor(value), self)
286273
elif isinstance(value, (str, unicode)):
287274
field = QLineEdit(value, self)
288275
elif isinstance(value, (list, tuple)):
@@ -342,7 +329,7 @@ def get(self):
342329
continue
343330
elif tuple_to_qfont(value) is not None:
344331
value = field.get_font()
345-
elif isinstance(value, (str, unicode)) or is_matplotlib_color(value):
332+
elif isinstance(value, (str, unicode)) or is_color_like(value):
346333
value = unicode(field.text())
347334
elif isinstance(value, (list, tuple)):
348335
index = int(field.currentIndex())

0 commit comments

Comments
 (0)