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 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
|
# -*- coding: utf-8 -*-
#
# Licensed under the terms of the Qwt License
# Copyright (c) 2002 Uwe Rathmann, for the original C++ code
# Copyright (c) 2015 Pierre Raybaut, for the Python translation/optimization
# (see LICENSE file for more details)
"""
QwtAbstractScaleDraw
--------------------
.. autoclass:: QwtAbstractScaleDraw
:members:
QwtScaleDraw
------------
.. autoclass:: QwtScaleDraw
:members:
"""
import math
from datetime import datetime
from qtpy.QtCore import (
QLineF,
QObject,
QPoint,
QPointF,
QRect,
QRectF,
Qt,
qFuzzyCompare,
)
from qtpy.QtGui import QFontMetrics, QPalette, QTransform
from qwt._math import qwtRadians
from qwt.scale_div import QwtScaleDiv
from qwt.scale_map import QwtScaleMap
from qwt.text import QwtText
class QwtAbstractScaleDraw_PrivateData(QObject):
def __init__(self):
QObject.__init__(self)
self.spacing = 4
self.penWidth = 0
self.minExtent = 0.0
self.components = (
QwtAbstractScaleDraw.Backbone
| QwtAbstractScaleDraw.Ticks
| QwtAbstractScaleDraw.Labels
)
self.tick_length = {
QwtScaleDiv.MinorTick: 4.0,
QwtScaleDiv.MediumTick: 6.0,
QwtScaleDiv.MajorTick: 8.0,
}
self.tick_lighter_factor = {
QwtScaleDiv.MinorTick: 100,
QwtScaleDiv.MediumTick: 100,
QwtScaleDiv.MajorTick: 100,
}
self.map = QwtScaleMap()
self.scaleDiv = QwtScaleDiv()
self.labelCache = {}
class QwtAbstractScaleDraw(object):
"""
A abstract base class for drawing scales
`QwtAbstractScaleDraw` can be used to draw linear or logarithmic scales.
After a scale division has been specified as a `QwtScaleDiv` object
using `setScaleDiv()`, the scale can be drawn with the `draw()` member.
Scale components:
* `QwtAbstractScaleDraw.Backbone`: Backbone = the line where the ticks are located
* `QwtAbstractScaleDraw.Ticks`: Ticks
* `QwtAbstractScaleDraw.Labels`: Labels
.. py:class:: QwtAbstractScaleDraw()
The range of the scale is initialized to [0, 100],
The spacing (distance between ticks and labels) is
set to 4, the tick lengths are set to 4,6 and 8 pixels
"""
# enum ScaleComponent
Backbone = 0x01
Ticks = 0x02
Labels = 0x04
def __init__(self):
self.__data = QwtAbstractScaleDraw_PrivateData()
def extent(self, font):
"""
Calculate the extent
The extent is the distance from the baseline to the outermost
pixel of the scale draw in opposite to its orientation.
It is at least minimumExtent() pixels.
:param QFont font: Font used for drawing the tick labels
:return: Number of pixels
.. seealso::
:py:meth:`setMinimumExtent()`, :py:meth:`minimumExtent()`
"""
return 0.0
def drawTick(self, painter, value, len_):
"""
Draw a tick
:param QPainter painter: Painter
:param float value: Value of the tick
:param float len: Length of the tick
.. seealso::
:py:meth:`drawBackbone()`, :py:meth:`drawLabel()`
"""
pass
def drawBackbone(self, painter):
"""
Draws the baseline of the scale
:param QPainter painter: Painter
.. seealso::
:py:meth:`drawTick()`, :py:meth:`drawLabel()`
"""
pass
def drawLabel(self, painter, value):
"""
Draws the label for a major scale tick
:param QPainter painter: Painter
:param float value: Value
.. seealso::
:py:meth:`drawTick()`, :py:meth:`drawBackbone()`
"""
pass
def enableComponent(self, component, enable):
"""
En/Disable a component of the scale
:param int component: Scale component
:param bool enable: On/Off
.. seealso::
:py:meth:`hasComponent()`
"""
if enable:
self.__data.components |= component
else:
self.__data.components &= ~component
def hasComponent(self, component):
"""
Check if a component is enabled
:param int component: Component type
:return: True, when component is enabled
.. seealso::
:py:meth:`enableComponent()`
"""
return self.__data.components & component
def setScaleDiv(self, scaleDiv):
"""
Change the scale division
:param qwt.scale_div.QwtScaleDiv scaleDiv: New scale division
"""
self.__data.scaleDiv = scaleDiv
self.__data.map.setScaleInterval(scaleDiv.lowerBound(), scaleDiv.upperBound())
self.invalidateCache()
def setTransformation(self, transformation):
"""
Change the transformation of the scale
:param qwt.transform.QwtTransform transformation: New scale transformation
"""
self.__data.map.setTransformation(transformation)
def scaleMap(self):
"""
:return: Map how to translate between scale and pixel values
"""
return self.__data.map
def scaleDiv(self):
"""
:return: scale division
"""
return self.__data.scaleDiv
def setPenWidth(self, width):
"""
Specify the width of the scale pen
:param int width: Pen width
.. seealso::
:py:meth:`penWidth()`
"""
if width < 0:
width = 0
if width != self.__data.penWidth:
self.__data.penWidth = width
def penWidth(self):
"""
:return: Scale pen width
.. seealso::
:py:meth:`setPenWidth()`
"""
return self.__data.penWidth
def draw(self, painter, palette):
"""
Draw the scale
:param QPainter painter: The painter
:param QPalette palette: Palette, text color is used for the labels,
foreground color for ticks and backbone
"""
painter.save()
pen = painter.pen()
pen.setWidth(self.__data.penWidth)
pen.setCosmetic(False)
painter.setPen(pen)
if self.hasComponent(QwtAbstractScaleDraw.Labels):
painter.save()
painter.setPen(palette.color(QPalette.Text))
majorTicks = self.__data.scaleDiv.ticks(QwtScaleDiv.MajorTick)
for v in majorTicks:
if self.__data.scaleDiv.contains(v):
self.drawLabel(painter, v)
painter.restore()
if self.hasComponent(QwtAbstractScaleDraw.Ticks):
painter.save()
pen = painter.pen()
pen.setCapStyle(Qt.FlatCap)
default_color = palette.color(QPalette.WindowText)
for tickType in range(QwtScaleDiv.NTickTypes):
tickLen = self.__data.tick_length[tickType]
if tickLen <= 0.0:
continue
factor = self.__data.tick_lighter_factor[tickType]
pen.setColor(default_color.lighter(factor))
painter.setPen(pen)
ticks = self.__data.scaleDiv.ticks(tickType)
for v in ticks:
if self.__data.scaleDiv.contains(v):
self.drawTick(painter, v, tickLen)
painter.restore()
if self.hasComponent(QwtAbstractScaleDraw.Backbone):
painter.save()
pen = painter.pen()
pen.setColor(palette.color(QPalette.WindowText))
pen.setCapStyle(Qt.FlatCap)
painter.setPen(pen)
self.drawBackbone(painter)
painter.restore()
painter.restore()
def setSpacing(self, spacing):
"""
Set the spacing between tick and labels
The spacing is the distance between ticks and labels.
The default spacing is 4 pixels.
:param float spacing: Spacing
.. seealso::
:py:meth:`spacing()`
"""
if spacing < 0:
spacing = 0
self.__data.spacing = spacing
def spacing(self):
"""
Get the spacing
The spacing is the distance between ticks and labels.
The default spacing is 4 pixels.
:return: Spacing
.. seealso::
:py:meth:`setSpacing()`
"""
return self.__data.spacing
def setMinimumExtent(self, minExtent):
"""
Set a minimum for the extent
The extent is calculated from the components of the
scale draw. In situations, where the labels are
changing and the layout depends on the extent (f.e scrolling
a scale), setting an upper limit as minimum extent will
avoid jumps of the layout.
:param float minExtent: Minimum extent
.. seealso::
:py:meth:`extent()`, :py:meth:`minimumExtent()`
"""
if minExtent < 0.0:
minExtent = 0.0
self.__data.minExtent = minExtent
def minimumExtent(self):
"""
Get the minimum extent
:return: Minimum extent
.. seealso::
:py:meth:`extent()`, :py:meth:`setMinimumExtent()`
"""
return self.__data.minExtent
def setTickLength(self, tick_type, length):
"""
Set the length of the ticks
:param int tick_type: Tick type
:param float length: New length
.. warning::
the length is limited to [0..1000]
"""
if tick_type not in self.__data.tick_length:
raise ValueError("Invalid tick type: %r" % tick_type)
self.__data.tick_length[tick_type] = min([1000.0, max([0.0, length])])
def tickLength(self, tick_type):
"""
:param int tick_type: Tick type
:return: Length of the ticks
.. seealso::
:py:meth:`setTickLength()`, :py:meth:`maxTickLength()`
"""
if tick_type not in self.__data.tick_length:
raise ValueError("Invalid tick type: %r" % tick_type)
return self.__data.tick_length[tick_type]
def maxTickLength(self):
"""
:return: Length of the longest tick
Useful for layout calculations
.. seealso::
:py:meth:`tickLength()`, :py:meth:`setTickLength()`
"""
return max([0.0] + list(self.__data.tick_length.values()))
def setTickLighterFactor(self, tick_type, factor):
"""
Set the color lighter factor of the ticks
:param int tick_type: Tick type
:param int factor: New factor
"""
if tick_type not in self.__data.tick_length:
raise ValueError("Invalid tick type: %r" % tick_type)
self.__data.tick_lighter_factor[tick_type] = min([0, factor])
def tickLighterFactor(self, tick_type):
"""
:param int tick_type: Tick type
:return: Color lighter factor of the ticks
.. seealso::
:py:meth:`setTickLighterFactor()`
"""
if tick_type not in self.__data.tick_length:
raise ValueError("Invalid tick type: %r" % tick_type)
return self.__data.tick_lighter_factor[tick_type]
def label(self, value):
"""
Convert a value into its representing label
The value is converted to a plain text using
`QLocale().toString(value)`.
This method is often overloaded by applications to have individual
labels.
:param float value: Value
:return: Label string
"""
# Adding a space before the value is a way to add a margin on the left
# of the scale. This helps to avoid truncating the first digit of the
# tick labels while keeping a tight layout.
return " %g" % value
def tickLabel(self, font, value):
"""
Convert a value into its representing label and cache it.
The conversion between value and label is called very often
in the layout and painting code. Unfortunately the
calculation of the label sizes might be slow (really slow
for rich text in Qt4), so it's necessary to cache the labels.
:param QFont font: Font
:param float value: Value
:return: Tuple (tick label, text size)
"""
lbl = self.__data.labelCache.get(value)
if lbl is None:
lbl = QwtText(self.label(value))
lbl.setRenderFlags(0)
lbl.setLayoutAttribute(QwtText.MinimumLayout)
self.__data.labelCache[value] = lbl
return lbl, lbl.textSize(font)
def invalidateCache(self):
"""
Invalidate the cache used by `tickLabel()`
The cache is invalidated, when a new `QwtScaleDiv` is set. If
the labels need to be changed. while the same `QwtScaleDiv` is set,
`invalidateCache()` needs to be called manually.
"""
self.__data.labelCache.clear()
class QwtScaleDraw_PrivateData(QObject):
def __init__(self):
QObject.__init__(self)
self.len = 0
self.alignment = QwtScaleDraw.BottomScale
self.labelAlignment = 0
self.labelRotation = 0.0
self.labelAutoSize = True
self.pos = QPointF()
class QwtScaleDraw(QwtAbstractScaleDraw):
"""
A class for drawing scales
QwtScaleDraw can be used to draw linear or logarithmic scales.
A scale has a position, an alignment and a length, which can be specified .
The labels can be rotated and aligned
to the ticks using `setLabelRotation()` and `setLabelAlignment()`.
After a scale division has been specified as a QwtScaleDiv object
using `QwtAbstractScaleDraw.setScaleDiv(scaleDiv)`,
the scale can be drawn with the `QwtAbstractScaleDraw.draw()` member.
Alignment of the scale draw:
* `QwtScaleDraw.BottomScale`: The scale is below
* `QwtScaleDraw.TopScale`: The scale is above
* `QwtScaleDraw.LeftScale`: The scale is left
* `QwtScaleDraw.RightScale`: The scale is right
.. py:class:: QwtScaleDraw()
The range of the scale is initialized to [0, 100],
The position is at (0, 0) with a length of 100.
The orientation is `QwtAbstractScaleDraw.Bottom`.
"""
# enum Alignment
BottomScale, TopScale, LeftScale, RightScale = list(range(4))
Flags = (
Qt.AlignHCenter | Qt.AlignBottom, # BottomScale
Qt.AlignHCenter | Qt.AlignTop, # TopScale
Qt.AlignLeft | Qt.AlignVCenter, # LeftScale
Qt.AlignRight | Qt.AlignVCenter, # RightScale
)
def __init__(self):
QwtAbstractScaleDraw.__init__(self)
self.__data = QwtScaleDraw_PrivateData()
self.setLength(100)
self._max_label_sizes = {}
def alignment(self):
"""
:return: Alignment of the scale
.. seealso::
:py:meth:`setAlignment()`
"""
return self.__data.alignment
def setAlignment(self, align):
"""
Set the alignment of the scale
:param int align: Alignment of the scale
Alignment of the scale draw:
* `QwtScaleDraw.BottomScale`: The scale is below
* `QwtScaleDraw.TopScale`: The scale is above
* `QwtScaleDraw.LeftScale`: The scale is left
* `QwtScaleDraw.RightScale`: The scale is right
The default alignment is `QwtScaleDraw.BottomScale`
.. seealso::
:py:meth:`alignment()`
"""
self.__data.alignment = align
def orientation(self):
"""
Return the orientation
TopScale, BottomScale are horizontal (`Qt.Horizontal`) scales,
LeftScale, RightScale are vertical (`Qt.Vertical`) scales.
:return: Orientation of the scale
.. seealso::
:py:meth:`alignment()`
"""
if self.__data.alignment in (self.TopScale, self.BottomScale):
return Qt.Horizontal
elif self.__data.alignment in (self.LeftScale, self.RightScale):
return Qt.Vertical
def getBorderDistHint(self, font):
"""
Determine the minimum border distance
This member function returns the minimum space
needed to draw the mark labels at the scale's endpoints.
:param QFont font: Font
:return: tuple `(start, end)`
Returned tuple:
* start: Start border distance
* end: End border distance
"""
start, end = 0, 1.0
if not self.hasComponent(QwtAbstractScaleDraw.Labels):
return start, end
ticks = self.scaleDiv().ticks(QwtScaleDiv.MajorTick)
if len(ticks) == 0:
return start, end
minTick = ticks[0]
minPos = self.scaleMap().transform(minTick)
maxTick = minTick
maxPos = minPos
for tick in ticks:
tickPos = self.scaleMap().transform(tick)
if tickPos < minPos:
minTick = tick
minPos = tickPos
if tickPos > self.scaleMap().transform(maxTick):
maxTick = tick
maxPos = tickPos
s = 0.0
e = 0.0
if self.orientation() == Qt.Vertical:
s = -self.labelRect(font, minTick).top()
s -= abs(minPos - round(self.scaleMap().p2()))
e = self.labelRect(font, maxTick).bottom()
e -= abs(maxPos - self.scaleMap().p1())
else:
s = -self.labelRect(font, minTick).left()
s -= abs(minPos - self.scaleMap().p1())
e = self.labelRect(font, maxTick).right()
e -= abs(maxPos - self.scaleMap().p2())
return max(math.ceil(s), 0), max(math.ceil(e), 0)
def minLabelDist(self, font):
"""
Determine the minimum distance between two labels, that is necessary
that the texts don't overlap.
:param QFont font: Font
:return: The maximum width of a label
.. seealso::
:py:meth:`getBorderDistHint()`
"""
if not self.hasComponent(QwtAbstractScaleDraw.Labels):
return 0
ticks = self.scaleDiv().ticks(QwtScaleDiv.MajorTick)
if not ticks:
return 0
fm = QFontMetrics(font)
vertical = self.orientation() == Qt.Vertical
bRect1 = QRectF()
bRect2 = self.labelRect(font, ticks[0])
if vertical:
bRect2.setRect(-bRect2.bottom(), 0.0, bRect2.height(), bRect2.width())
maxDist = 0.0
for tick in ticks:
bRect1 = bRect2
bRect2 = self.labelRect(font, tick)
if vertical:
bRect2.setRect(-bRect2.bottom(), 0.0, bRect2.height(), bRect2.width())
dist = fm.leading()
if bRect1.right() > 0:
dist += bRect1.right()
if bRect2.left() < 0:
dist += -bRect2.left()
if dist > maxDist:
maxDist = dist
angle = qwtRadians(self.labelRotation())
if vertical:
angle += math.pi / 2
sinA = math.sin(angle)
if qFuzzyCompare(sinA + 1.0, 1.0):
return math.ceil(maxDist)
fmHeight = fm.ascent() - 2
labelDist = fmHeight / math.sin(angle) * math.cos(angle)
if labelDist < 0:
labelDist = -labelDist
if labelDist > maxDist:
labelDist = maxDist
if labelDist < fmHeight:
labelDist = fmHeight
return math.ceil(labelDist)
def extent(self, font):
"""
Calculate the width/height that is needed for a
vertical/horizontal scale.
The extent is calculated from the pen width of the backbone,
the major tick length, the spacing and the maximum width/height
of the labels.
:param QFont font: Font used for painting the labels
:return: Extent
.. seealso::
:py:meth:`minLength()`
"""
d = 0.0
if self.hasComponent(QwtAbstractScaleDraw.Labels):
if self.orientation() == Qt.Vertical:
d = self.maxLabelWidth(font)
else:
d = self.maxLabelHeight(font)
if d > 0:
d += self.spacing()
if self.hasComponent(QwtAbstractScaleDraw.Ticks):
d += self.maxTickLength()
if self.hasComponent(QwtAbstractScaleDraw.Backbone):
pw = max([1, self.penWidth()])
d += pw
return max([d, self.minimumExtent()])
def minLength(self, font):
"""
Calculate the minimum length that is needed to draw the scale
:param QFont font: Font used for painting the labels
:return: Minimum length that is needed to draw the scale
.. seealso::
:py:meth:`extent()`
"""
startDist, endDist = self.getBorderDistHint(font)
sd = self.scaleDiv()
minorCount = len(sd.ticks(QwtScaleDiv.MinorTick)) + len(
sd.ticks(QwtScaleDiv.MediumTick)
)
majorCount = len(sd.ticks(QwtScaleDiv.MajorTick))
lengthForLabels = 0
if self.hasComponent(QwtAbstractScaleDraw.Labels):
lengthForLabels = self.minLabelDist(font) * majorCount
lengthForTicks = 0
if self.hasComponent(QwtAbstractScaleDraw.Ticks):
pw = max([1, self.penWidth()])
lengthForTicks = math.ceil((majorCount + minorCount) * (pw + 1.0))
return startDist + endDist + max([lengthForLabels, lengthForTicks])
def labelPosition(self, value):
"""
Find the position, where to paint a label
The position has a distance that depends on the length of the ticks
in direction of the `alignment()`.
:param float value: Value
:return: Position, where to paint a label
"""
tval = self.scaleMap().transform(value)
dist = self.spacing()
if self.hasComponent(QwtAbstractScaleDraw.Backbone):
dist += max([1, self.penWidth()])
if self.hasComponent(QwtAbstractScaleDraw.Ticks):
dist += self.tickLength(QwtScaleDiv.MajorTick)
px = 0
py = 0
if self.alignment() == self.RightScale:
px = self.__data.pos.x() + dist
py = tval
elif self.alignment() == self.LeftScale:
px = self.__data.pos.x() - dist
py = tval
elif self.alignment() == self.BottomScale:
px = tval
py = self.__data.pos.y() + dist
elif self.alignment() == self.TopScale:
px = tval
py = self.__data.pos.y() - dist
return QPointF(px, py)
def drawTick(self, painter, value, len_):
"""
Draw a tick
:param QPainter painter: Painter
:param float value: Value of the tick
:param float len: Length of the tick
.. seealso::
:py:meth:`drawBackbone()`, :py:meth:`drawLabel()`
"""
if len_ <= 0:
return
pos = self.__data.pos
tval = self.scaleMap().transform(value)
pw = self.penWidth()
a = 0
if self.alignment() == self.LeftScale:
x1 = pos.x() + a
x2 = pos.x() + a - pw - len_
painter.drawLine(QLineF(x1, tval, x2, tval))
elif self.alignment() == self.RightScale:
x1 = pos.x()
x2 = pos.x() + pw + len_
painter.drawLine(QLineF(x1, tval, x2, tval))
elif self.alignment() == self.BottomScale:
y1 = pos.y()
y2 = pos.y() + pw + len_
painter.drawLine(QLineF(tval, y1, tval, y2))
elif self.alignment() == self.TopScale:
y1 = pos.y() + a
y2 = pos.y() - pw - len_ + a
painter.drawLine(QLineF(tval, y1, tval, y2))
def drawBackbone(self, painter):
"""
Draws the baseline of the scale
:param QPainter painter: Painter
.. seealso::
:py:meth:`drawTick()`, :py:meth:`drawLabel()`
"""
pos = self.__data.pos
len_ = self.__data.len
off = 0.5 * self.penWidth()
if self.alignment() == self.LeftScale:
x = pos.x() - off
painter.drawLine(QLineF(x, pos.y(), x, pos.y() + len_))
elif self.alignment() == self.RightScale:
x = pos.x() + off
painter.drawLine(QLineF(x, pos.y(), x, pos.y() + len_))
elif self.alignment() == self.TopScale:
y = pos.y() - off
painter.drawLine(QLineF(pos.x(), y, pos.x() + len_, y))
elif self.alignment() == self.BottomScale:
y = pos.y() + off
painter.drawLine(QLineF(pos.x(), y, pos.x() + len_, y))
def move(self, *args):
"""
Move the position of the scale
The meaning of the parameter pos depends on the alignment:
* `QwtScaleDraw.LeftScale`:
The origin is the topmost point of the backbone. The backbone is a
vertical line. Scale marks and labels are drawn at the left of the
backbone.
* `QwtScaleDraw.RightScale`:
The origin is the topmost point of the backbone. The backbone is a
vertical line. Scale marks and labels are drawn at the right of
the backbone.
* `QwtScaleDraw.TopScale`:
The origin is the leftmost point of the backbone. The backbone is
a horizontal line. Scale marks and labels are drawn above the
backbone.
* `QwtScaleDraw.BottomScale`:
The origin is the leftmost point of the backbone. The backbone is
a horizontal line Scale marks and labels are drawn below the
backbone.
.. py:method:: move(x, y)
:noindex:
:param float x: X coordinate
:param float y: Y coordinate
.. py:method:: move(pos)
:noindex:
:param QPointF pos: position
.. seealso::
:py:meth:`pos()`, :py:meth:`setLength()`
"""
if len(args) == 2:
x, y = args
self.move(QPointF(x, y))
elif len(args) == 1:
(pos,) = args
self.__data.pos = pos
self.updateMap()
else:
raise TypeError(
"%s().move() takes 1 or 2 argument(s) (%s given)"
% (self.__class__.__name__, len(args))
)
def pos(self):
"""
:return: Origin of the scale
.. seealso::
:py:meth:`pos()`, :py:meth:`setLength()`
"""
return self.__data.pos
def setLength(self, length):
"""
Set the length of the backbone.
The length doesn't include the space needed for overlapping labels.
:param float length: Length of the backbone
.. seealso::
:py:meth:`move()`, :py:meth:`minLabelDist()`
"""
if length >= 0 and length < 10:
length = 10
if length < 0 and length > -10:
length = -10
self.__data.len = length
self.updateMap()
def length(self):
"""
:return: the length of the backbone
.. seealso::
:py:meth:`setLength()`, :py:meth:`pos()`
"""
return self.__data.len
def drawLabel(self, painter, value):
"""
Draws the label for a major scale tick
:param QPainter painter: Painter
:param float value: Value
.. seealso::
:py:meth:`drawTick()`, :py:meth:`drawBackbone()`,
:py:meth:`boundingLabelRect()`
"""
lbl, labelSize = self.tickLabel(painter.font(), value)
if lbl is None or lbl.isEmpty():
return
pos = self.labelPosition(value)
transform = self.labelTransformation(pos, labelSize)
painter.save()
painter.setWorldTransform(transform, True)
lbl.draw(painter, QRect(QPoint(0, 0), labelSize.toSize()))
painter.restore()
def boundingLabelRect(self, font, value):
"""
Find the bounding rectangle for the label.
The coordinates of the rectangle are absolute (calculated from
`pos()`) in direction of the tick.
:param QFont font: Font used for painting
:param float value: Value
:return: Bounding rectangle
.. seealso::
:py:meth:`labelRect()`
"""
lbl, labelSize = self.tickLabel(font, value)
if lbl.isEmpty():
return QRect()
pos = self.labelPosition(value)
transform = self.labelTransformation(pos, labelSize)
return transform.mapRect(QRect(QPoint(0, 0), labelSize.toSize()))
def labelTransformation(self, pos, size):
"""
Calculate the transformation that is needed to paint a label
depending on its alignment and rotation.
:param QPointF pos: Position where to paint the label
:param QSizeF size: Size of the label
:return: Transformation matrix
.. seealso::
:py:meth:`setLabelAlignment()`, :py:meth:`setLabelRotation()`
"""
transform = QTransform()
transform.translate(pos.x(), pos.y())
transform.rotate(self.labelRotation())
flags = self.labelAlignment()
if flags == 0:
flags = self.Flags[self.alignment()]
if flags & Qt.AlignLeft:
x = -size.width()
elif flags & Qt.AlignRight:
x = 0.0
else:
x = -(0.5 * size.width())
if flags & Qt.AlignTop:
y = -size.height()
elif flags & Qt.AlignBottom:
y = 0
else:
y = -(0.5 * size.height())
transform.translate(x, y)
return transform
def labelRect(self, font, value):
"""
Find the bounding rectangle for the label. The coordinates of
the rectangle are relative to spacing + tick length from the backbone
in direction of the tick.
:param QFont font: Font used for painting
:param float value: Value
:return: Bounding rectangle that is needed to draw a label
"""
lbl, labelSize = self.tickLabel(font, value)
if not lbl or lbl.isEmpty():
return QRectF(0.0, 0.0, 0.0, 0.0)
pos = self.labelPosition(value)
transform = self.labelTransformation(pos, labelSize)
br = transform.mapRect(QRectF(QPointF(0, 0), labelSize))
br.translate(-pos.x(), -pos.y())
return br
def labelSize(self, font, value):
"""
Calculate the size that is needed to draw a label
:param QFont font: Label font
:param float value: Value
:return: Size that is needed to draw a label
"""
return self.labelRect(font, value).size()
def setLabelRotation(self, rotation):
"""
Rotate all labels.
When changing the rotation, it might be necessary to
adjust the label flags too. Finding a useful combination is
often the result of try and error.
:param float rotation: Angle in degrees. When changing the label rotation, the
label flags often needs to be adjusted too.
.. seealso::
:py:meth:`setLabelAlignment()`, :py:meth:`labelRotation()`,
:py:meth:`labelAlignment()`
"""
self.__data.labelRotation = rotation
def labelRotation(self):
"""
:return: the label rotation
.. seealso::
:py:meth:`setLabelRotation()`, :py:meth:`labelAlignment()`
"""
return self.__data.labelRotation
def setLabelAlignment(self, alignment):
"""
Change the label flags
Labels are aligned to the point tick length + spacing away from the
backbone.
The alignment is relative to the orientation of the label text.
In case of an flags of 0 the label will be aligned
depending on the orientation of the scale:
* `QwtScaleDraw.TopScale`: `Qt.AlignHCenter | Qt.AlignTop`
* `QwtScaleDraw.BottomScale`: `Qt.AlignHCenter | Qt.AlignBottom`
* `QwtScaleDraw.LeftScale`: `Qt.AlignLeft | Qt.AlignVCenter`
* `QwtScaleDraw.RightScale`: `Qt.AlignRight | Qt.AlignVCenter`
Changing the alignment is often necessary for rotated labels.
:param Qt.Alignment alignment Or'd `Qt.AlignmentFlags`
.. seealso::
:py:meth:`setLabelRotation()`, :py:meth:`labelRotation()`,
:py:meth:`labelAlignment()`
.. warning::
The various alignments might be confusing. The alignment of the
label is not the alignment of the scale and is not the alignment
of the flags (`QwtText.flags()`) returned from
`QwtAbstractScaleDraw.label()`.
"""
self.__data.labelAlignment = alignment
def labelAlignment(self):
"""
:return: the label flags
.. seealso::
:py:meth:`setLabelAlignment()`, :py:meth:`labelRotation()`
"""
return self.__data.labelAlignment
def setLabelAutoSize(self, state):
"""
Set label automatic size option state
When drawing text labels, if automatic size mode is enabled (default
behavior), the axes are drawn in order to optimize layout space and
depends on text label individual sizes. Otherwise, width and height
won't change when axis range is changing.
This option is not implemented in Qwt C++ library: this may be used
either as an optimization (updating plot layout is faster when this
option is enabled) or as an appearance preference (with Qwt default
behavior, the size of axes may change when zooming and/or panning
plot canvas which in some cases may not be desired).
:param bool state: On/off
.. seealso::
:py:meth:`labelAutoSize()`
"""
self.__data.labelAutoSize = state
def labelAutoSize(self):
"""
:return: True if automatic size option is enabled for labels
.. seealso::
:py:meth:`setLabelAutoSize()`
"""
return self.__data.labelAutoSize
def _get_max_label_size(self, font):
key = (font.toString(), self.labelRotation())
size = self._max_label_sizes.get(key)
if size is None:
size = self.labelSize(font, -999999) # -999999 is the biggest label
size.setWidth(math.ceil(size.width()))
size.setHeight(math.ceil(size.height()))
return self._max_label_sizes.setdefault(key, size)
else:
return size
def maxLabelWidth(self, font):
"""
:param QFont font: Font
:return: the maximum width of a label
"""
ticks = self.scaleDiv().ticks(QwtScaleDiv.MajorTick)
if not ticks:
return 0
if self.labelAutoSize():
vmax = sorted(
[v for v in ticks if self.scaleDiv().contains(v)],
key=lambda obj: len("%g" % obj),
)[-1]
return math.ceil(self.labelSize(font, vmax).width())
## Original implementation (closer to Qwt's C++ code, but slower):
# return math.ceil(max([self.labelSize(font, v).width()
# for v in ticks if self.scaleDiv().contains(v)]))
else:
return self._get_max_label_size(font).width()
def maxLabelHeight(self, font):
"""
:param QFont font: Font
:return: the maximum height of a label
"""
ticks = self.scaleDiv().ticks(QwtScaleDiv.MajorTick)
if not ticks:
return 0
if self.labelAutoSize():
vmax = sorted(
[v for v in ticks if self.scaleDiv().contains(v)],
key=lambda obj: len("%g" % obj),
)[-1]
return math.ceil(self.labelSize(font, vmax).height())
## Original implementation (closer to Qwt's C++ code, but slower):
# return math.ceil(max([self.labelSize(font, v).height()
# for v in ticks if self.scaleDiv().contains(v)]))
else:
return self._get_max_label_size(font).height()
def updateMap(self):
pos = self.__data.pos
len_ = self.__data.len
sm = self.scaleMap()
if self.orientation() == Qt.Vertical:
sm.setPaintInterval(pos.y() + len_, pos.y())
else:
sm.setPaintInterval(pos.x(), pos.x() + len_)
class QwtDateTimeScaleDraw(QwtScaleDraw):
"""Scale draw for datetime axis
This class formats axis labels as date/time strings from Unix timestamps.
Args:
format: Format string for datetime display (default: "%Y-%m-%d %H:%M:%S").
Uses Python datetime.strftime() format codes.
spacing: Spacing between labels (default: 4)
Examples:
>>> # Create a datetime scale with default format
>>> scale = QwtDateTimeScaleDraw()
>>> # Create a datetime scale with custom format (time only)
>>> scale = QwtDateTimeScaleDraw(format="%H:%M:%S")
>>> # Create a datetime scale with date only
>>> scale = QwtDateTimeScaleDraw(format="%Y-%m-%d", spacing=4)
"""
def __init__(self, format: str = "%Y-%m-%d %H:%M:%S", spacing: int = 4) -> None:
super().__init__()
self._format = format
self.setSpacing(spacing)
def get_format(self) -> str:
"""Get the current datetime format string
Returns:
str: Format string
"""
return self._format
def set_format(self, format: str) -> None:
"""Set the datetime format string
Args:
format: Format string for datetime display
"""
self._format = format
def label(self, value: float) -> QwtText:
"""Convert a timestamp value to a formatted date/time label
Args:
value: Unix timestamp (seconds since epoch)
Returns:
QwtText: Formatted label
"""
try:
dt = datetime.fromtimestamp(value)
return QwtText(dt.strftime(self._format))
except (ValueError, OSError):
# Handle invalid timestamps
return QwtText("")
|