-
Notifications
You must be signed in to change notification settings - Fork 2
/
mainWidget.py
1699 lines (1553 loc) · 79.3 KB
/
mainWidget.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
from os import listdir
from os.path import join
from PyQt5.QtCore import (QPropertyAnimation, QSize, Qt)
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QStandardItem, QStandardItemModel, QTransform, QPainter
from generatedUiFile.Spine_BrokenUi import Ui_MainWindow
from generatedUiFile.customUi import Ui_Dialog
from generatedUiFile.metaData import dicom_Dialog
from generatedUiFile.frameSpineUi import frame_spine_Dialog
import os, requests
from PyQt5.QtWidgets import *
from PyQt5.QtWidgets import QApplication, QGraphicsView, QGraphicsScene, QInputDialog, QLineEdit, QDialog, QListWidgetItem
from pydicom import dcmread
import numpy as np
import shutil
from collections import defaultdict
from pathlib import Path
from data import *
from model import *
import cv2
WINDOW_SIZE = 0
os.environ["CUDA_VISIBLE_DEVICES"] = "1" # use cpu to test
class initialWidget(QtWidgets.QMainWindow):
pic_ith = 1
pic_jth = 1
pic_windows = [0, 1, 1, 1, 1, 1]
listShow = [[], [], [], [], [], []]
listNoShow = [[], [], [], [], [], []]
for i in range(1, 6):
listShow[i].append(1)
for i in range(1, 6):
for j in range(2, 5):
listNoShow[i].append(j)
# dictionary mapping series(str) to Dicoms(.dcm)
series_2_dicoms = [None] * (5 + 1)
for i in range(1, 5 + 1):
series_2_dicoms[i] = defaultdict(lambda: defaultdict(list))
enlarge = False
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.search_record = QStandardItemModel()
initialWidget.ui = self.ui
self.loadPtList()
self.pt_list.sort()
# 在搜尋那頁列出符合醫生輸入的數字的病歷號
for ptid in self.pt_list:
self.ui.no_list.addItem(ptid)
self.tmp_cnt = 0
# 控制工具列現在選擇的工具為: mouse(defalut), pen, angle, ruler, move, magnifier
self.tool_lock = "mouse"
# patient num map to page
self.empty_page_stack = []
for i in range(5, 0, -1):
self.empty_page_stack.append(i)
self.patient_mapto_page = {}
self.opened_list = [] # 紀錄打開順序
self.recent_list = [] # 記錄倒過來
self.ui.patient_list.setEditTriggers(QAbstractItemView.NoEditTriggers)
#右鍵菜單
self.ui.patient_list.setContextMenuPolicy(Qt.CustomContextMenu)
self.ui.patient_list.customContextMenuRequested.connect(self.myListWidgetContext)
self.ui.patient_list.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
#brightness相關
self.custom_window = custom()
self.aboutBrightness()
#選幾張照片
self.aboutWindows()
self.backend()
def moveWindow(e):
if self.isMaximized() == False: # Not maximized
if e.buttons() == Qt.LeftButton:
self.move(self.pos() + e.globalPos() - self.clickPosition)
self.clickPosition = e.globalPos()
e.accept()
self.ui.header.mouseMoveEvent = moveWindow # 移動視窗
self.show()
def closeEvent(self,event):
self.saveSearchRecord()
self.saveOpened()
event.accept()
def backend(self):
self.ui.stackedWidget_right.setCurrentWidget(self.ui.recently_viewed_page)
self.ui.close_button.clicked.connect(self.close) # 叉叉
self.ui.minimize_button.clicked.connect(lambda: self.showMinimized()) # minimize window
self.ui.restore_button.clicked.connect(lambda: self.restoreOrMaximizeWindow()) # restore window
self.setWindowFlag(QtCore.Qt.FramelessWindowHint) # 隱藏邊框
self.ui.menu_toggle.clicked.connect(lambda: self.slideLeftMenu()) # slide menu
self.ui.add_patient.clicked.connect(self.addPatient)
self.ui.search.clicked.connect(lambda: self.ui.stackedWidget_right.setCurrentWidget(self.ui.search_page))
self.loadSearchRecord() # 載入搜尋紀錄
self.loadOpened() # 載入上次開啟紀錄
self.ui.input_no.editingFinished.connect(self.addEntry) # 按enter
self.ui.search_no_button.clicked.connect(self.addEntry) # 按 search_no
completer = QCompleter(self.search_record, self)
self.ui.patient_list.itemClicked.connect(self.patient_listItemClicked)
self.ui.no_list.itemClicked.connect(self.no_listItemClicked)
self.ui.input_no.setCompleter(completer) # 搜尋紀錄
self.linkPage2Array() # 將影像處理頁面預設有五頁
self.ui.pushButton_angle.clicked.connect(self.pushButtonAngleClicked) # 角度按鈕連結
self.ui.pushButton_ruler.clicked.connect(self.pushButtonRulerClicked)
self.ui.pushButton_add_pic.clicked.connect(self.pushButtonAddPicClicked) # 加照片按鈕連結
self.ui.pushButton_pen.clicked.connect(self.pushButtonPenClicked) # 畫筆按鈕連結
self.ui.pushButton_save.clicked.connect(self.pushButtonSaveClicked) # 儲存照片按鈕連結
self.ui.pushButton_mouse.clicked.connect(self.pushButtonMouseClicked) # 鼠標
self.ui.pushButton_erase.clicked.connect(self.pushButtonEraseClicked) # 清除畫筆、角度
self.ui.pushButton_magnifier.clicked.connect(self.pushButtonMagnifier) # 放大 縮小
self.ui.pushButton_rotate.clicked.connect(lambda: self.slideRotateLeftOrRight()) # 打開旋轉的frame
self.ui.pushButton_rotate_right.clicked.connect(self.rotate_image_right) #向右旋轉
self.ui.pushButton_rotate_left.clicked.connect(self.rotate_image_left) #向左旋轉
self.ui.pushButton_move.clicked.connect(self.pushButtonMoveClicked) # 移動
self.ui.patient_list.itemClicked.connect(self.patient_listItemClicked)
self.ui.recently_list.itemClicked.connect(self.recently_listItemClicked)
self.ui.pushButton_meta_data.clicked.connect(self.pushButtonMetaData) # 顯示 metaData
# Load unet model
model_path = "focalLoss.hdf5"
self.unet_model = load_model(model_path)
#照片Show Pic----------------------------------------------------------------------
# 顯示分割好的脊椎照片
def adjustPredictPic(self, src):
pmax = np.max(src)
pmin = np.min(src)
rescale = (src - pmin) / (pmax - pmin) * 255
img = rescale.astype(np.uint8)
new_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)
for i in range(3):
new_img[:, :, i] = img
return new_img
def spineSegmentationPredict(self, src, test_path = './ml_workspace/test'):
dst = './ml_workspace/test/a.bmp'
cv2.imwrite(dst, src)
test_list = createTestList(test_path)
testGene = testGenerator(test_path, len(test_list), test_list)
results = self.unet_model.predict(testGene, len(test_list), verbose=0)
saveResult('./ml_workspace/result', results, test_list)
def showingFrameSpine(self):
dic_path = self.pic_viewer[self.pic_ith][self.pic_jth].pv.ds_copy[self.pic_viewer[self.pic_ith][self.pic_jth].pv.instance_of_series].dcm_path
# print(dic_path)
self.showFramed = frameSpineDialog()
self.showFramed.show()
# print(Path(dic_path).stem)
self.showFramed.setWindowTitle(Path(dic_path).stem)
ds = customDicom(dic_path)
arr = initialWidget.mappingWindow(ds.pixel_array, ds.window_level, ds.window_width)
original_qimage = QtGui.QImage(arr, arr.shape[1], arr.shape[0], arr.shape[1]*2, QtGui.QImage.Format_Grayscale16).copy()
original_pixmap = QtGui.QPixmap(original_qimage)
original_pixmap = original_pixmap.scaled(500, 500, Qt.KeepAspectRatio, Qt.SmoothTransformation)
self.showFramed.framed.originalLabel.setPixmap(original_pixmap)
new_arr = self.adjustPredictPic(arr)
self.spineSegmentationPredict(new_arr)
frame_pixmap = QtGui.QPixmap('./ml_workspace/result/a_predict.bmp')
frame_pixmap = frame_pixmap.scaled(500, 500, Qt.KeepAspectRatio, Qt.SmoothTransformation)
self.showFramed.framed.framedLabel.setPixmap(frame_pixmap)
#brightness
def getWindow(self, WL, WW):
if(WL == 1 and WW == 1): # custom
WL, WW = self.showCustom()
if(WL == 0 & WW == 0):
return
self.pic_viewer[initialWidget.pic_ith][initialWidget.pic_jth].pv.resetWindow(WL, WW)
self.update()
def showCustom(self):
self.custom_window.show()
if(self.custom_window.exec() == 1):
WL = self.custom_window.customui.WLinput.value()
WW = self.custom_window.customui.WWinput.value()
else:
WL = 0
WW = 0
return WL, WW
@staticmethod
def mappingWindow(arr, WL, WW):
pixel_max = WL + WW/2
pixel_min = WL - WW/2
arr = np.clip(arr, pixel_min, pixel_max)
arr = (arr - pixel_min) / (pixel_max - pixel_min) * 65535
return np.copy(np.uint16(arr))
# 設定照片處理的地方有幾格
def windows4to3(self):
tp = [0]
for t in initialWidget.listShow[initialWidget.pic_ith]:
tp.append(t)
self.gridLayout_list[initialWidget.pic_ith].addWidget(self.pic_viewer[initialWidget.pic_ith][tp[1]], 0, 0, 1, 1)
self.gridLayout_list[initialWidget.pic_ith].addWidget(self.pic_viewer[initialWidget.pic_ith][tp[2]], 0, 1, 1, 1)
self.gridLayout_list[initialWidget.pic_ith].removeWidget(self.pic_viewer[initialWidget.pic_ith][tp[3]])
self.gridLayout_list[initialWidget.pic_ith].addWidget(self.pic_viewer[initialWidget.pic_ith][tp[3]], 0, 2, 1, 1)
def setPicWindows(self, x):
self.now_windows = initialWidget.pic_jth # 當前按的照片位置
if initialWidget.pic_windows[initialWidget.pic_ith] > x:
for k in range(x + 1, initialWidget.pic_windows[initialWidget.pic_ith] + 1):
index = initialWidget.listShow[initialWidget.pic_ith][-1]
initialWidget.listShow[initialWidget.pic_ith].pop()
initialWidget.listNoShow[initialWidget.pic_ith].append(index)
self.gridLayout_list[initialWidget.pic_ith].removeWidget(self.pic_viewer[initialWidget.pic_ith][index])
self.pic_viewer[initialWidget.pic_ith][index].deleteLater()
if x == 3:
self.windows4to3()
if self.now_windows > x: # 如果照片當前位置被刪除,則設為x(如4張照片變3張且當前位置在第四張,則設為第三張)
initialWidget.pic_jth = x
initialWidget.pic_windows[initialWidget.pic_ith] = x
if initialWidget.pic_windows[initialWidget.pic_ith] < x:
for k in range(initialWidget.pic_windows[initialWidget.pic_ith] + 1, x + 1):
index = initialWidget.listNoShow[initialWidget.pic_ith][-1]
initialWidget.listNoShow[initialWidget.pic_ith].pop()
initialWidget.listShow[initialWidget.pic_ith].append(index)
self.pic_viewer[initialWidget.pic_ith][index] = PhotoProcessing(self.pic_frame_list[initialWidget.pic_ith], initialWidget.pic_ith, index)
tp = [0]
for t in initialWidget.listShow[initialWidget.pic_ith]:
tp.append(t)
if x == 2:
self.gridLayout_list[initialWidget.pic_ith].addWidget(self.pic_viewer[initialWidget.pic_ith][tp[1]], 0, 0, 1, 1)
self.gridLayout_list[initialWidget.pic_ith].addWidget(self.pic_viewer[initialWidget.pic_ith][tp[2]], 0, 1, 1, 1)
self.pic_viewer[initialWidget.pic_ith][tp[1]].pv.show()
self.pic_viewer[initialWidget.pic_ith][tp[2]].pv.show()
self.pic_viewer[initialWidget.pic_ith][tp[1]].title.button_frame_spine.clicked.connect(self.showingFrameSpine)
self.pic_viewer[initialWidget.pic_ith][tp[2]].title.button_frame_spine.clicked.connect(self.showingFrameSpine)
elif x == 3:
self.gridLayout_list[initialWidget.pic_ith].addWidget(self.pic_viewer[initialWidget.pic_ith][tp[1]], 0, 0, 1, 1)
self.gridLayout_list[initialWidget.pic_ith].addWidget(self.pic_viewer[initialWidget.pic_ith][tp[2]], 0, 1, 1, 1)
self.gridLayout_list[initialWidget.pic_ith].addWidget(self.pic_viewer[initialWidget.pic_ith][tp[3]], 0, 2, 1, 1)
self.pic_viewer[initialWidget.pic_ith][tp[1]].pv.show()
self.pic_viewer[initialWidget.pic_ith][tp[2]].pv.show()
self.pic_viewer[initialWidget.pic_ith][tp[3]].pv.show()
self.pic_viewer[initialWidget.pic_ith][tp[1]].title.button_frame_spine.clicked.connect(self.showingFrameSpine)
self.pic_viewer[initialWidget.pic_ith][tp[2]].title.button_frame_spine.clicked.connect(self.showingFrameSpine)
self.pic_viewer[initialWidget.pic_ith][tp[3]].title.button_frame_spine.clicked.connect(self.showingFrameSpine)
elif x == 4:
self.gridLayout_list[initialWidget.pic_ith].addWidget(self.pic_viewer[initialWidget.pic_ith][tp[1]], 0, 0, 1, 1)
self.gridLayout_list[initialWidget.pic_ith].addWidget(self.pic_viewer[initialWidget.pic_ith][tp[2]], 0, 1, 1, 1)
self.gridLayout_list[initialWidget.pic_ith].addWidget(self.pic_viewer[initialWidget.pic_ith][tp[3]], 1, 0, 1, 1)
self.gridLayout_list[initialWidget.pic_ith].addWidget(self.pic_viewer[initialWidget.pic_ith][tp[4]], 1, 1, 1, 1)
self.pic_viewer[initialWidget.pic_ith][tp[1]].pv.show()
self.pic_viewer[initialWidget.pic_ith][tp[2]].pv.show()
self.pic_viewer[initialWidget.pic_ith][tp[3]].pv.show()
self.pic_viewer[initialWidget.pic_ith][tp[4]].pv.show()
self.pic_viewer[initialWidget.pic_ith][tp[1]].title.button_frame_spine.clicked.connect(self.showingFrameSpine)
self.pic_viewer[initialWidget.pic_ith][tp[2]].title.button_frame_spine.clicked.connect(self.showingFrameSpine)
self.pic_viewer[initialWidget.pic_ith][tp[3]].title.button_frame_spine.clicked.connect(self.showingFrameSpine)
self.pic_viewer[initialWidget.pic_ith][tp[4]].title.button_frame_spine.clicked.connect(self.showingFrameSpine)
initialWidget.pic_windows[initialWidget.pic_ith] = x
initialWidget.pic_jth = self.now_windows # 設回原本的位置
self.setToolLock(PhotoViewer.tool_lock) # 傳到setToolLock更新當前總共幾張照片
def closeWindowX(self, _i, _j):
print(_i, _j)
#按鈕連結處--------------------------------------------------------------------------------------------------------
# 鼠標
def pushButtonMouseClicked(self):
self.setToolLock('mouse')
# 移動
def pushButtonMoveClicked(self):
self.setToolLock('move')
# 放大 縮小
def pushButtonMagnifier(self):
self.setToolLock('magnifier')
# 順時鐘轉
def rotate_image_right(self):
self.setToolLock('rotate_right')
# 逆時鐘轉
def rotate_image_left(self):
self.setToolLock('rotate_left')
# 角度
def pushButtonAngleClicked(self):
self.setToolLock('angle')
# 尺
def pushButtonRulerClicked(self):
self.setToolLock('ruler')
# 筆
def pushButtonPenClicked(self):
self.setToolLock('pen')
# 儲存
def pushButtonSaveClicked(self):
self.setToolLock('save')
# 清除
def pushButtonEraseClicked(self):
self.setToolLock('clear')
# 顯示 meta data
def pushButtonMetaData(self):
self.meta_data = metaDataDialog()
self.meta_data.show()
def show_dataset(ds, indent):
for elem in ds:
if elem.VR == "SQ":
indent += 4 * " "
for item in elem:
show_dataset(item, indent)
indent = indent[4:]
# print(str(elem))
self.meta_data.meta.dicom_table.setItem(self.ind, 0, QtWidgets.QTableWidgetItem(str(elem.tag)))
self.meta_data.meta.dicom_table.setItem(self.ind, 1, QtWidgets.QTableWidgetItem(str(elem.keyword)))
self.meta_data.meta.dicom_table.setItem(self.ind, 2, QtWidgets.QTableWidgetItem(elem.VR))
self.meta_data.meta.dicom_table.setItem(self.ind, 3, QtWidgets.QTableWidgetItem(elem.repval))
self.ind += 1
self.ind = 0
self.whichYouWantIsHere = self.pic_viewer[self.pic_ith][self.pic_jth].pv.ds_copy[self.pic_viewer[self.pic_ith][self.pic_jth].pv.instance_of_series].ds_copy
show_dataset(self.whichYouWantIsHere, indent="")
# path = self.whichYouWantIsHere = self.pic_viewer[self.pic_ith][self.pic_jth].pv.ds_copy[self.pic_viewer[self.pic_ith][self.pic_jth].pv.instance_of_series].dcm_path
# print(path)
# 加照片
def pushButtonAddPicClicked(self):
pic_file_path, filetype = QFileDialog.getOpenFileName(self,"選取檔案","/Users/user/Documents/畢專/dicom_data") #設定副檔名過濾,注意用雙分號間隔
if pic_file_path == "":
print("\n取消")
return
print(pic_file_path)
pt_id = list(self.patient_mapto_page.keys())[list(self.patient_mapto_page.values()).index(initialWidget.pic_ith)]
tmp_dst = './tmp/' + pt_id
if(os.path.exists(tmp_dst)):
self.picAlreadyExist()
return
database_dst = './tmp_database/' + pt_id
shutil.copy(pic_file_path, tmp_dst)
shutil.copy(pic_file_path, database_dst)
def picAlreadyExist(self):
picAlreadyExist_msg = QMessageBox()
picAlreadyExist_msg.setWindowTitle("Warning")
picAlreadyExist_msg.setText("Dicom already exist !")
picAlreadyExist_msg.setIcon(QMessageBox.Warning)
x = picAlreadyExist_msg.exec_()
def setToolLock(self, lock):
self.pic_viewer[initialWidget.pic_ith][initialWidget.pic_jth].pv.resetFlags()
# 預設所有item都不能動且沒有手手
for k in initialWidget.listShow[initialWidget.pic_ith]:
self.pic_viewer[initialWidget.pic_ith][k].pv.Movable(False)
self.pic_viewer[initialWidget.pic_ith][k].pv.toggleDragMode(False)
PhotoViewer.tool_lock = lock
if PhotoViewer.tool_lock == 'move':
for k in initialWidget.listShow[initialWidget.pic_ith]:
self.pic_viewer[initialWidget.pic_ith][k].pv.toggleDragMode(True)
elif PhotoViewer.tool_lock == 'mouse':
for k in initialWidget.listShow[initialWidget.pic_ith]:
self.pic_viewer[initialWidget.pic_ith][k].pv.Movable(True)
PhotoViewer.tool_lock = 'mouse'
elif PhotoViewer.tool_lock == 'save':
self.pic_viewer[initialWidget.pic_ith][initialWidget.pic_jth].pv.save()
PhotoViewer.tool_lock = 'mouse'
elif PhotoViewer.tool_lock == 'rotate_right':
self.pic_viewer[initialWidget.pic_ith][initialWidget.pic_jth].pv.rotate(90)
self.pic_viewer[initialWidget.pic_ith][initialWidget.pic_jth].pv.turnBack(90)
PhotoViewer.tool_lock = 'mouse'
elif PhotoViewer.tool_lock == 'rotate_left':
self.pic_viewer[initialWidget.pic_ith][initialWidget.pic_jth].pv.rotate(-90)
self.pic_viewer[initialWidget.pic_ith][initialWidget.pic_jth].pv.turnBack(-90)
PhotoViewer.tool_lock = 'mouse'
elif PhotoViewer.tool_lock == 'clear':
self.pic_viewer[initialWidget.pic_ith][initialWidget.pic_jth].pv.clear()
PhotoViewer.tool_lock = 'mouse'
# 對比度的選單設定
def aboutBrightness(self):
self.ui.pushButton_brightness.setStyleSheet("::menu-indicator{ image: none; }") #remove triangle
self.window_menu = QtWidgets.QMenu()
self.window_menu.addAction('Default window', lambda: self.getWindow(0, 0))
self.window_menu.addAction('[160/320]', lambda: self.getWindow(160, 320))
self.window_menu.addAction('[320/640]', lambda: self.getWindow(320, 640))
self.window_menu.addAction('[640/1280]', lambda: self.getWindow(640, 1280))
self.window_menu.addAction('[1280/2560]', lambda: self.getWindow(1280, 2560))
self.window_menu.addAction('[2560/5120]', lambda: self.getWindow(2560, 5120))
self.window_menu.addAction('Custom window', lambda: self.getWindow(1, 1))
self.ui.pushButton_brightness.setMenu(self.window_menu)
def slideRotateLeftOrRight(self):
rotate_frame_width = self.ui.rotate_frame.width()
if rotate_frame_width == 0:
new_rotate_frame_width = 100
else:
new_rotate_frame_width = 0
self.animation = QPropertyAnimation(self.ui.rotate_frame, b"minimumWidth")
self.animation.setDuration(250)
self.animation.setStartValue(rotate_frame_width)
self.animation.setEndValue(new_rotate_frame_width)
self.animation.setEasingCurve(QtCore.QEasingCurve.InOutQuart)
self.animation.start()
def aboutWindows(self): # 格數選單設定
self.ui.pushButton_windows.setStyleSheet("::menu-indicator{ image: none; }") #remove triangle
self.windows_menu = QtWidgets.QMenu()
self.windows_menu.addAction('1', lambda: self.setPicWindows(1))
self.windows_menu.addAction('2', lambda: self.setPicWindows(2))
self.windows_menu.addAction('3', lambda: self.setPicWindows(3))
self.windows_menu.addAction('4', lambda: self.setPicWindows(4))
self.ui.pushButton_windows.setMenu(self.windows_menu)
#MENU選單---------------------------------------------------------------------------------------------------------
#add patient
def addPatient(self):
if(not self.empty_page_stack):
self.pageFull()
else:
dir_choose = QFileDialog.getExistingDirectory(self, "選取資料夾", "/Users/user/Documents/畢專/dicom_data") # 第三參數是起始路徑
if dir_choose == "":
print("\n取消")
return
print("\n選擇的資料夾:")
print(dir_choose)
pt_id = os.path.basename(dir_choose)
# post
url = 'http://127.0.0.1:8000/pdicom/' + pt_id
#headers = {'accept': 'application/json', 'Content-Type': 'multipart/form-data'}
myfiles = listdir(dir_choose) # 檔案
dic_file = []
for f in myfiles:
# 產生檔案的絕對路徑
fullpath = join(dir_choose, f)
# dicom的名字
dicom_id = os.path.basename(fullpath)
dic_file.append(('files', (dicom_id, open(fullpath, 'rb'))))
response = requests.post(url, files=dic_file)
print(response.reason)
print(response.json())
if(response.json()['Result'] == 'Directory already exists.'):
self.duplicateAdd()
else:
self.pt_list.append(pt_id)
self.pt_list.sort()
self.ui.no_list.clear()
for ptid in self.pt_list:
self.ui.no_list.addItem(ptid)
src = './tmp_database/' + pt_id
dst = './tmp/' + pt_id
if(not os.path.exists(dst)):
os.makedirs(dst)
copytree(src, dst)
self.openPtPage(pt_id)
def openPtPage(self, pt_id): #記得要先檢查self.empty_page_stack空->Page滿->pageFull, 用在add和pt_list中打開
temp = self.empty_page_stack[-1]
self.empty_page_stack.pop()
self.patient_mapto_page[pt_id] = temp
initialWidget.pic_ith = temp
self.ui.patient_list.addItem(pt_id)
self.ui.stackedWidget_right.setCurrentWidget(self.ui.thumbnail_page)
temp_page = self.patient_mapto_page[pt_id]
self.ui.stackedWidget_patients.setCurrentWidget(self.patient_page[temp_page])
self.opened_list.append(pt_id)
self.setThumbnail(pt_id)
def pageFull(self):
pageFull_msg = QMessageBox()
pageFull_msg.setWindowTitle("Warning")
pageFull_msg.setText("Patient page full !\nPlease close some pages and try again.")
pageFull_msg.setIcon(QMessageBox.Warning)
x = pageFull_msg.exec_()
def duplicateAdd(self):
duplicateAdd_msg = QMessageBox()
duplicateAdd_msg.setWindowTitle("Warning")
duplicateAdd_msg.setText("Patient already exist !")
duplicateAdd_msg.setIcon(QMessageBox.Warning)
x = duplicateAdd_msg.exec_()
# list item clicked
def patient_listItemClicked(self, item):
print(str(item.text()))
self.ui.stackedWidget_right.setCurrentWidget(self.ui.thumbnail_page)
temp = str(item.text())
temp_page = self.patient_mapto_page[temp]
initialWidget.pic_ith = self.patient_mapto_page[temp]
self.ui.stackedWidget_patients.setCurrentWidget(self.patient_page[temp_page])
# menu 伸縮
def slideLeftMenu(self):
width = self.ui.frame_left_menu.width()
if width == 50:
initialWidget.enlarge = True
newWidth = 200
else:
newWidth = 50
self.animation = QPropertyAnimation(self.ui.frame_left_menu, b"minimumWidth")
self.animation.setDuration(250)
self.animation.setStartValue(width)
self.animation.setEndValue(newWidth)
self.animation.setEasingCurve(QtCore.QEasingCurve.InOutQuart)
self.animation.start()
def closePatient(self): # 關閉patient編輯,tmp 也要刪除
curRow = self.ui.patient_list.currentRow()
get_close_id = self.ui.patient_list.item(curRow)
close_id = str(get_close_id.text())
tmp = self.patient_mapto_page[close_id]
self.empty_page_stack.append(tmp)
self.patient_mapto_page.pop(close_id)
self.ui.patient_list.takeItem(self.ui.patient_list.currentRow())
close_path = "./tmp/" + close_id
for filename in os.listdir(close_path):
file_path = close_path + '/' + filename
os.remove(file_path)
os.rmdir(close_path)
if(self.ui.patient_list.count() == 0 & curRow == 0): # if close the last one
self.ui.stackedWidget_right.setCurrentWidget(self.ui.search_page)
elif(curRow == 0): # close first
get_next_id = self.ui.patient_list.item(curRow)
next_pt = str(get_next_id.text())
temp_page = self.patient_mapto_page[next_pt]
initialWidget.pic_ith = temp_page
self.ui.stackedWidget_patients.setCurrentWidget(self.patient_page[temp_page])
else: # close other patient
get_next_id = self.ui.patient_list.item(curRow - 1)
next_pt = str(get_next_id.text())
temp_page = self.patient_mapto_page[next_pt]
initialWidget.pic_ith = temp_page
self.ui.stackedWidget_patients.setCurrentWidget(self.patient_page[temp_page])
# Thumbnail-------------------------------------------------------------------------------------------------------
def setThumbnail(self, pt_id):
pt_path = './tmp/' + pt_id
i = self.patient_mapto_page[pt_id]
self.thumbnail_list[i].setViewMode(QListWidget.IconMode)
self.thumbnail_list[i].setItemAlignment(Qt.AlignCenter)
self.thumbnail_list[i].setIconSize(QSize(215, 215))
self.thumbnail_list[i].setContentsMargins(0, 0, 0, 0)
self.thumbnail_list[i].setDragEnabled(True)
self.thumbnail_list[i].setDragDropMode(QAbstractItemView.DragOnly)
self.thumbnail_list[i].setStyleSheet( "QListWidget::item { border-top : 1px solid black }" )
initialWidget.series_2_dicoms[i].clear()
#先放pt id
item = QtWidgets.QListWidgetItem(self.thumbnail_list[i])
self.thumbnail_list[i].addItem(item)
new_item = MyCustomWidgetPtid(pt_id)
item.setTextAlignment(Qt.AlignVCenter)
item.setSizeHint(QSize(219, 50))
self.thumbnail_list[i].setItemWidget(item, new_item)
for filename in os.listdir(pt_path): #set map
if not filename.endswith('.dcm') :
continue
dicom_path = pt_path + '/' + filename
ds = customDicom(dicom_path)
initialWidget.series_2_dicoms[i][ds.study_date, ds.study_time, ds.study_id][ds.series_description].append(ds)
for study, series in dict(sorted(initialWidget.series_2_dicoms[i].items())).items():
first = True
for key, value in dict(sorted(series.items(), key= lambda x: x[1][0].acquisition_time)).items(): # key = series description
if first:
first = False
item = QtWidgets.QListWidgetItem(self.thumbnail_list[i])
self.thumbnail_list[i].addItem(item)
date = "%s/%s/%s" % (study[0][0:4], study[0][4:6], study[0][6:8])
time = "%s:%s:%s" % (study[1][0:2], study[1][2:4], study[1][4:6])
new_item = MyCustomWidget("%s %s" % (date, time), value[0].study_description, "%s: %d series" % (value[0].modality, len(initialWidget.series_2_dicoms[i][study].keys())))
item.setTextAlignment(Qt.AlignVCenter)
item.setSizeHint(QSize(219, 90))
self.thumbnail_list[i].setItemWidget(item, new_item)
ds = initialWidget.series_2_dicoms[i][study][key][0]
arr = initialWidget.mappingWindow(ds.pixel_array, ds.window_level, ds.window_width)
qimage = QtGui.QImage(arr, arr.shape[1], arr.shape[0], arr.shape[1]*2, QtGui.QImage.Format_Grayscale16).copy()
pixmap = QtGui.QPixmap(qimage)
pixmap = pixmap.scaled(190, 190, Qt.KeepAspectRatio, Qt.SmoothTransformation)
pix_wid = pixmap.width()
pix_hei = pixmap.height()
start_x = int((190 - pix_wid)/2) #pixmap 在黑框中起始x
start_y = int((190 - pix_hei)/2) # y
item = QtWidgets.QListWidgetItem()
item.setSizeHint(QSize(219, 219))
item.setText(key)
item.setData(Qt.UserRole, study)
black_base = QtGui.QPixmap(190, 190)
black_base.fill(Qt.black)
no_rect = QtGui.QPixmap(25, 20) # num of instance background black rect
no_rect.fill(Qt.black)
qp = QPainter(black_base)
pen = QtGui.QPen(Qt.white, 1)
qp.setPen(pen)
qp.drawPixmap(start_x, start_y, pixmap) #pic
qp.drawPixmap(160, 165, no_rect) #num_of_inst background
font = QtGui.QFont()
font.setFamily("Verdana")
font.setPointSize(7)
qp.setFont(font)
num_of_instance = len(initialWidget.series_2_dicoms[i][study][key])
qp.drawText(165, 180, str(num_of_instance))
qp.end()
icon = QtGui.QIcon(black_base)
item.setIcon(icon)
item.setFont(QtGui.QFont('Verdana', 8))
self.thumbnail_list[i].addItem(item)
# search page----------------------------------------------------------------------------------------------------
# search
def loadSearchRecord(self):
self.search_record_cnt = 0
with open('./record/search_record.txt', 'r') as f:
medical_numbers = f.read().splitlines()
for k in medical_numbers:
self.search_record.insertRow(self.search_record_cnt, QStandardItem(k))
self.search_record_cnt += 1
def saveSearchRecord(self):
with open('./record/search_record.txt', 'w') as f:
for i in range(self.search_record_cnt):
f.write(self.search_record.item(i).text() + "\n")
def addEntry(self):
entryItem = self.ui.input_no.text()
if entryItem != '':
self.ui.input_no.clear()
self.ui.no_list.clear()
for id in self.pt_list:
if id.startswith(entryItem):
self.ui.no_list.addItem(id)
else:
self.ui.no_list.clear()
for id in self.pt_list:
self.ui.no_list.addItem(id)
completer = QCompleter(self.search_record, self)
self.ui.input_no.setCompleter(completer)
if not self.search_record.findItems(entryItem) and len(entryItem) != 0:
self.search_record_cnt += 1
self.search_record.insertRow(0, QStandardItem(entryItem))
# open patient
def no_listItemClicked(self, item):
#print(str(item.text()))
if(not self.empty_page_stack):
self.pageFull()
else:
pt_id = str(item.text())
if(pt_id not in self.patient_mapto_page):
src = './tmp_database/' + pt_id
dst = './tmp/' + pt_id
if(not os.path.exists(dst)):
os.makedirs(dst)
copytree(src, dst)
self.openPtPage(pt_id)
else:
self.ui.stackedWidget_right.setCurrentWidget(self.ui.thumbnail_page)
temp_page = self.patient_mapto_page[pt_id]
initialWidget.pic_ith = self.patient_mapto_page[pt_id]
self.ui.stackedWidget_patients.setCurrentWidget(self.patient_page[temp_page])
self.opened_list.append(pt_id)
# Recently viewed page--------------------------------------------------------------------------------------------
def loadOpened(self):
with open('./record/tmpOpened.txt', 'r') as f:
pt_id = f.read().splitlines()
for k in pt_id:
self.recent_list.append(k)
self.ui.recently_list.addItem(k)
self.opened_list = self.recent_list[::-1]
def saveOpened(self):
self.recent_list = self.opened_list[::-1]
self.recent_list = list(dict.fromkeys(self.recent_list))
while(len(self.recent_list) > 10):
self.recent_list.pop()
with open('./record/tmpOpened.txt', 'w') as f:
for k in self.recent_list:
f.write(k + "\n")
for filename in os.listdir('./tmp'):
shutil.rmtree('./tmp/'+ filename)
def recently_listItemClicked(self, item):
pt_id = str(item.text())
src = './tmp_database/' + pt_id
dst = './tmp/' + pt_id
if(not os.path.exists(dst)):
os.makedirs(dst)
copytree(src, dst)
self.openPtPage(pt_id)
# 其他/初始--------------------------------------------------------------------------------------------------------
def loadPtList(self):
url = 'http://127.0.0.1:8000/gmedicalnumbers'
response = requests.get(url)
self.ui.no_list.clear()
medical_count = response.json()['medical_count']
medical_numbers = response.json()['medical_numbers']
self.pt_list = []
for i in medical_numbers:
self.pt_list.append(i)
def myListWidgetContext(self,position): # 設定patient list 右鍵功能 關閉
popMenu = QMenu()
closeAct = QAction("Close",self)
if self.ui.patient_list.itemAt(position): #查看右键是否點在item上面
popMenu.addAction(closeAct)
closeAct.triggered.connect(self.closePatient)
popMenu.exec_(self.ui.patient_list.mapToGlobal(position))
def transitiveMatrix(self, _x, _y, theda):
radi = np.deg2rad(theda)
tx = _x * np.cos(radi) + _y * np.sin(radi)
ty = _x * np.sin(-radi) + _y * np.cos(radi)
return tx, ty
def transitiveWithBiasMatrix(self, _x, _y, theda):
index = int((-theda % 360) / 90)
tx, ty = self.transitiveMatrix(_x, _y, theda)
tx += self.rotate_coordinate_system[index][0]
ty += self.rotate_coordinate_system[index][1]
return tx, ty
def picPixelMapping(self, arr, WL, WW):
pixel_max = WL + WW/2
pixel_min = WL - WW/2
rows = arr.shape[0]
cols = arr.shape[1]
for x in range(0, rows):
for y in range(0, cols):
if(arr[x, y]>pixel_max):
arr[x, y] = pixel_max
elif(arr[x, y] < pixel_min):
arr[x, y] = pixel_min
for x in range(0, rows):
for y in range(0, cols):
arr[x, y] = (arr[x, y] - pixel_min) / (pixel_max - pixel_min) * 65535
return np.copy(arr)
def linkPage2Array(self, _MAXIMUM_PAGE = 5, _MAXIMUM_PIC = 4):
# 把QtDesigner的一些重複的Widget用array對應
# patient_page
self.MAXIMUM_PAGE = _MAXIMUM_PAGE
self.MAXIMUM_PIC = _MAXIMUM_PIC
var_patient_page = 'self.ui.patient_page'
self.patient_page = [None] * (self.MAXIMUM_PAGE + 1)
var_array_patient_page = 'self.patient_page'
for i in range(1, self.MAXIMUM_PAGE + 1):
exec("%s[%d] = %s_%d" % (var_array_patient_page, i, var_patient_page, i))
# thumbnail_list
var_thumbnail_list = 'self.ui.thumbnail_list'
self.thumbnail_list = [None] * (self.MAXIMUM_PAGE + 1)
var_array_thumbnail_list = 'self.thumbnail_list'
for i in range(1, self.MAXIMUM_PAGE + 1):
exec("%s[%d] = %s_%d" % (var_array_thumbnail_list, i, var_thumbnail_list, i))
# gridLayout
var_gridLayout_list = 'self.ui.gridLayout'
self.gridLayout_list = [None] * (self.MAXIMUM_PAGE + 1)
var_array_gridLayout_list = 'self.gridLayout_list'
for i in range(1, self.MAXIMUM_PAGE + 1):
exec("%s[%d] = %s_%d" % (var_array_gridLayout_list, i, var_gridLayout_list, i))
# pic_frame
var_pic_frame_list = 'self.ui.pic_frame'
self.pic_frame_list = [None] * (self.MAXIMUM_PAGE + 1)
var_array_pic_frame_list = 'self.pic_frame_list'
for i in range(1, self.MAXIMUM_PAGE + 1):
exec("%s[%d] = %s_%d" % (var_array_pic_frame_list, i, var_pic_frame_list, i))
# pic Viewer
self.pic_viewer = [ [None] * (self.MAXIMUM_PIC + 1) for i in range(self.MAXIMUM_PAGE
+ 1) ] # 對應到照片的viewer array
for i in range(1, self.MAXIMUM_PAGE + 1):
self.pic_viewer[i][1] = PhotoProcessing(self.pic_frame_list[i], i, 1)
self.gridLayout_list[i].addWidget(self.pic_viewer[i][1], 0, 0, 1, 1)
self.pic_viewer[i][1].pv.show()
self.pic_viewer[i][1].title.button_frame_spine.clicked.connect(self.showingFrameSpine)
# Image Processing Attributes
var_pic = 'self.ui.pic'
self.pic_clicked = [ [False] * (self.MAXIMUM_PIC + 1) for i in range(self.MAXIMUM_PAGE + 1) ] # 哪張照片被clicked
self.pic_released = [ [False] * (self.MAXIMUM_PIC + 1) for i in range(self.MAXIMUM_PAGE + 1) ] # 哪張照片被 released
self.dicoms = [ [None] * (self.MAXIMUM_PIC + 1) for i in range(self.MAXIMUM_PAGE + 1) ] # 存Dicoms
var_array_pic = 'self.pic'
self.pic_cnt = [0] * (self.MAXIMUM_PAGE + 1)
initialWidget.pic_ith = initialWidget.pic_jth = 1
def mousePressEvent(self, event):
self.clickPosition = event.globalPos()
def restoreOrMaximizeWindow(self):
global WINDOW_SIZE
win_status = WINDOW_SIZE
if win_status == 0:
WINDOW_SIZE = 1
self.showMaximized()
self.ui.restore_button.setIcon(QtGui.QIcon(u":/icons/icons/window-restore.png")) # Show minized icon
else:
WINDOW_SIZE = 0
self.showNormal()
self.ui.restore_button.setIcon(QtGui.QIcon(u":/icons/icons/window-maximize.png"))
def copytree(src, dst, symlinks=False, ignore=None):
for item in os.listdir(src):
s = os.path.join(src, item)
d = os.path.join(dst, item)
if os.path.isdir(s):
shutil.copytree(s, d, symlinks, ignore)
else:
shutil.copy2(s, d)
# classes
class custom(QDialog):
def __init__(self):
super().__init__()
self.customui = Ui_Dialog()
self.customui.setupUi(self)
class customDicom():
def __init__(self, _dcm_path):
self.dcm_path = _dcm_path
# self.dicom = self.dcmreader(self.dcm_path) # 若要存dicom
self.pixel_array = None
self.study_description = None
self.study_instance_UID = None
self.series_description = None
self.series_number = None
self.instance_no_of_series = None
self.echotime = None
self.content_time = None
self.repetition_time = None
self.magnetic = None
self.window_level = None # WL
self.window_width = None # WW
self.study_date = None
self.study_time = None
self.study_id = None
self.modality = None
self.series_data_time_stamp = None
self.acquisition_time = None
self.content_date = None
self.content_time = None
self.content_time = None
self.window_center= None
self.window_width = None
self.tr = None
self.te = None
self.spacing = None
self.ds_copy = None
self.scropInfo(self.dcmreader(self.dcm_path))
def dcmreader(self, _dcm_path):
ds = dcmread(_dcm_path)
self.ds_copy = ds
# show_dataset(ds, indent="")
return ds
def scropInfo(self, ds):
self.pixel_array = np.uint16(ds.pixel_array).copy()
self.study_description = ds[0x0008, 0x1030].value if (0x0008, 0x1030) in ds else None
self.study_instance_UID = ds[0x0020, 0x000d].value if (0x0020, 0x000d) in ds else None
self.series_description = ds[0x0008, 0x103e].value if (0x0008, 0x103e) in ds else None
self.series_number = ds[0x0020, 0x0011].value if (0x0020, 0x0011) in ds else None
self.instance_no_of_series = ds[0x0020, 0x0013].value if (0x0020, 0x0013) in ds else None
self.echotime = ds[0x0018, 0x0081].value if (0x0018, 0x0081) in ds else None
self.content_time = ds[0x0008, 0x0033].value if (0x0008, 0x0033) in ds else None
self.repetition_time = ds[0x0019, 0x1087].value if (0x0019, 0x1087) in ds else None
self.magnetic = ds[0x0018, 0x0087].value if (0x0018, 0x0087) in ds else None
self.window_level = ds[0x0028, 0x1050].value if (0x0028, 0x1050) in ds else None
self.window_width = ds[0x0028, 0x1051].value if (0x0028, 0x1051) in ds else None
self.study_date = ds[0x0008, 0x0020].value if (0x0008, 0x0020) in ds else None
self.study_time = ds[0x0008, 0x0030].value if (0x0008, 0x0030) in ds else None
self.study_id = ds[0x0020, 0x0010].value if (0x0020, 0x0010) in ds else None
self.modality = ds[0x0008, 0x0060].value if (0x0008, 0x0060) in ds else None
self.series_data_time_stamp = ds[0x0009, 0x10e9].value if (0x0009, 0x10e9) in ds else None
self.acquisition_time = ds[0x0008, 0x0032].value if (0x0008, 0x0032) in ds else "300000"
self.content_date = ds[0x0008, 0x0023].value if (0x0008, 0x0023) in ds else None
self.window_center = ds[0x0028, 0x1050].value if (0x0028, 0x1050) in ds else None
self.window_width = ds[0x0028, 0x1051].value if (0x0028, 0x1051) in ds else None
self.tr = ds[0x0018, 0x0080].value if (0x0018, 0x0080) in ds else None
self.te = ds[0x0018, 0x81].value if (0x0018, 0x81) in ds else None
self.spacing = ds[0x0028, 0x30].value[0] if (0x0028, 0x30) in ds else None
class metaDataDialog(QDialog):
def __init__(self):
super().__init__()
self.meta = dicom_Dialog()
self.meta.setupUi(self)
class frameSpineDialog(QDialog):
def __init__(self):
super().__init__()
self.framed = frame_spine_Dialog()
self.framed.setupUi(self)
class QGraphicsLabel(QtWidgets.QGraphicsTextItem):
def __init__(self, text):
super().__init__(text)
# self.setPen(QtGui.QPen(QtGui.QColor(230, 230, 10)))
# self.setBrush(QtGui.QBrush(QtGui.QColor(60, 30, 30)))
self.movable = False
self.setVisible(False)
def setMovable(self, enable):
self.setAcceptHoverEvents(enable)
self.movable = enable
# mouse hover event
def hoverEnterEvent(self, event):
app.instance().setOverrideCursor(QtCore.Qt.OpenHandCursor)
def hoverLeaveEvent(self, event):
app.instance().restoreOverrideCursor()
# mouse click event
def mousePressEvent(self, event):
pass
def mouseMoveEvent(self, event):
if self.movable:
self.parentItem().mouseMoveEvent(event) # 可以跟parent同時移動
# orig_cursor_position = event.lastScenePos()
# updated_cursor_position = event.scenePos()
# orig_position = self.scenePos()
# updated_cursor_x = updated_cursor_position.x() - orig_cursor_position.x() + orig_position.x()
# updated_cursor_y = updated_cursor_position.y() - orig_cursor_position.y() + orig_position.y()
# self.setPos(QtCore.QPointF(updated_cursor_x, updated_cursor_y))
def mouseReleaseEvent(self, event):
pass
class Protractor(QtWidgets.QGraphicsPathItem):
def __init__(self, qpainterpath):
super().__init__(qpainterpath)
self.setPen(QtGui.QPen(QtGui.QColor(5, 105, 25)))
self.angle_degree = 0
self.sp = None
self.mp = None
self.ep = None
self.movable = False
def setMovable(self, enable):
self.setAcceptHoverEvents(enable)
self.movable = enable
# mouse hover event
def hoverEnterEvent(self, event):
app.instance().setOverrideCursor(QtCore.Qt.OpenHandCursor)
def hoverLeaveEvent(self, event):
app.instance().restoreOverrideCursor()
# mouse click event
def mousePressEvent(self, event):
pass
def mouseMoveEvent(self, event):
if self.movable:
orig_cursor_position = event.lastScenePos()
updated_cursor_position = event.scenePos()
orig_position = self.scenePos()
updated_cursor_x = updated_cursor_position.x() - orig_cursor_position.x() + orig_position.x()
updated_cursor_y = updated_cursor_position.y() - orig_cursor_position.y() + orig_position.y()
self.setPos(QtCore.QPointF(updated_cursor_x, updated_cursor_y))
def mouseReleaseEvent(self, event):
pass
class Ruler(QtWidgets.QGraphicsLineItem):
def __init__(self, x1, y1, x2, y2):
super().__init__(x1, y1, x2, y2)
self.setPen(QtGui.QPen(QtGui.QColor(5, 105, 25)))
self.movable = False
self.sp = None
self.ep = None
self.length = 0
def setMovable(self, enable):
self.setAcceptHoverEvents(enable)
self.movable = enable
# mouse hover event
def hoverEnterEvent(self, event):
app.instance().setOverrideCursor(QtCore.Qt.OpenHandCursor)
def hoverLeaveEvent(self, event):
app.instance().restoreOverrideCursor()
# mouse click event
def mousePressEvent(self, event):
pass
def mouseMoveEvent(self, event):
if self.movable:
orig_cursor_position = event.lastScenePos()
updated_cursor_position = event.scenePos()