1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
|
import sys
from typing import Tuple, List, Dict, Iterable
from AnyQt.QtCore import Qt
from AnyQt.QtWidgets import QApplication
from AnyQt.QtGui import QFont, QFontDatabase
import pyqtgraph as pg
from pyqtgraph.graphicsItems.LegendItem import ItemSample
from orangewidget.utils.visual_settings_dlg import KeyType, ValueType, \
SettingsType, FontList
_SettingType = Dict[str, ValueType]
_LegendItemType = Tuple[ItemSample, pg.LabelItem]
def available_font_families() -> List:
"""
Function returns list of available font families.
Can be used to instantiate font combo boxes.
Returns
-------
fonts: list
List of available font families.
"""
if not QApplication.instance():
_ = QApplication(sys.argv)
fonts = QFontDatabase.families()
default = default_font_family()
defaults = [default]
if default in fonts:
fonts.remove(default)
guessed_name = default.split()[0]
i = 0
while i < len(fonts):
if fonts[i].startswith(guessed_name):
defaults.append(fonts.pop(i))
else:
i += 1
return FontList(defaults
+ [""]
+ sorted(fonts, key=lambda s: s.replace(".", "")))
def default_font_family() -> str:
"""
Function returns default font family used in Qt application.
Can be used to instantiate initial dialog state.
Returns
-------
font: str
Default font family.
"""
if not QApplication.instance():
_ = QApplication(sys.argv)
return QFont().family()
def default_font_size() -> int:
"""
Function returns default font size in points used in Qt application.
Can be used to instantiate initial dialog state.
Returns
-------
size: int
Default font size in points.
"""
if not QApplication.instance():
_ = QApplication(sys.argv)
return QFont().pointSize()
class Updater:
""" Class with helper functions and constants. """
FONT_FAMILY_LABEL, SIZE_LABEL, IS_ITALIC_LABEL = \
"Font family", "Font size", "Italic"
WIDTH_LABEL, ALPHA_LABEL, STYLE_LABEL, ANTIALIAS_LABEL = \
"Width", "Opacity", "Style", "Antialias"
LINE_STYLES = {"Solid line": Qt.SolidLine,
"Dash line": Qt.DashLine,
"Dot line": Qt.DotLine,
"Dash dot line": Qt.DashDotLine,
"Dash dot dot line": Qt.DashDotDotLine}
DEFAULT_LINE_STYLE = "Solid line"
@staticmethod
def update_plot_title_text(title_item: pg.LabelItem, text: str):
title_item.text = text
title_item.setVisible(bool(text))
title_item.item.setPlainText(text)
Updater.plot_title_resize(title_item)
@staticmethod
def update_plot_title_font(title_item: pg.LabelItem,
**settings: _SettingType):
font = Updater.change_font(title_item.item.font(), settings)
title_item.item.setFont(font)
title_item.item.setPlainText(title_item.text)
Updater.plot_title_resize(title_item)
@staticmethod
def plot_title_resize(title_item):
height = title_item.item.boundingRect().height() + 6 \
if title_item.text else 0
title_item.setMaximumHeight(height)
title_item.parentItem().layout.setRowFixedHeight(0, height)
title_item.resizeEvent(None)
@staticmethod
def update_axis_title_text(item: pg.AxisItem, text: str):
item.setLabel(text, item.labelUnits, item.labelUnitPrefix)
item.resizeEvent(None)
@staticmethod
def update_axes_titles_font(items: List[pg.AxisItem],
**settings: _SettingType):
for item in items:
font = Updater.change_font(item.label.font(), settings)
default_color = pg.mkPen(pg.getConfigOption("foreground"))
item.label.setFont(font)
fstyle = ["normal", "italic"][font.italic()]
style = {"font-size": f"{font.pointSize()}pt",
"font-family": f"{font.family()}",
"color": item.labelStyle.get("color", default_color),
"font-style": f"{fstyle}"}
item.setLabel(item.labelText, item.labelUnits,
item.labelUnitPrefix, **style)
@staticmethod
def update_axes_ticks_font(items: List[pg.AxisItem],
**settings: _SettingType):
for item in items:
font = item.style["tickFont"] or QFont()
# remove when contained in setTickFont() - version 0.11.0
item.style['tickFont'] = font
item.setTickFont(Updater.change_font(font, settings))
@staticmethod
def update_legend_font(items: Iterable[_LegendItemType],
**settings: _SettingType):
for sample, label in items:
if "size" in label.opts:
# pyqtgraph added html-like support for size in 0.11.1, which
# overrides our QFont property
label.opts.pop("size")
label.setText(label.text)
sample.setFixedHeight(sample.height())
sample.setFixedWidth(sample.width())
label.item.setFont(Updater.change_font(label.item.font(), settings))
bounds = label.itemRect()
label.setMaximumWidth(bounds.width())
label.setMaximumHeight(bounds.height())
label.updateMin()
label.resizeEvent(None)
label.updateGeometry()
@staticmethod
def update_num_legend_font(legend: pg.LegendItem,
**settings: _SettingType):
if not legend:
return
for sample, _ in legend.items:
sample.set_font(Updater.change_font(sample.font, settings))
legend.setGeometry(sample.boundingRect())
@staticmethod
def update_label_font(items: List[pg.TextItem], font: QFont):
for item in items:
item.setFont(font)
@staticmethod
def change_font(font: QFont, settings: _SettingType) -> QFont:
assert all(s in (Updater.FONT_FAMILY_LABEL, Updater.SIZE_LABEL,
Updater.IS_ITALIC_LABEL) for s in settings), settings
family = settings.get(Updater.FONT_FAMILY_LABEL)
if family is not None:
font.setFamily(family)
size = settings.get(Updater.SIZE_LABEL)
if size is not None:
font.setPointSize(size)
italic = settings.get(Updater.IS_ITALIC_LABEL)
if italic is not None:
font.setItalic(italic)
return font
@staticmethod
def update_lines(items: List[pg.PlotCurveItem], **settings: _SettingType):
for item in items:
antialias = settings.get(Updater.ANTIALIAS_LABEL)
if antialias is not None:
item.setData(item.xData, item.yData, antialias=antialias)
pen = item.opts["pen"]
alpha = settings.get(Updater.ALPHA_LABEL)
if alpha is not None:
color = pen.color()
color.setAlpha(alpha)
pen.setColor(color)
style = settings.get(Updater.STYLE_LABEL)
if style is not None:
pen.setStyle(Updater.LINE_STYLES[style])
width = settings.get(Updater.WIDTH_LABEL)
if width is not None:
pen.setWidth(width)
item.setPen(pen)
@staticmethod
def update_inf_lines(items, **settings):
for item in items:
pen = item.pen
alpha = settings.get(Updater.ALPHA_LABEL)
if alpha is not None:
color = pen.color()
color.setAlpha(alpha)
pen.setColor(color)
if hasattr(item, "label"):
item.label.setColor(color)
style = settings.get(Updater.STYLE_LABEL)
if style is not None:
pen.setStyle(Updater.LINE_STYLES[style])
width = settings.get(Updater.WIDTH_LABEL)
if width is not None:
pen.setWidth(width)
item.setPen(pen)
class CommonParameterSetter:
""" Subclass to add 'setter' functionality to a plot. """
LABELS_BOX = "Fonts"
ANNOT_BOX = "Annotations"
PLOT_BOX = "Figure"
FONT_FAMILY_LABEL = "Font family"
AXIS_TITLE_LABEL = "Axis title"
AXIS_TICKS_LABEL = "Axis ticks"
LEGEND_LABEL = "Legend"
LABEL_LABEL = "Label"
LINE_LAB_LABEL = "Line label"
X_AXIS_LABEL = "x-axis title"
Y_AXIS_LABEL = "y-axis title"
TITLE_LABEL = "Title"
LINE_LABEL = "Lines"
FONT_FAMILY_SETTING = None # set in __init__ because it requires a running QApplication
FONT_SETTING = None # set in __init__ because it requires a running QApplication
LINE_SETTING: SettingsType = {
Updater.WIDTH_LABEL: (range(1, 15), 1),
Updater.ALPHA_LABEL: (range(0, 255, 5), 255),
Updater.STYLE_LABEL: (list(Updater.LINE_STYLES), Updater.DEFAULT_LINE_STYLE),
Updater.ANTIALIAS_LABEL: (None, False),
}
def __init__(self):
def update_font_family(**settings):
# false positive, pylint: disable=unsubscriptable-object
for label in self.initial_settings[self.LABELS_BOX]:
if label != self.FONT_FAMILY_LABEL:
setter = self._setters[self.LABELS_BOX][label]
setter(**settings)
def update_title(**settings):
Updater.update_plot_title_font(self.title_item, **settings)
def update_label(**settings):
self.label_font = Updater.change_font(self.label_font, settings)
Updater.update_label_font(self.labels, self.label_font)
def update_axes_titles(**settings):
Updater.update_axes_titles_font(self.axis_items, **settings)
def update_axes_ticks(**settings):
Updater.update_axes_ticks_font(self.axis_items, **settings)
def update_legend(**settings):
self.legend_settings.update(**settings)
Updater.update_legend_font(self.legend_items, **settings)
def update_title_text(**settings):
Updater.update_plot_title_text(
self.title_item, settings[self.TITLE_LABEL])
def update_axis(axis, **settings):
Updater.update_axis_title_text(
self.getAxis(axis), settings[self.TITLE_LABEL])
self.FONT_FAMILY_SETTING: SettingsType = { # pylint: disable=invalid-name
Updater.FONT_FAMILY_LABEL: (available_font_families(), default_font_family()),
}
self.FONT_SETTING: SettingsType = { # pylint: disable=invalid-name
Updater.SIZE_LABEL: (range(4, 50), QFont().pointSize()),
Updater.IS_ITALIC_LABEL: (None, False)
}
self.label_font = QFont()
self.legend_settings = {}
self._setters = {
self.LABELS_BOX: {
self.FONT_FAMILY_LABEL: update_font_family,
self.TITLE_LABEL: update_title,
self.LABEL_LABEL: update_label,
self.AXIS_TITLE_LABEL: update_axes_titles,
self.AXIS_TICKS_LABEL: update_axes_ticks,
self.LEGEND_LABEL: update_legend,
},
self.ANNOT_BOX: {
self.TITLE_LABEL: update_title_text,
self.X_AXIS_LABEL: lambda **kw: update_axis("bottom", **kw),
self.Y_AXIS_LABEL: lambda **kw: update_axis("left", **kw),
}
}
self.initial_settings: Dict[str, Dict[str, SettingsType]] = NotImplemented
self.update_setters()
self._check_setters()
def update_setters(self):
pass
def _check_setters(self):
# false positive, pylint: disable=not-an-iterable
assert all(key in self._setters for key in self.initial_settings)
for k, inner in self.initial_settings.items():
assert all(key in self._setters[k] for key in inner)
def set_parameter(self, key: KeyType, value: ValueType):
self._setters[key[0]][key[1]](**{key[2]: value})
|