forked from sweiss93/LengthNestPro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
window.py
1650 lines (1452 loc) · 68.6 KB
/
window.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
# import math
import numpy as np
# import time
import math
# import sys
import os
from PyQt5 import QtWidgets, QtGui, QtCore, QtPrintSupport
from PyQt5.QtWidgets import (
QMainWindow,
QTableWidget,
QTableWidgetItem,
QGridLayout,
QAction,
QFileDialog,
)
from PyQt5.QtGui import QColor, QIcon, QBrush, QLinearGradient
from PyQt5.QtCore import Qt, QThread
from xml.etree import ElementTree
from nest_calculation import CalculateThread
# from fractions import Fraction
# import ctypes
import csv
canvasHeight = 422
canvasWidth = 1700
# Create subclass of QMainWindow for the application window
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.setAcceptDrops(True)
self.file_path = 0
# Initialize attributes
self.part_quantities = []
self.part_lengths = []
self.part_names = []
# Initialize error code to 0 to signify no errors (to be used in length_nest_pro_calculate)
self.error = 0
# Create a default file path for saving and opening files
user = os.getlogin()
self.default_path_string = "C:/Users/" + user + "/Documents"
# Create and set main widget object
self.main_widget = QtWidgets.QWidget(self)
self.main_widget.setFocus()
self.setCentralWidget(self.main_widget)
# Create a grid layout object in the main widget
self.grid_layout = QGridLayout(self.main_widget)
self.setLayout(self.grid_layout)
self.grid_layout.setContentsMargins(10, 10, 10, 10)
self.grid_layout.setHorizontalSpacing(20)
self.grid_layout.setVerticalSpacing(20)
# Set properties of the window
# user32 = ctypes.windll.user32
# screenWidth = user32.GetSystemMetrics(0)
# screenHeight = user32.GetSystemMetrics(1)
self.setGeometry(150, 35, 1200, 600)
# TODO make window and contents adjustable to any size, allow zooming
self.setWindowState(Qt.WindowMaximized)
self.setWindowTitle(f"LengthNestPro, The free 1D nesting optimizer")
self.setWindowIcon(
QtGui.QIcon("C:/Program Files (x86)/LengthNestPro v1.3/icon.ico")
)
self.statusBar().showMessage("Ready")
# Setup menu bar options
# Create new action
new_action = QAction(QIcon("new.png"), "&New", self)
new_action.setShortcut("Ctrl+N")
new_action.setStatusTip("New document")
new_action.triggered.connect(self.new_call)
# Create open action
open_action = QAction(QIcon("open.png"), "&Open", self)
open_action.setShortcut("Ctrl+O")
open_action.setStatusTip("Open document")
open_action.triggered.connect(self.open_call)
# Create save action
save_action = QAction(QIcon("save.png"), "&Save", self)
save_action.setShortcut("Ctrl+S")
save_action.setStatusTip("Save document")
save_action.triggered.connect(self.save_call)
# Create quit action
quit_action = QAction(QIcon("quit.png"), "&Quit", self)
quit_action.setShortcut("Ctrl+Q")
quit_action.setStatusTip("Quit application")
quit_action.triggered.connect(self.quit_call)
# Create menu bar and add actions
menu_bar = self.menuBar()
file_menu = menu_bar.addMenu("&File")
file_menu.addAction(new_action)
file_menu.addAction(open_action)
file_menu.addAction(save_action)
file_menu.addAction(quit_action)
# Create headers
self.header1()
# self.header2()
self.header3()
# Create blank canvas by placing a label object in the window and setting its properties
self.nest_image = QtWidgets.QLabel()
canvas = QtGui.QPixmap(canvasWidth, canvasHeight)
canvas.fill(QColor(150, 150, 150))
self.nest_image.setPixmap(canvas)
# Place nest_image inside of a scroll area
self.scroll_area = QtWidgets.QScrollArea()
self.scroll_area.setFixedWidth(1740)
self.scroll_area.setFixedHeight(540)
self.scroll_area.setWidgetResizable(True)
self.scroll_area.setWidget(self.nest_image)
self.scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.nest_image.setAlignment(Qt.AlignCenter)
# Set up "Required Parts" table
self.t1 = self.Table()
self.t1.expandable = True
# Connect cellChanged signal to a function that can update the table dimensions based on the new entry
self.t1.cellChanged.connect(self.t1.cell_was_changed)
# Fix width of left header and center labels
self.t1.verticalHeader().setFixedWidth(25)
self.t1.verticalHeader().setDefaultAlignment(Qt.AlignHCenter)
# Fix height of table
# self.t1.setFixedHeight(265)
self.t1.starting_num_rows = 6
self.t1.setFixedHeight(21 + 30 * self.t1.starting_num_rows)
self.t1.setRowCount(self.t1.starting_num_rows)
self.t1.setColumnCount(3)
self.t1.setColumnWidth(0, 60)
self.t1.setColumnWidth(1, 60)
self.t1.setColumnWidth(2, 420)
self.t1.setHorizontalHeaderLabels(["Qty", "Length", "Name / ID"])
self.t1.update_table_width(self.t1)
qty = ["", "", "", "", "", "", "", ""]
qty[0] = QTableWidgetItem("9000")
qty[1] = QTableWidgetItem("3500")
qty[2] = QTableWidgetItem("2500")
qty[3] = QTableWidgetItem("")
qty[4] = QTableWidgetItem("")
qty[5] = QTableWidgetItem("")
qty[6] = QTableWidgetItem("")
qty[7] = QTableWidgetItem("")
qty[0].setTextAlignment(Qt.AlignCenter)
qty[1].setTextAlignment(Qt.AlignCenter)
qty[2].setTextAlignment(Qt.AlignCenter)
qty[3].setTextAlignment(Qt.AlignCenter)
qty[4].setTextAlignment(Qt.AlignCenter)
qty[5].setTextAlignment(Qt.AlignCenter)
qty[6].setTextAlignment(Qt.AlignCenter)
qty[7].setTextAlignment(Qt.AlignCenter)
length = ["", "", "", "", "", "", "", ""]
length[0] = QTableWidgetItem("44.9")
length[1] = QTableWidgetItem("79.11")
length[2] = QTableWidgetItem("31.25")
length[3] = QTableWidgetItem("")
length[4] = QTableWidgetItem("")
length[5] = QTableWidgetItem("")
length[6] = QTableWidgetItem("")
length[7] = QTableWidgetItem("")
length[0].setTextAlignment(Qt.AlignCenter)
length[1].setTextAlignment(Qt.AlignCenter)
length[2].setTextAlignment(Qt.AlignCenter)
length[3].setTextAlignment(Qt.AlignCenter)
length[4].setTextAlignment(Qt.AlignCenter)
length[5].setTextAlignment(Qt.AlignCenter)
length[6].setTextAlignment(Qt.AlignCenter)
length[7].setTextAlignment(Qt.AlignCenter)
name = ["", "", "", "", "", "", "", ""]
name[0] = QTableWidgetItem("L15762")
name[1] = QTableWidgetItem("N42719")
name[2] = QTableWidgetItem("P58634")
name[3] = QTableWidgetItem("")
name[4] = QTableWidgetItem("")
name[5] = QTableWidgetItem("")
name[6] = QTableWidgetItem("")
name[7] = QTableWidgetItem("")
name[0].setTextAlignment(Qt.AlignCenter)
name[1].setTextAlignment(Qt.AlignCenter)
name[2].setTextAlignment(Qt.AlignCenter)
name[3].setTextAlignment(Qt.AlignCenter)
name[4].setTextAlignment(Qt.AlignCenter)
name[5].setTextAlignment(Qt.AlignCenter)
name[6].setTextAlignment(Qt.AlignCenter)
name[7].setTextAlignment(Qt.AlignCenter)
self.t1.setItem(0, 0, qty[0])
self.t1.setItem(1, 0, qty[1])
self.t1.setItem(2, 0, qty[2])
self.t1.setItem(3, 0, qty[3])
self.t1.setItem(4, 0, qty[4])
self.t1.setItem(5, 0, qty[5])
self.t1.setItem(6, 0, qty[6])
self.t1.setItem(7, 0, qty[7])
self.t1.setItem(0, 1, length[0])
self.t1.setItem(1, 1, length[1])
self.t1.setItem(2, 1, length[2])
self.t1.setItem(3, 1, length[3])
self.t1.setItem(4, 1, length[4])
self.t1.setItem(5, 1, length[5])
self.t1.setItem(6, 1, length[6])
self.t1.setItem(7, 1, length[7])
self.t1.setItem(0, 2, name[0])
self.t1.setItem(1, 2, name[1])
self.t1.setItem(2, 2, name[2])
self.t1.setItem(3, 2, name[3])
self.t1.setItem(4, 2, name[4])
self.t1.setItem(5, 2, name[5])
self.t1.setItem(6, 2, name[6])
self.t1.setItem(7, 2, name[7])
# Set up "Nesting Settings" table
self.t2 = self.Table()
self.t2.expandable = False
# Fix width of left header and center labels
self.t2.verticalHeader().setFixedWidth(150)
self.t2.verticalHeader().setDefaultAlignment(Qt.AlignHCenter)
self.t2.starting_num_rows = 6
# Fix height of table
self.t2.setFixedHeight(21 + 30 * self.t2.starting_num_rows)
self.t2.setRowCount(self.t2.starting_num_rows)
self.t2.setColumnCount(1)
self.t2.setColumnWidth(0, 150)
self.t2.setHorizontalHeaderLabels([""])
self.t2.setVerticalHeaderLabels(
[
"Stock Length",
"Left Waste",
"Right Waste",
"Spacing",
"Max Parts Per Nest " "(goal)",
"Max # of Containers (goal)",
]
)
self.stock_length = QTableWidgetItem("6000")
self.left_waste = QTableWidgetItem("5")
self.right_waste = QTableWidgetItem("500")
self.spacing = QTableWidgetItem("10")
self.max_parts_per_nest = QTableWidgetItem("4")
self.max_containers = QTableWidgetItem("4")
self.stock_length.setTextAlignment(Qt.AlignCenter)
self.left_waste.setTextAlignment(Qt.AlignCenter)
self.right_waste.setTextAlignment(Qt.AlignCenter)
self.spacing.setTextAlignment(Qt.AlignCenter)
self.max_parts_per_nest.setTextAlignment(Qt.AlignCenter)
self.max_containers.setTextAlignment(Qt.AlignCenter)
self.t2.setItem(0, 0, self.stock_length)
self.t2.setItem(1, 0, self.left_waste)
self.t2.setItem(2, 0, self.right_waste)
self.t2.setItem(3, 0, self.spacing)
self.t2.setItem(4, 0, self.max_parts_per_nest)
self.t2.setItem(5, 0, self.max_containers)
# Enter function to create calculate button
self.calculate()
# Enter function to create calculate button
self.cancel()
# Create status messages
self.error_message = QtWidgets.QLabel(self)
self.error_message.setHidden(True)
self.error_message.setFont(QtGui.QFont("Arial", 12))
self.error_message.setAlignment(Qt.AlignCenter)
self.error_message.setText(
"One or more of the parts is too long for the available nesting length."
)
self.error_message.setWordWrap(True)
self.error_message.setFixedWidth(200)
self.error_message.setFixedHeight(100)
self.error_message.setStyleSheet(
"margin:0px 20px 0px 0px; padding:0px 10px 0px 10px; background-color: red"
)
self.grid_layout.addWidget(self.error_message, 1, 2, Qt.AlignCenter)
self.error_message2 = QtWidgets.QLabel(self)
self.error_message2.setHidden(True)
self.error_message2.setFont(QtGui.QFont("Arial", 12))
self.error_message2.setAlignment(Qt.AlignCenter)
self.error_message2.setText("Some values still need to be entered.")
self.error_message2.setWordWrap(True)
self.error_message2.setFixedWidth(200)
self.error_message2.setFixedHeight(100)
self.error_message2.setStyleSheet(
"margin:0px 20px 0px 0px; padding:0px 10px 0px 10px; background-color: red"
)
self.grid_layout.addWidget(self.error_message2, 1, 2, Qt.AlignCenter)
self.error_message3 = QtWidgets.QLabel(self)
self.error_message3.setHidden(True)
self.error_message3.setFont(QtGui.QFont("Arial", 12))
self.error_message3.setAlignment(Qt.AlignCenter)
self.error_message3.setText(
"Nested quantities do not match required quantities."
)
self.error_message3.setWordWrap(True)
self.error_message3.setFixedWidth(200)
self.error_message3.setFixedHeight(100)
self.error_message3.setStyleSheet(
"margin:0px 20px 0px 0px; padding:0px 10px 0px 10px; background-color: red"
)
self.grid_layout.addWidget(self.error_message3, 1, 2, Qt.AlignCenter)
self.error_message4 = QtWidgets.QLabel(self)
self.error_message4.setHidden(True)
self.error_message4.setFont(QtGui.QFont("Arial", 12))
self.error_message4.setAlignment(Qt.AlignCenter)
self.error_message4.setText("Calculation was canceled.")
self.error_message4.setWordWrap(True)
self.error_message4.setFixedWidth(200)
self.error_message4.setFixedHeight(100)
self.error_message4.setStyleSheet(
"margin:0px 20px 0px 0px; padding:0px 10px 0px 10px; background-color: rgb("
"100, 100, 0)"
)
self.grid_layout.addWidget(self.error_message4, 1, 2, Qt.AlignCenter)
self.success_message = QtWidgets.QLabel(self)
self.success_message.setHidden(True)
self.success_message.setFont(QtGui.QFont("Arial", 12))
self.success_message.setAlignment(Qt.AlignCenter)
self.success_message.setText("Parts were nested successfully.")
self.success_message.setWordWrap(True)
self.success_message.setFixedWidth(200)
self.success_message.setFixedHeight(100)
self.success_message.setStyleSheet(
"margin:0px 20px 0px 0px; padding:0px 10px 0px 10px; background-color: "
"green"
)
self.grid_layout.addWidget(self.success_message, 1, 2, Qt.AlignCenter)
self.status_message = QtWidgets.QLabel(self)
self.status_message.setHidden(True)
self.status_message.setFont(QtGui.QFont("Arial", 12))
self.status_message.setAlignment(Qt.AlignCenter)
self.status_message.setText("Calculating new nest...")
self.status_message.setWordWrap(True)
self.status_message.setFixedWidth(200)
self.status_message.setFixedHeight(100)
self.status_message.setStyleSheet(
"margin:0px 20px 0px 0px; padding:0px 10px 0px 10px; background-color: blue"
)
self.grid_layout.addWidget(self.status_message, 1, 2, Qt.AlignCenter)
self.status_message2 = QtWidgets.QLabel(self)
self.status_message2.setHidden(True)
self.status_message2.setFont(QtGui.QFont("Arial", 12))
self.status_message2.setAlignment(Qt.AlignCenter)
self.status_message2.setText("Click 'Calculate' to begin nesting.")
self.status_message2.setWordWrap(True)
self.status_message2.setFixedWidth(200)
self.status_message2.setFixedHeight(100)
self.status_message2.setStyleSheet(
"margin:0px 20px 0px 0px; padding:0px 10px 0px 10px; background-color: "
"rgb(100, 100, 100); color: rgb(255, 255, 255)"
)
self.grid_layout.addWidget(self.status_message2, 1, 2, Qt.AlignCenter)
self.status_message2.setVisible(True)
self.grid_layout.addWidget(self.h1, 0, 1, Qt.AlignHCenter)
self.grid_layout.addWidget(self.h3, 0, 3, Qt.AlignHCenter)
self.grid_layout.addWidget(self.t1, 1, 1, 2, 1, Qt.AlignLeft)
self.grid_layout.addWidget(self.t2, 1, 3, 2, 1, Qt.AlignTop)
# self.grid_layout.addWidget(self.cancel_btn, 2, 0, 1, 5, Qt.AlignCenter)
self.grid_layout.addWidget(self.calc_btn, 2, 2, 1, 1, Qt.AlignCenter)
self.grid_layout.addWidget(self.scroll_area, 4, 0, 1, 5, Qt.AlignHCenter)
self.scroll_area.show()
self.grid_layout.setColumnStretch(0, 11)
self.grid_layout.setColumnStretch(1, 13)
self.grid_layout.setColumnStretch(2, 10)
self.grid_layout.setColumnStretch(3, 13)
self.grid_layout.setColumnStretch(4, 9)
self.grid_layout.setRowStretch(0, 1)
self.grid_layout.setRowStretch(1, 1)
self.grid_layout.setRowStretch(2, 1)
self.grid_layout.setRowStretch(3, 1)
def dragEnterEvent(self, event):
if event.mimeData().urls()[0].toLocalFile()[-8:] == ".csv":
event.accept()
else:
event.ignore()
def dragMoveEvent(self, event):
if event.mimeData().urls()[0].toLocalFile()[-8:] == ".csv":
event.accept()
else:
event.ignore()
def dropEvent(self, event):
if event.mimeData().urls()[0].toLocalFile()[-8:] == ".csv":
event.setDropAction(Qt.CopyAction) # TODO ???
self.file_path = event.mimeData().urls()[0].toLocalFile()
self.open_call()
# Reset file_path to 0 to allow for open dialog box again
self.file_path = 0
event.accept()
else:
event.ignore()
# def set_image(self, file_path):
# print("end")
# # self.photoViewer.setPixmap(QPixmap(file_path))
# Create table class
class Table(QTableWidget):
def __init__(self):
super().__init__()
# Adjust style of grid lines
self.setShowGrid(False)
self.setStyleSheet(
"QTableView::item {border-right: 1px solid #909090; border-bottom: 1px solid #909090;}"
)
def check_row_for_contents(self, row_number):
num_columns = self.columnCount()
for i in range(num_columns):
if hasattr(self.item(row_number, i), "text"):
if self.item(row_number, i).text() != "":
return True
# If this code is reached, then there were no contents in any cells in the specified row
return False
def add_row(self):
current_row_count = self.rowCount()
if self.expandable:
self.insertRow(current_row_count)
for i in range(self.columnCount()):
self.new_item = QTableWidgetItem("")
self.new_item.setTextAlignment(Qt.AlignCenter)
self.setItem(current_row_count, i, self.new_item)
def remove_row(self):
# Check number of rows in table
num_rows = self.rowCount()
last_row_index = num_rows - 1
# Remove last row
self.removeRow(last_row_index)
# Check if more empty rows need to be deleted from the end of the table
rows_need_deleted = 1
while rows_need_deleted == 1:
if (
not self.check_row_for_contents(last_row_index - 1)
and num_rows > self.starting_num_rows
):
self.removeRow(last_row_index)
num_rows -= 1
last_row_index -= 1
else:
rows_need_deleted = 0
def cell_was_changed(self):
self.update_num_rows()
self.updateGeometries()
self.update_table_width(self)
def update_num_rows(self):
# Check number of rows in table
num_rows = self.rowCount()
last_row_index = num_rows - 1
# Add a row to the table if the last row has any contents
if self.check_row_for_contents(last_row_index):
self.add_row()
# Remove a row from the table if the second to last row has no contents (assumes there will always be an
# empty row after any contents)
if (
not self.check_row_for_contents(last_row_index - 1)
and num_rows > self.starting_num_rows
):
self.remove_row()
def update_table_width(self, table):
if self:
width = table.verticalHeader().width()
width += table.horizontalHeader().length()
if table.verticalScrollBar().isVisible():
width += table.verticalScrollBar().width() - 1
width += 1
width += table.frameWidth() * 2
table.setFixedWidth(width)
def keyPressEvent(self, event):
if event.key() == 16777223: # Delete
self.delete_cell_contents()
elif event.key() == 16777221 or event.key() == 16777220: # Enter
self.enter_was_pressed()
else:
super().keyPressEvent(event)
def delete_cell_contents(self):
indices = self.selectedIndexes()
for index in indices[::-1]:
i = index.row()
j = index.column()
self.setItem(i, j, QTableWidgetItem(""))
# Make sure row still exists before trying to align contents
if self.rowCount() > i:
self.item(i, j).setTextAlignment(Qt.AlignCenter)
def enter_was_pressed(self):
# Record the indices of the current cell
current_row = self.currentRow()
current_column = self.currentColumn()
# Temporarily change the current cell so that cell_value can update to the typed value before it is checked
self.setCurrentCell(current_row + 1, current_column)
# Extract value of cell that was active when user pressed enter
cell_value = self.item(current_row, current_column).text()
# Highlight the correct cell based on the status of the table
# TODO remove last condition after adding max_containers functionality since no rows will be hidden
if self.rowCount() != current_row + 1 or (
cell_value != "" and self.expandable
):
self.setCurrentCell(current_row + 1, current_column)
else:
self.setCurrentCell(current_row, current_column)
def resizeEvent(self, *args, **kwargs):
self.cell_was_changed()
# Functions to setup widgets
def new_call(self):
self.t1.clearContents()
def open_call(self):
# Allow user to select csv file to open, or use file path from drag and drop
if self.file_path == 0:
file_path = QFileDialog.getOpenFileName(
QFileDialog(),
"",
self.default_path_string,
"LengthNestPro csv (*.csv)",
)[0]
else:
file_path = self.file_path
if file_path: # Make sure the user selected a file before trying to open one
# # Create blank list with length equal to the number of parts in the nesting job
blank_list = []
for i in range(20):
blank_list.append(QTableWidgetItem(""))
# # Copy blank list to initialize each attribute
name = blank_list.copy()
qty = blank_list.copy()
length = blank_list.copy()
# # Clear contents from table
self.t1.clearContents()
with open(file_path, "r") as file:
csvreader = csv.reader(file)
# Set a line count so we know which line has the headings
line_count = 0
spacing = 1
for row in csvreader:
# Print out the headings from the first line of the file
if line_count != 0:
word = row[0]
if word.find("Profil") != -1:
name[line_count - spacing] = QTableWidgetItem(
word[13 : len(word)]
)
qty[line_count - spacing] = QTableWidgetItem(row[1])
length[line_count - spacing] = QTableWidgetItem(row[4])
name[line_count - spacing].setTextAlignment(Qt.AlignCenter)
qty[line_count - spacing].setTextAlignment(Qt.AlignCenter)
length[line_count - spacing].setTextAlignment(
Qt.AlignCenter
)
self.t1.setItem(
line_count - spacing, 0, qty[line_count - spacing]
)
self.t1.setItem(
line_count - spacing, 1, length[line_count - spacing]
)
self.t1.setItem(
line_count - spacing, 2, name[line_count - spacing]
)
else:
spacing += 1
line_count += 1
# # Extract nesting settings and add them to "nesting settings" table
# nesting_settings = nesting_job.find("nestingSettings")
# if hasattr(nesting_settings.find("stockLength"), "text"):
# stock_length = QTableWidgetItem(
# nesting_settings.find("stockLength").text
# )
# stock_length.setTextAlignment(Qt.AlignCenter)
# self.t2.setItem(0, 0, stock_length)
# if hasattr(nesting_settings.find("leftWaste"), "text"):
# left_waste = QTableWidgetItem(nesting_settings.find("leftWaste").text)
# left_waste.setTextAlignment(Qt.AlignCenter)
# self.t2.setItem(1, 0, left_waste)
# if hasattr(nesting_settings.find("rightWaste"), "text"):
# right_waste = QTableWidgetItem(nesting_settings.find("rightWaste").text)
# right_waste.setTextAlignment(Qt.AlignCenter)
# self.t2.setItem(2, 0, right_waste)
# if hasattr(nesting_settings.find("spacing"), "text"):
# spacing = QTableWidgetItem(nesting_settings.find("spacing").text)
# spacing.setTextAlignment(Qt.AlignCenter)
# self.t2.setItem(3, 0, spacing)
# if hasattr(nesting_settings.find("maxPartsPerNest"), "text"):
# max_parts_per_nest = QTableWidgetItem(
# nesting_settings.find("maxPartsPerNest").text
# )
# max_parts_per_nest.setTextAlignment(Qt.AlignCenter)
# self.t2.setItem(4, 0, max_parts_per_nest)
# if hasattr(nesting_settings.find("maxContainers"), "text"):
# max_containers = QTableWidgetItem(
# nesting_settings.find("maxContainers").text
# )
# max_containers.setTextAlignment(Qt.AlignCenter)
# self.t2.setItem(5, 0, max_containers)
self.name_of_open_file = file_path
self.setWindowTitle(
f"LengthNestPro, The free 1D nesting optimizer - {self.name_of_open_file}"
)
self.statusBar().showMessage("Ready")
def save_call(self):
# Allow user to select where to save xml file
file_path = 0
if file_path == 0:
file_path = QFileDialog.getSaveFileName(
QFileDialog(),
"",
self.default_path_string,
"LengthNestPro xml (*.LNP.xml)",
)[0]
if file_path:
# Construct xml file structure
nesting_job = ElementTree.Element("nestingJob")
required_parts = ElementTree.SubElement(nesting_job, "requiredParts")
nesting_settings = ElementTree.SubElement(
nesting_job, "nestingSettings"
)
stock_length = ElementTree.SubElement(nesting_settings, "stockLength")
left_waste = ElementTree.SubElement(nesting_settings, "leftWaste")
right_waste = ElementTree.SubElement(nesting_settings, "rightWaste")
spacing = ElementTree.SubElement(nesting_settings, "spacing")
max_parts_per_nest = ElementTree.SubElement(
nesting_settings, "maxPartsPerNest"
)
max_containers = ElementTree.SubElement(
nesting_settings, "maxContainers"
)
# Add current data for nesting settings
try:
stock_length.text = self.t2.item(0, 0).text()
except 1:
pass
try:
left_waste.text = self.t2.item(1, 0).text()
except 1:
pass
try:
right_waste.text = self.t2.item(2, 0).text()
except 1:
pass
try:
spacing.text = self.t2.item(3, 0).text()
except 1:
pass
try:
max_parts_per_nest.text = self.t2.item(4, 0).text()
except 1:
pass
try:
max_containers.text = self.t2.item(5, 0).text()
except 1:
pass
# Check how many parts have data in the "Required Parts" table
# Assume that all rows could have data
num_parts = self.t1.rowCount()
# Extract number of columns in "Required Parts" table
num_columns = self.t1.columnCount()
# Initialize parameter to enter while loop
no_data_found = 1
while no_data_found and num_parts > 0:
# Check if there is any text in each cell
for i in range(num_columns):
if self.t1.item(num_parts - 1, i) is not None:
if self.t1.item(num_parts - 1, i).text() != "":
no_data_found = 0
break
else:
# At the end of the row's for loop, decrement num_parts, and return to start of while loop
num_parts -= 1
continue
# Create blank list with length equal to the number of parts in the "required parts" table
blank_list = []
for i in range(num_parts):
blank_list.append(ElementTree.Element)
# Copy blank list to initialize each attribute
part = blank_list.copy()
name = blank_list.copy()
qty = blank_list.copy()
length = blank_list.copy()
# Add current data for required parts
# for i in range(len(self.t1))
for i in range(num_parts):
part[i] = ElementTree.SubElement(required_parts, "part")
qty[i] = ElementTree.SubElement(part[i], "qty")
length[i] = ElementTree.SubElement(part[i], "length")
name[i] = ElementTree.SubElement(part[i], "name")
qty[i].text = self.t1.item(i, 0).text()
length[i].text = self.t1.item(i, 1).text()
name[i].text = self.t1.item(i, 2).text()
# create a new XML file with the results
save_data_string = ElementTree.tostring(nesting_job)
save_data_file = open(file_path, "wb")
save_data_file.write(save_data_string)
self.name_of_open_file = file_path
self.setWindowTitle(
f"LengthNestPro, The free 1D nesting optimizer - {self.name_of_open_file}"
)
self.statusBar().showMessage("Ready")
def print_widget(self, widget, filename):
printer = QtPrintSupport.QPrinter(QtPrintSupport.QPrinter.HighResolution)
printer.setOutputFormat(QtPrintSupport.QPrinter.PdfFormat)
printer.setOrientation(QtPrintSupport.QPrinter.Landscape)
printer.setOutputFileName(filename)
painter = QtGui.QPainter(printer)
# start scale
xscale = printer.pageRect().width() * 1.0 / widget.width()
yscale = printer.pageRect().height() * 1.0 / widget.height()
scale = min(xscale, yscale)
painter.translate(printer.paperRect().center())
painter.scale(scale, scale)
painter.translate(-widget.width() / 2, -widget.height() / 2)
# end scale
widget.render(painter)
painter.end()
def SavetoPDF(self):
fn = self.name_of_open_file[:-4]
if fn:
if QtCore.QFileInfo(fn).suffix() == "":
fn += ".pdf"
self.print_widget(self.nest_image, fn)
def save_results_call(self):
# Make sure a file is open, and exit function if it is not
try:
self.name_of_open_file
except AttributeError:
# Exit function
return
# Create a file path where the results can be saved
file_path = 0
if file_path == 0:
file_path = f"{self.name_of_open_file[:-4]}.results.xml"
if file_path:
# Construct xml file structure
nesting_job = ElementTree.Element("nestingJob")
required_parts = ElementTree.SubElement(nesting_job, "requiredParts")
nesting_settings = ElementTree.SubElement(
nesting_job, "nestingSettings"
)
result = ElementTree.SubElement(nesting_job, "result")
stock_length = ElementTree.SubElement(nesting_settings, "stockLength")
left_waste = ElementTree.SubElement(nesting_settings, "leftWaste")
right_waste = ElementTree.SubElement(nesting_settings, "rightWaste")
spacing = ElementTree.SubElement(nesting_settings, "spacing")
max_parts_per_nest = ElementTree.SubElement(
nesting_settings, "maxPartsPerNest"
)
max_containers = ElementTree.SubElement(
nesting_settings, "maxContainers"
)
num_lengths_required = ElementTree.SubElement(
result, "numLengthsRequired"
)
num_lengths_required.text = (
f"{self.calculator.final_required_lengths_minus_drop}"
)
scrap_rate = ElementTree.SubElement(result, "scrapRate")
scrap_rate.text = f"{self.calculator.scrap_without_drop}"
num_containers_required = ElementTree.SubElement(
result, "numContainersRequired"
)
num_containers_required.text = (
f"{self.calculator.actual_max_containers}"
)
# Add current data for nesting settings
try:
stock_length.text = self.t2.item(0, 0).text()
except 1:
pass
try:
left_waste.text = self.t2.item(1, 0).text()
except 1:
pass
try:
right_waste.text = self.t2.item(2, 0).text()
except 1:
pass
try:
spacing.text = self.t2.item(3, 0).text()
except 1:
pass
try:
max_parts_per_nest.text = self.t2.item(4, 0).text()
except 1:
pass
try:
max_containers.text = self.t2.item(5, 0).text()
except 1:
pass
# Check how many parts have data in the "Required Parts" table
# Assume that all rows could have data
num_parts = self.t1.rowCount()
# Extract number of columns in "Required Parts" table
num_columns = self.t1.columnCount()
# Initialize parameter to enter while loop
no_data_found = 1
while no_data_found:
# Check if there is any text in each cell
for i in range(num_columns):
if self.t1.item(num_parts - 1, i) is not None:
if self.t1.item(num_parts - 1, i).text() != "":
no_data_found = 0
break
else:
# At the end of the row's for loop, decrement num_parts, and return to start of while loop
num_parts -= 1
continue
# Create blank list with length equal to the number of parts in the "required parts" table
blank_list = []
for i in range(num_parts):
blank_list.append(ElementTree.Element)
# Copy blank list to initialize each attribute
part = blank_list.copy()
name = blank_list.copy()
qty = blank_list.copy()
length = blank_list.copy()
# Add current data for required parts
for i in range(num_parts):
part[i] = ElementTree.SubElement(required_parts, "part")
qty[i] = ElementTree.SubElement(part[i], "qty")
length[i] = ElementTree.SubElement(part[i], "length")
name[i] = ElementTree.SubElement(part[i], "name")
qty[i].text = self.t1.item(i, 0).text()
length[i].text = self.t1.item(i, 1).text()
name[i].text = self.t1.item(i, 2).text()
# Create blank list with length equal to the number of patterns in the result
blank_list = []
num_patterns = len(self.calculator.final_allocations)
for i in range(num_patterns):
blank_list.append(ElementTree.Element)
# Copy blank list to initialize each attribute
pattern = blank_list.copy()
pattern_label = blank_list.copy()
pattern_qty = blank_list.copy()
# Create blank list of lists with length equal to the number of patterns in the result
blank_list = []
for i in range(num_patterns):
num_unique_parts = np.count_nonzero(
self.calculator.final_patterns.T[i]
)
blank_list.append([])
for j in range(num_unique_parts):
blank_list[i].append(ElementTree.Element)
nested_part = blank_list.copy()
# Create blank list of lists with length equal to the number of patterns in the result
blank_list = []
for i in range(num_patterns):
num_unique_parts = np.count_nonzero(
self.calculator.final_patterns.T[i]
)
blank_list.append([])
for j in range(num_unique_parts):
blank_list[i].append(ElementTree.Element)
nested_part_name = blank_list.copy()
# Create blank list of lists with length equal to the number of patterns in the result
blank_list = []
for i in range(num_patterns):
num_unique_parts = np.count_nonzero(
self.calculator.final_patterns.T[i]
)
blank_list.append([])
for j in range(num_unique_parts):
blank_list[i].append(ElementTree.Element)
nested_part_qty = blank_list.copy()
# Add current data for required parts
for i in range(num_patterns):
pattern[i] = ElementTree.SubElement(result, "pattern")
pattern_label[i] = ElementTree.SubElement(
pattern[i], "patternLabel"
)
pattern_qty[i] = ElementTree.SubElement(pattern[i], "patternQty")
pattern_label[i].text = f"{i}"
pattern_qty[i].text = f"{int(self.calculator.final_allocations[i])}"
# Cycle through nested parts in each pattern
for j in range(len(self.calculator.final_patterns)):
ii = 0
if self.calculator.final_patterns[j, i]:
nested_part[i][ii] = ElementTree.SubElement(
pattern[i], "nestedPart"
)
nested_part_name[i][ii] = ElementTree.SubElement(
nested_part[i][ii], "nestedPartName"
)
nested_part_qty[i][ii] = ElementTree.SubElement(
nested_part[i][ii], "nestedPartQty"
)
nested_part_name[i][ii].text = f"{self.part_names[j]}"
nested_part_qty[i][
ii
].text = f"{int(self.calculator.final_patterns[j, i])}"
ii += 1
# create a new XML file with the results
save_data_string = ElementTree.tostring(nesting_job)
save_data_file = open(file_path, "wb")
save_data_file.write(save_data_string)