forked from DKStudio/QtPropertyBrowserV2.6-for-pyqt5
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathqtcanvas.py
5294 lines (4837 loc) · 173 KB
/
qtcanvas.py
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
# -*- coding: utf-8 -*-
#############################################################################
##
## Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
## Contact: http:#www.qt-project.org/legal
##
## This file is part of the Qt Solutions component.
##
## $QT_BEGIN_LICENSE:BSD$
## You may use this file under the terms of the BSD license as follows:
##
## "Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions are
## met:
## * Redistributions of source code must retain the above copyright
## notice, this list of conditions and the following disclaimer.
## * Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in
## the documentation and/or other materials provided with the
## distribution.
## * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
## of its contributors may be used to endorse or promote products derived
## from this software without specific prior written permission.
##
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
##
## $QT_END_LICENSE$
##
#############################################################################
import sys
import os
filePath = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(filePath,'QtProperty'))
sys.path.append(os.path.join(filePath,'libqt5'))
#print(sys.path)
from array import array
from qtpy.QtGui import QTransform as QMatrix
from qtpy.QtCore import (
Qt,
QRect,
QTimer,
QPoint,
QSize,
qWarning,
QRectF,
Signal,
QObject
)
from qtpy.QtGui import (
QRegion,
QImage,
QPolygon,
QPixmap,
QPainter,
QPainterPath,
QPen,
QBrush,
QFontMetrics,
QFont,
QColor
)
from qtpy.QtWidgets import (
QWidget,
QApplication,
QScrollArea
)
from pyqtcore import QSet, QList
from enum import Enum
class QPolygonEx(QPolygon):
def resize(self, n):
_n = self.size()
for i in range(n-_n):
self.append(QPoint())
for i in range(_n-n):
self.remove(self.size()-1)
def detach(self):
pass
def qt_testCollision(s1, s2):
s2image = s2.imageAdvanced().collision_mask
s2area = s2.boundingRectAdvanced()
cyourarea = QRect(s2area.x(), s2area.y(), s2area.width(), s2area.height())
s1image = s1.imageAdvanced().collision_mask
s1area = s1.boundingRectAdvanced()
ourarea = s1area.intersected(cyourarea)
if (ourarea.isEmpty()):
return False
x2 = ourarea.x()-cyourarea.x()
y2 = ourarea.y()-cyourarea.y()
x1 = ourarea.x()-s1area.x()
y1 = ourarea.y()-s1area.y()
w = ourarea.width()
h = ourarea.height()
if (not s2image):
if (not s1image):
return w>0 and h>0
# swap everything around
t = x1; x1 = x2; x2 = t
t = y1; x1 = y2; y2 = t
s2image = s1image
s1image = 0
# s2image != 0
# A non-linear search may be more efficient.
# Perhaps spiralling out from the center, or a simpler
# vertical expansion from the centreline.
# We assume that sprite masks don't have
# different bit orders.
#
# Q_ASSERT(s1image.bitOrder() == s2image.bitOrder())
if (s1image):
if (s1image.format() == QImage.Format_MonoLSB):
for j in range(h):
ml = s1image.scanLine(y1+j)
yl = s2image.scanLine(y2+j)
for i in range(w):
if (yl + ((x2+i) >> 3) & (1 << ((x2+i) & 7)) and ml + ((x1+i) >> 3) & (1 << ((x1+i) & 7))):
return True
else:
for j in range(h):
ml = s1image.scanLine(y1+j)
yl = s2image.scanLine(y2+j)
for i in range(w):
if (yl + ((x2+i) >> 3) & (1 << (7-((x2+i) & 7))) and ml + ((x1+i) >> 3) & (1 << (7-((x1+i) & 7)))):
return True
else:
if (s2image.format() == QImage.Format_MonoLSB):
for j in range(h):
yl = s2image.scanLine(y2+j)
for i in range(w):
if ((yl + ((x2+i) >> 3)) & (1 << ((x2+i) & 7))):
return True
else:
for j in range(h):
yl = s2image.scanLine(y2+j)
for i in range(w):
if ((yl + ((x2+i) >> 3)) & (1 << (7-((x2+i) & 7)))):
return True
return False
def collision_double_dispatch(s1, p1, r1, e1, t1, s2, p2, r2, e2, t2):
if s1:
i1 = s1
elif p1:
i1 = p1
elif r1:
i1 = r1
elif e1:
i1 = e1
elif t1:
i1 = t1
if s2:
i2 = s2
elif p2:
i2 = p2
elif r2:
i2 = r2
elif e2:
i2 = e2
elif t2:
i2 = t2
if (s1 and s2):
# a
return qt_testCollision(s1, s2)
elif ((r1 or t1 or s1) and (r2 or t2 or s2)):
# b
rc1 = i1.boundingRectAdvanced()
rc2 = i2.boundingRectAdvanced()
return rc1.intersects(rc2)
elif (e1 and e2
and e1.angleLength()>= 360*16 and e2.angleLength()>= 360*16
and e1.width() == e1.height()
and e2.width() == e2.height()):
# c
xd = (e1.x()+e1.xVelocity())-(e2.x()+e1.xVelocity())
yd = (e1.y()+e1.yVelocity())-(e2.y()+e1.yVelocity())
rd = (e1.width()+e2.width())/2
return xd*xd+yd*yd <= rd*rd
elif (p1 and (p2 or s2 or t2)):
# d
pa1 = p1.areaPointsAdvanced()
if p2:
pa2 = p2.areaPointsAdvanced()
else:
pa2 = QPolygonEx(i2.boundingRectAdvanced())
col = not (QRegion(pa1) & QRegion(pa2, Qt.WindingFill)).isEmpty()
return col
else:
return collision_double_dispatch(s2, p2, r2, e2, t2,
s1, p1, r1, e1, t1)
class Edge(Enum):
Left = 1
Right = 2
Top = 4
Bottom = 8
###
# \enum RttiValues
#
# This enum is used to name the different types of canvas item.
#
# \value Rtti_Item Canvas item abstract base class
# \value Rtti_Ellipse
# \value Rtti_Line
# \value Rtti_Polygon
# \value Rtti_PolygonalItem
# \value Rtti_Rectangle
# \value Rtti_Spline
# \value Rtti_Sprite
# \value Rtti_Text
#
###
class RttiValues(Enum):
Rtti_Item = 0
Rtti_Sprite = 1
Rtti_PolygonalItem = 2
Rtti_Text = 3
Rtti_Polygon = 4
Rtti_Rectangle = 5
Rtti_Ellipse = 6
Rtti_Line = 7
Rtti_Spline = 8
class QtCanvasData():
def __init__(self):
self.viewList = QList()
self.itemDict = QSet()
self.animDict = QSet()
class QtCanvasViewData():
def __init__(self):
self.xform = QMatrix()
self.ixform = QMatrix()
self.highQuality = False
def include(r, rect):
if (rect.left() < r.left()):
r.setLeft(rect.left())
if (rect.right()>r.right()):
r.setRight(rect.right())
if (rect.top() < r.top()):
r.setTop(rect.top())
if (rect.bottom()>r.bottom()):
r.setBottom(rect.bottom())
###
#A QtCanvasClusterizer groups rectangles (QRects) into non-overlapping rectangles
#by a merging heuristic.
###
class QtCanvasClusterizer():
def __init__(self, maxclusters):
self.cluster = QList()
for i in range(maxclusters):
self.cluster.append(QRect())
self.count = 0
self.maxcl = maxclusters
def __del__(self):
del self.cluster
def clear(self):
self.count = 0
def add(self, x, y, w=1, h=1):
self.__add(QRect(x, y, w, h))
def __add(self, rect):
biggerrect = QRect(rect.x()-1, rect.y()-1, rect.width()+2, rect.height()+2)
#assert(rect.width()>0 and rect.height()>0)
for cursor in range(self.count):
if (self.cluster[cursor].contains(rect)):
# Wholly contained already.
return
lowestcost = 9999999
cheapest = -1
cursor = 0
while(cursor < self.count):
if (self.cluster[cursor].intersects(biggerrect)):
larger = self.cluster[cursor]
include(larger, rect)
cost = larger.width()*larger.height() - self.cluster[cursor].width()*self.cluster[cursor].height()
if (cost < lowestcost):
bad = False
for c in range(self.count):
if not bad:
bad = self.cluster[c].intersects(larger) and c!= cursor
if (not bad):
cheapest = cursor
lowestcost = cost
cursor += 1
if (cheapest>= 0):
include(self.cluster[cheapest], rect)
return
if (self.count < self.maxcl):
self.cluster[self.count] = rect
self.count += 1
return
# Do cheapest of:
# add to closest self.cluster
# do cheapest self.cluster merge, add to new self.cluster
lowestcost = 9999999
cheapest = -1
cursor = 0
while(cursor < self.count):
larger = self.cluster[cursor]
include(larger, rect)
cost = larger.width()*larger.height() - self.cluster[cursor].width()*self.cluster[cursor].height()
if (cost < lowestcost):
bad = False
for c in range(self.count):
if not bad:
bad = self.cluster[c].intersects(larger) and c!= cursor
if (not bad):
cheapest = cursor
lowestcost = cost
cursor += 1
# ###
# could make an heuristic guess as to whether we need to bother
# looking for a cheap merge.
cheapestmerge1 = -1
cheapestmerge2 = -1
merge1 = 0
while(merge1 < self.count):
merge2 = 0
while(merge2 < self.count):
if(merge1!= merge2):
larger = self.cluster[merge1]
include(larger, self.cluster[merge2])
cost = larger.width()*larger.height() - self.cluster[merge1].width()*self.cluster[merge1].height()
if (cost < lowestcost):
bad = False
for c in range(self.count):
if not bad:
bad = self.cluster[c].intersects(larger) and c!= cursor
if (not bad):
cheapestmerge1 = merge1
cheapestmerge2 = merge2
lowestcost = cost
merge2 += 1
merge1 += 1
if (cheapestmerge1>= 0):
include(self.cluster[cheapestmerge1], self.cluster[cheapestmerge2])
self.cluster[cheapestmerge2] = self.cluster[self.count]
self.count -= 1
else:
# if (not cheapest) debugRectangles(rect):
include(self.cluster[cheapest], rect)
# NB: clusters do not intersect (or intersection will
# overwrite). This is a result of the above algorithm,
# given the assumption that (x, y) are ordered topleft
# to bottomright.
# ###
#
# add explicit x/y ordering to that comment, move it to the top
# and rephrase it as pre-/post-conditions.
def __getItem__(self, i):
return self.cluster[i]
# end of clusterizer
class QtCanvasItemLess():
def func(self, i1, i2):
if (i1.z() == i2.z()):
return i1 > i2
return (i1.z() > i2.z())
class QtCanvasChunk():
def __init__(self):
self.changed = True
self.m_list = QList()
# Other code assumes lists are not deleted. Assignment is also
# done on ChunkRecs. So don't add that sort of thing here.
def sort(self):
self.m_list = QList(sorted(self.m_list, key=lambda x:x.z(), reverse=True))
def list(self):
return self.m_list
def add(self, item):
self.m_list.prepend(item)
self.changed = True
def remove(self, item):
self.m_list.removeAll(item)
self.changed = True
def change(self):
self.changed = True
def hasChanged(self):
return self.changed
def takeChange(self):
y = self.changed
self.changed = False
return y
def gcd(a, b):
r = 0
while r:
r = a%b
a = b
b = r
return b
def scm(a, b):
g = gcd(a, b)
return a/g*b
###
# \class QtCanvas qtcanvas.h
# \brief The QtCanvas class provides a 2D area that can contain QtCanvasItem objects.
#
# The QtCanvas class manages its 2D graphic area and all the canvas
# items the area contains. The canvas has no visual appearance of
# its own. Instead, it is displayed on screen using a QtCanvasView.
# Multiple QtCanvasView widgets may be associated with a canvas to
# provide multiple views of the same canvas.
#
# The canvas is optimized for large numbers of items, particularly
# where only a small percentage of the items change at any
# one time. If the entire display changes very frequently, you should
# consider using your own custom QtScrollView subclass.
#
# Qt provides a rich
# set of canvas item classes, e.g. QtCanvasEllipse, QtCanvasLine,
# QtCanvasPolygon, QtCanvasPolygonalItem, QtCanvasRectangle, QtCanvasSpline,
# QtCanvasSprite and QtCanvasText. You can subclass to create your own
# canvas items; QtCanvasPolygonalItem is the most common base class used
# for this purpose.
#
# Items appear on the canvas after their \link QtCanvasItem.show()
# show()\endlink function has been called (or \link
# QtCanvasItem.setVisible() setVisible(True)\endlink), and \e after
# update() has been called. The canvas only shows items that are
# \link QtCanvasItem.setVisible() visible\endlink, and then only if
# \l update() is called. (By default the canvas is white and so are
# canvas items, so if nothing appears try changing colors.):
#
# If you created the canvas without passing a width and height to
# the constructor you must also call resize().
#
# Although a canvas may appear to be similar to a widget with child
# widgets, there are several notable differences:
#
# \list
# \i Canvas items are usually much faster to manipulate and redraw than
# child widgets, with the speed advantage becoming especially great when
# there are \e many canvas items and non-rectangular items. In most
# situations canvas items are also a lot more memory efficient than child
# widgets.
#
# \i It's easy to detect overlapping items (collision detection).
#
# \i The canvas can be larger than a widget. A million-by-million canvas
# is perfectly possible. At such a size a widget might be very
# inefficient, and some window systems might not support it at all,
# whereas QtCanvas scales well. Even with a billion pixels and a million
# items, finding a particular canvas item, detecting collisions, etc.,
# is still fast (though the memory consumption may be prohibitive
# at such extremes).
#
# \i Two or more QtCanvasView objects can view the same canvas.
#
# \i An arbitrary transformation matrix can be set on each QtCanvasView
# which makes it easy to zoom, rotate or shear the viewed canvas.
#
# \i Widgets provide a lot more functionality, such as input (QKeyEvent,
# QMouseEvent etc.) and layout management (QGridLayout etc.).
#
# \endlist
#
# A canvas consists of a background, a number of canvas items organized by
# x, y and z coordinates, and a foreground. A canvas item's z coordinate
# can be treated as a layer number -- canvas items with a higher z
# coordinate appear in front of canvas items with a lower z coordinate.
#
# The background is white by default, but can be set to a different color
# using setBackgroundColor(), or to a repeated pixmap using
# setBackgroundPixmap() or to a mosaic of smaller pixmaps using
# setTiles(). Individual tiles can be set with setTile(). There
# are corresponding get functions, e.g. backgroundColor() and
# backgroundPixmap().
#
# Note that QtCanvas does not inherit from QWidget, even though it has some
# functions which provide the same functionality as those in QWidget. One
# of these is setBackgroundPixmap(); some others are resize(), size(),
# width() and height(). \l QtCanvasView is the widget used to display a
# canvas on the screen.
#
# Canvas items are added to a canvas by constructing them and passing the
# canvas to the canvas item's constructor. An item can be moved to a
# different canvas using QtCanvasItem.setCanvas().
#
# Canvas items are movable (and in the case of QtCanvasSprites, animated)
# objects that inherit QtCanvasItem. Each canvas item has a position on the
# canvas (x, y coordinates) and a height (z coordinate), all of which are
# held as floating-point numbers. Moving canvas items also have x and y
# velocities. It's possible for a canvas item to be outside the canvas
# (for example QtCanvasItem.x() is greater than width()). When a canvas
# item is off the canvas, onCanvas() returns False and the canvas
# disregards the item. (Canvas items off the canvas do not slow down any
# of the common operations on the canvas.)
#
# Canvas items can be moved with QtCanvasItem.move(). The advance()
# function moves all QtCanvasItem.animated() canvas items and
# setAdvancePeriod() makes QtCanvas move them automatically on a periodic
# basis. In the context of the QtCanvas classes, to `animate' a canvas item
# is to set it in motion, i.e. using QtCanvasItem.setVelocity(). Animation
# of a canvas item itself, i.e. items which change over time, is enabled
# by calling QtCanvasSprite.setFrameAnimation(), or more generally by
# subclassing and reimplementing QtCanvasItem.advance(). To detect collisions
# use one of the QtCanvasItem.collisions() functions.
#
# The changed parts of the canvas are redrawn (if they are visible in a
# canvas view) whenever update() is called. You can either call update()
# manually after having changed the contents of the canvas, or force
# periodic updates using setUpdatePeriod(). If you have moving objects on
# the canvas, you must call advance() every time the objects should
# move one step further. Periodic calls to advance() can be forced using
# setAdvancePeriod(). The advance() function will call
# QtCanvasItem.advance() on every item that is \link
# QtCanvasItem.animated() animated\endlink and trigger an update of the
# affected areas afterwards. (A canvas item that is `animated' is simply
# a canvas item that is in motion.)
#
# QtCanvas organizes its canvas items into \e chunks; these are areas on
# the canvas that are used to speed up most operations. Many operations
# start by eliminating most chunks (i.e. those which haven't changed)
# and then process only the canvas items that are in the few interesting
# (i.e. changed) chunks. A valid chunk, validChunk(), is one which is on
# the canvas.
#
# The chunk size is a key factor to QtCanvas's speed: if there are too many
# chunks, the speed benefit of grouping canvas items into chunks is
# reduced. If the chunks are too large, it takes too long to process each
# one. The QtCanvas constructor tries to pick a suitable size, but you
# can call retune() to change it at any time. The chunkSize() function
# returns the current chunk size. The canvas items always make sure
# they're in the right chunks; all you need to make sure of is that
# the canvas uses the right chunk size. A good rule of thumb is that
# the size should be a bit smaller than the average canvas item
# size. If you have moving objects, the chunk size should be a bit
# smaller than the average size of the moving items.
#
# The foreground is normally nothing, but if you reimplement
# drawForeground(), you can draw things in front of all the canvas
# items.
#
# Areas can be set as changed with setChanged() and set unchanged with
# setUnchanged(). The entire canvas can be set as changed with
# setAllChanged(). A list of all the items on the canvas is returned by
# allItems().
#
# An area can be copied (painted) to a QPainter with drawArea().
#
# If the canvas is resized it emits the resized() signal.
#
# The examples/canvas application and the 2D graphics page of the
# examples/demo application demonstrate many of QtCanvas's facilities.
#
# \sa QtCanvasView QtCanvasItem
###
class QtCanvas(QObject):
resized = Signal()
###
# Create a QtCanvas with no size. \a parent is passed to the QObject
# superclass.
#
# \warning You \e must call resize() at some time after creation to
# be able to use the canvas.
###
def __init__(self, parent=None, *arg):
self.pm = QPixmap()
l = len(arg)
if l==0:
super(QtCanvas, self).__init__(parent)
self.init(0, 0)
#Constructs a QtCanvas that is \a w pixels wide and \a h pixels high.
elif l==1:
super(QtCanvas, self).__init__()
self.init(parent, arg[0])
##
# Constructs a QtCanvas which will be composed of \a h tiles
# horizontally and \a v tiles vertically. Each tile will be an image
# \a tilewidth by \a tileheight pixels taken from pixmap \a p.
# The pixmap \a p is a list of tiles, arranged left to right, (and
# in the case of pixmaps that have multiple rows of tiles, top to
# bottom), with tile 0 in the top-left corner, tile 1 next to the
# right, and so on, e.g.
# \table
# \row \i 0 \i 1 \i 2 \i 3
# \row \i 4 \i 5 \i 6 \i 7
# \endtable
# The QtCanvas is initially sized to show exactly the given number of
# tiles horizontally and vertically. If it is resized to be larger,
# the entire matrix of tiles will be repeated as often as necessary
# to cover the area. If it is smaller, tiles to the right and bottom
# will not be visible.
# \sa setTiles()
##
elif l==4:
super(QtCanvas, self).__init__()
self.init(arg[0]*arg[2], arg[1]*arg[3], scm(arg[2], arg[3]))
self.setTiles(parent, arg[0], arg[1], arg[2], arg[3])
def init(self, w, h, chunksze=16, mxclusters=100):
self.d = QtCanvasData()
self.awidth = w
self.aheight = h
self.chunksize = chunksze
self.maxclusters = mxclusters
self.chwidth = int((w+self.chunksize-1)/self.chunksize)
self.chheight = int((h+self.chunksize-1)/self.chunksize)
self.chunks = QList()
for i in range(self.chwidth*self.chheight):
self.chunks.append(QtCanvasChunk())
self.update_timer = 0
self.bgcolor = Qt.white
self.grid = 0
self.htiles = 0
self.vtiles = 0
self.debug_redraw_areas = False
def tile(self, x, y):
return self.grid[x+y*self.htiles]
def tilesHorizontally(self):
return self.htiles
def tilesVertically(self):
return self.vtiles
def tileWidth(self):
return self.tilew
def tileHeight(self):
return self.tileh
def width(self):
return self.awidth
def height(self):
return self.aheight
def size(self):
return QSize(self.awidth, self.aheight)
def rect(self):
return QRect(0, 0, self.awidth, self.aheight)
def onCanvas(self, arg1, arg2=None):
tp = type(arg1)
if tp==QPoint:
x = arg1.x()
y = arg2.y()
elif tp==int:
x = arg1
y = arg2
return x>=0 and y>=0 and x<self.awidth and y<self.aheight
def validChunk(self, arg1, arg2=None):
tp = type(arg1)
if tp==QPoint:
x = arg1.x()
y = arg2.y()
elif tp==int:
x = arg1
y = arg2
return x>=0 and y>=0 and x<self.chwidth and y<self.chheight
def chunkSize(self):
return self.chunksize
def sameChunk(self, x1, y1, x2, y2):
return self.x1/self.chunksize==x2/self.chunksize and y1/self.chunksize==y2/self.chunksize
###
# Destroys the canvas and all the canvas's canvas items.
###
def __del__(self):
for i in range(self.d.viewList.size()):
self.d.viewList[i].viewing = 0
all = self.allItems()
for it in all:
del it
del self.chunks
del self.grid
del self.d
###
# Returns a list of canvas items that collide with the point \a p.
# The list is ordered by z coordinates, from highest z coordinate
# (front-most item) to lowest z coordinate (rear-most item).
###
# def collisions(self, p):
# return collisions(QRect(p, QSize(1, 1)))
###
# \overload
#
# Returns a list of items which collide with the rectangle \a r. The
# list is ordered by z coordinates, from highest z coordinate
# (front-most item) to lowest z coordinate (rear-most item).
###
def collisions(self, r, item=None, exact=None):
tp = type(r)
if tp in [QPoint, QRect]:
if tp == QPoint:
r = QRect(r, QSize(1, 1))
i = QtCanvasRectangle(r, self)
i.setPen(QPen(Qt.NoPen))
i.show(); # doesn't actually show, since we destroy it
l = QList(i.collisions(True))
l = QList(sorted(l, key=lambda x:x.z(), reverse=True))
self.removeItem(i)
return l
elif tp==QPolygonEx:
###
# \overload
#
# Returns a list of canvas items which intersect with the chunks
# listed in \a chunklist, excluding \a item. If \a exact is True,
# only those which actually \link QtCanvasItem.collidesWith()
# collide with\endlink \a item are returned; otherwise canvas items
# are included just for being in the chunks.
#
# This is a utility function mainly used to implement the simpler
# QtCanvasItem.collisions() function.
###
chunklist = r
seen = QSet()
result = QList()
for i in range(chunklist.count()):
x = chunklist[i].x()
y = chunklist[i].y()
if (self.validChunk(x, y)):
l = self.chunk(x, y).list()
for i in range(l.size()):
g = l.at(i)
if (g != item):
if (not seen.contains(g)):
seen.insert(g)
if (not exact or item.collidesWith(g)):
item.collidesWith(g)
result.append(g)
return result
###
#\internal
#Returns the chunk at a chunk position \a i, \a j.
###
def chunk(self, i, j):
return self.chunks[i+self.chwidth*j]
###
#\internal
#Returns the chunk at a pixel position \a x, \a y.
###
def chunkContaining(self, x, y):
return self.chunk(x/self.chunksize, y/self.chunksize)
###
# Returns a list of all the items in the canvas.
###
def allItems(self):
return self.d.itemDict.toList()
###
# Changes the size of the canvas to have a width of \a w and a
# height of \a h. This is a slow operation.
###
def resize(self, w, h):
if (self.awidth == w and self.aheight == h):
return
hidden = QList()
for it in self.d.itemDict:
if (it.isVisible()):
it.hide()
hidden.append(it)
nchwidth = (w+self.chunksize-1)/self.chunksize
nchheight = (h+self.chunksize-1)/self.chunksize
newchunks = QList()
for i in range(nchwidth*nchheight):
newchunks.append(QtCanvasChunk())
# Commit the new values.
#
self.awidth = w
self.aheight = h
self.chwidth = nchwidth
self.chheight = nchheight
del self.chunks
self.chunks = newchunks
for i in range(hidden.size()):
hidden.at(i).show()
self.setAllChanged()
self.resized.emit()
###
# \fn void QtCanvas.resized()
#
# This signal is emitted whenever the canvas is resized. Each
# QtCanvasView connects to this signal to keep the scrollview's size
# correct.
###
###
# Change the efficiency tuning parameters to \a mxclusters clusters,
# each of size \a chunksze. This is a slow operation if there are
# many objects on the canvas.
#
# The canvas is divided into chunks which are rectangular areas \a
# chunksze wide by \a chunksze high. Use a chunk size which is about
# the average size of the canvas items. If you choose a chunk size
# which is too small it will increase the amount of calculation
# required when drawing since each change will affect many chunks.
# If you choose a chunk size which is too large the amount of
# drawing required will increase because for each change, a lot of
# drawing will be required since there will be many (unchanged)
# canvas items which are in the same chunk as the changed canvas
# items.
#
# Internally, a canvas uses a low-resolution "chunk matrix" to keep
# track of all the items in the canvas. A 64x64 chunk matrix is the
# default for a 1024x1024 pixel canvas, where each chunk collects
# canvas items in a 16x16 pixel square. This default is also
# affected by setTiles(). You can tune this default using this
# function. For example if you have a very large canvas and want to
# trade off speed for memory then you might set the chunk size to 32
# or 64.
#
# The \a mxclusters argument is the number of rectangular groups of
# chunks that will be separately drawn. If the canvas has a large
# number of small, dispersed items, this should be about that
# number. Our testing suggests that a large number of clusters is
# almost always best.
#
###
def retune(self, chunksze, mxclusters=100):
self.maxclusters = mxclusters
if (self.chunksize!= chunksze):
hidden = QList()
for it in self.d.itemDict:
if (it.isVisible()):
it.hide()
hidden.appendit
self.chunksize = chunksze
nchwidth = (self.awidth+self.chunksize-1)/self.chunksize
nchheight = (self.aheight+self.chunksize-1)/self.chunksize
newchunks = QList()
for i in range(nchwidth*nchheight):
newchunks.append(QtCanvasChunk())
# Commit the new values.
#
self.chwidth = nchwidth
self.chheight = nchheight
del self.chunks
self.chunks = newchunks
for i in range(hidden.size()):
hidden.at(i).show()
###
# \fn int QtCanvas.width()
#
# Returns the width of the canvas, in pixels.
###
###
# \fn int QtCanvas.height()
#
# Returns the height of the canvas, in pixels.
###
###
# \fn QSize QtCanvas.size()
#
# Returns the size of the canvas, in pixels.
###
###
# \fn QRect QtCanvas.rect()
#
# Returns a rectangle the size of the canvas.
###
###
# \fn bool QtCanvas.onCanvas(x, y)
#
# Returns True if the pixel position (\a x, \a y) is on the canvas
# otherwise returns False.
#
# \sa validChunk()
###
###
# \fn bool QtCanvas.onCanvas(p)
# \overload
#
# Returns True if the pixel position \a p is on the canvas
# otherwise returns False.
#
# \sa validChunk()
###
###
# \fn bool QtCanvas.validChunk(x, y)
#
# Returns True if the chunk position (\a x, \a y) is on the canvas
# otherwise returns False.
#
# \sa onCanvas()
###
###
# \fn bool QtCanvas.validChunk(p)
# \overload
#
# Returns True if the chunk position \a p is on the canvas; otherwise
# returns False.
#
# \sa onCanvas()
###
###
# \fn int QtCanvas.chunkSize()
#
# Returns the chunk size of the canvas.
#
# \sa retune()
###
###
#\fn bool QtCanvas.sameChunk(x1, y1, x2, y2)
#\internal
#Tells if the points (\a x1, \a y1) and (\a x2, \a y2) are within the same chunk.
###
###
#\internal
#This method adds an the item \a item to the list of QtCanvasItem objects
#in the QtCanvas. The QtCanvasItem class calls this.
###