#!/usr/bin/env python3 """ project: GarageCalc1 file: main.py summary: Calculates available size of a garage space license: GPL author: Paul Salajean (p.salajean[at]gmx.de) """ # Standard library imports import sys import os import csv import configparser # Third party imports from PySide2.QtWidgets import QApplication, QMainWindow, QTableWidgetItem, QStatusBar, QFileDialog, \ QAbstractItemView, QMenu, QMessageBox, QHBoxLayout, QVBoxLayout, QAction, QActionGroup, QSizePolicy from PySide2.QtGui import QIcon from PySide2.QtCore import QFile, QSize, Qt, QCoreApplication, QTranslator from PySide2.QtUiTools import QUiLoader import xlsxwriter # Local imports from utils import show_about, resource_path, str_iff, fit_col_widths # my own classes imports from clsTableWidget import TableWidget # Local globals APP_VERSION = "v0.6" DIR_APPDATA = os.getenv('LOCALAPPDATA') APP_NAME = "Garage Space Calculator" APP_DISPNAME = "GarageCalc" APP_AUTHOR = "Paul Salajean" APP_DESCR = "Calculates available garage space" APP_COPYRIGHT = "(c) Paul Salajean 2021" APP_WEBSITE = "https://gitlab.com/ProfP303" APP_DESKTOPFILENAME = APP_DISPNAME APP_ICON = "./img/icons8-garage-32.ico" ICON_NEW = "./img/icons8-new-file-32.png" ICON_OPEN = "./img/icons8-opened-folder-32.png" ICON_SAVE = "./img/icons8-save-32.png" ICON_EXPORT = "./img/icons8-export-xls-32.png" ICON_ABOUT = "./img/icons8-information-32.png" ICON_QUIT = "./img/system-shutdown.png" UI_MAIN = "./ui/main.ui" DEFAULT_GARAGE_LENGTH = "6" DEFAULT_GARAGE_WIDTH = "2,5" DEFAULT_GARAGE_HEIGHT = "2,5" COL_GARAGE_LENGTH = 1 COL_GARAGE_WIDTH = 2 COL_GARAGE_HEIGHT = 3 COL_GARAGE_COMMENT = 4 COL_STUFF_NAME = 0 COL_STUFF_LENGTH = 1 COL_STUFF_WIDTH = 2 COL_STUFF_HEIGHT = 3 COL_STUFF_WEIGHT = 4 COL_STUFF_COMMENT = 5 TBL_STUFF_COL_COUNT = 6 TBL_STUFF_ROW_COUNT = 50 WIN_WIDTH = 700 WIN_HEIGHT = 640 TXT_UNSAVED_CHANGES = QCoreApplication.translate("main", "There are unsaved entries. Without saving, all changes are lost. Continue anyway?") CONFIG = configparser.ConfigParser() TRANSLATOR = QTranslator() #################################################################### def main(): qApp = QApplication(sys.argv) global APP_NAME, CONFIG, TRANSLATOR qApp.setApplicationName(APP_NAME) qApp.setApplicationDisplayName(APP_DISPNAME) qApp.setApplicationVersion(APP_VERSION) qApp.description = APP_DESCR qApp.copyright = APP_COPYRIGHT qApp.website = APP_WEBSITE qApp.setWindowIcon(QIcon(APP_ICON)) qApp.setDesktopFileName(APP_DESKTOPFILENAME) language = "Deutsch" if os.path.exists(os.path.join(DIR_APPDATA, APP_DISPNAME, APP_DISPNAME + '.ini')): CONFIG.read(os.path.join(DIR_APPDATA, APP_DISPNAME, APP_DISPNAME + '.ini')) language = CONFIG['DEFAULT']['language'] else: CONFIG['DEFAULT']['language'] = language if not os.path.exists(os.path.join(DIR_APPDATA, APP_DISPNAME)): os.makedirs(os.path.join(DIR_APPDATA, APP_DISPNAME)) with open(os.path.join(DIR_APPDATA, APP_DISPNAME, APP_DISPNAME + '.ini'), 'w') as configfile: # save CONFIG.write(configfile) print("Current dir:", os.getcwd()) if language == "Deutsch": print("Loading german language file.") TRANSLATOR.load(resource_path('./i18n/de_DE')) elif language == "Magyar": print("Loading hungarian langauge file.") TRANSLATOR.load(resource_path('./i18n/hu_HU')) else: print(f"Unknown language setting '{language}' -> defaulting to english language.") qApp.installTranslator(TRANSLATOR) app_name = qApp.translate("main", APP_NAME) qApp.setApplicationName(app_name) winMain = MainWindow(language) if qApp.primaryScreen().size().width() <= 800: winMain.showMaximized() else: winMain.resize(WIN_WIDTH, WIN_HEIGHT) winMain.show() sys.exit(qApp.exec_()) #################################################################### def create_examples(table): from random import randint, choice, uniform from string import ascii_letters, punctuation, digits min = 12 max = 15 string_format = ascii_letters for row in range(10): generated_string1 = "".join(choice(string_format) for x in range(randint(min, max))) generated_string2 = "".join(choice(string_format) for x in range(randint(min, max))) table.setItem(row, 0, QTableWidgetItem(generated_string1)) table.setItem(row, 1, QTableWidgetItem(str(round(uniform(1.1, 10.2), 2)).replace('.', ','))) table.setItem(row, 2, QTableWidgetItem(str(round(uniform(1.5, 10.2), 2)).replace('.', ','))) table.setItem(row, 3, QTableWidgetItem(str(round(uniform(1.125, 8.75), 2)).replace('.', ','))) table.setItem(row, 4, QTableWidgetItem(str(round(uniform(20, 100), 2)).replace('.', ','))) table.setItem(row, 5, QTableWidgetItem(generated_string2)) #################################################################### class MainWindow(QMainWindow): def __init__(self, language): super().__init__() self.language = language self.is_modified = False self.opened_file = None self.remembered_row = None self.load_ui() self.init_ui() self.set_defaults() self.create_menu(self.language) self.connect_signals() self.create_actions() self.create_toolbar() self.create_statusbar() self.statusBar.showMessage(f"{APP_DISPNAME} {APP_VERSION} - {APP_AUTHOR}", 5000) self.calc_voluminae() self.ui.efWeight.setText(str("0")) self.retranslateUi() # TODO: disable for PROD! # create_examples(self.ui.tableStuff) # self.ui.tableGarage.setItem(0, 3, QTableWidgetItem("Garázs az udvaron")) for col in range(self.ui.tableStuff.columnCount()): # optimize column width self.ui.tableStuff.resizeColumnToContents(col) self.ui.tableStuff.resizeRowsToContents() # optimize row height self.ui.tableStuff.setFocus() def create_menu(self, language=None): menuMain = self.menuBar() self.menuSettings = menuMain.addMenu(QCoreApplication.translate("main", "&Settings")) self.menuLanguage = self.menuSettings.addMenu(QCoreApplication.translate("main", "Language")) ag = QActionGroup(self, exclusive=True) a = ag.addAction(QAction('English', self.menuSettings, checkable=True)) self.menuLanguage.addAction(a) a = ag.addAction(QAction('Deutsch', self.menuSettings, checkable=True)) self.menuLanguage.addAction(a) a = ag.addAction(QAction('Magyar', self.menuSettings, checkable=True)) self.menuLanguage.addAction(a) menuMain.triggered.connect(lambda: self.store_selected_language(self.menuLanguage)) if language: [action.setChecked(True) for action in self.menuLanguage.actions() if action.text()==language] def retranslateUi(self): # menus self.menuSettings.setTitle(QCoreApplication.translate("main", "&Settings")) self.menuLanguage.setTitle(QCoreApplication.translate("main", "Language")) # tables self.ui.tableGarage.setVerticalHeaderLabels([ QCoreApplication.translate("main","Garage")]) self.ui.tableGarage.setHorizontalHeaderLabels([ QCoreApplication.translate("main","Length") + " [m]", QCoreApplication.translate("main","Width") + " [m]", QCoreApplication.translate("main","Height") + " [m]", QCoreApplication.translate("main","Comment") ]) self.ui.tableStuff.setHorizontalHeaderLabels([ QCoreApplication.translate("main","Stuff"), QCoreApplication.translate("main","Length") + " [m]", QCoreApplication.translate("main","Width") + " [m]", QCoreApplication.translate("main","Height") + " [m]", QCoreApplication.translate("main","Weight") + " [kg]", QCoreApplication.translate("main","Comment") ]) # labels self.ui.gbGarage.setTitle(QCoreApplication.translate("main","Dimension of the garage")) self.ui.gbStuff.setTitle(QCoreApplication.translate("main", "Dimensions of the objects to be stored")) self.ui.gbResults.setTitle(QCoreApplication.translate("main", "Result")) self.ui.lblVol_Garage.setText(QCoreApplication.translate("main","Volume of the garage") + ":") self.ui.lblVol_Stuff.setText(QCoreApplication.translate("main","Volume of the items") + ":") self.ui.lblVol_Free.setText(QCoreApplication.translate("main","Free space in the garage") + ":") self.ui.lblWeight.setText(QCoreApplication.translate("main","Total weight") + ":") # Tooltips self.actionNew.setToolTip(QCoreApplication.translate("main","New (Ctrl+N)")) self.actionOpen.setToolTip(QCoreApplication.translate("main","Open... (Ctrl+O)")) self.actionSave.setToolTip(QCoreApplication.translate("main","Save (Ctrl+S)")) self.actionExport.setToolTip(QCoreApplication.translate("main","Export to EXCEL...")) self.actionAbout.setToolTip(QCoreApplication.translate("main","Information about the application")) self.actionQuit.setToolTip(QCoreApplication.translate("main","Quit the application (Strg+Q)")) def load_ui(self): loader = QUiLoader() path = os.path.join(os.path.dirname(__file__), resource_path(UI_MAIN)) ui_file = QFile(path) ui_file.open(QFile.ReadOnly) self.ui = loader.load(ui_file, self) ui_file.close() # implement custom class 'TableWidget' layoutGb = self.ui.gbStuff.layout() self.ui.tableStuff = TableWidget(self) self.ui.tableStuff.setColumnCount(TBL_STUFF_COL_COUNT) self.ui.tableStuff.setRowCount(TBL_STUFF_ROW_COUNT) self.ui.tableStuff.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.ui.splitter.setStretchFactor(1, 10) layoutGb.addWidget(self.ui.tableStuff) def create_actions(self): self.actionNew = QAction() self.actionNew.setIcon(QIcon(resource_path(ICON_NEW))) self.actionNew.triggered.connect(self.file_new) self.actionNew.setShortcut("Ctrl+N") self.actionOpen = QAction() self.actionOpen.setIcon(QIcon(resource_path(ICON_OPEN))) self.actionOpen.triggered.connect(self.file_open) self.actionOpen.setShortcut("Ctrl+O") self.actionSave = QAction() self.actionSave.setIcon(QIcon(resource_path(ICON_SAVE))) self.actionSave.triggered.connect(self.file_save) self.actionSave.setShortcut("Ctrl+S") self.actionExport = QAction() self.actionExport.setIcon(QIcon(resource_path(ICON_EXPORT))) self.actionExport.triggered.connect(self.file_export) self.actionAbout = QAction() self.actionAbout.setIcon(QIcon(resource_path(ICON_ABOUT))) self.actionAbout.triggered.connect(show_about) self.actionQuit = QAction() self.actionQuit.setIcon(QIcon(resource_path(ICON_QUIT))) self.actionQuit.triggered.connect(self.app_quit) self.actionQuit.setShortcut("Ctrl+Q") def create_toolbar(self): # Main Toolbar (for all pages/views) self.toolbar = self.addToolBar('Main Toolbar') self.toolbar.setIconSize(QSize(32, 32)) self.toolbar.addAction(self.actionNew) self.toolbar.addAction(self.actionOpen) self.toolbar.addAction(self.actionSave) self.toolbar.addSeparator() self.toolbar.addAction(self.actionExport) self.toolbar.addSeparator() self.toolbar.addAction(self.actionAbout) self.toolbar.addSeparator() self.toolbar.addAction(self.actionQuit) def set_defaults(self): tblGarage = self.ui.tableGarage tblStuff = self.ui.tableStuff tblGarage.setItem(0, 0, QTableWidgetItem(DEFAULT_GARAGE_LENGTH)) tblGarage.setItem(0, 1, QTableWidgetItem(DEFAULT_GARAGE_WIDTH)) tblGarage.setItem(0, 2, QTableWidgetItem(DEFAULT_GARAGE_HEIGHT)) tblStuff.setRowCount(TBL_STUFF_ROW_COUNT) self.is_modified = False def create_statusbar(self): self.statusBar = QStatusBar() self.setStatusBar(self.statusBar) def connect_signals(self): tblGarage = self.ui.tableGarage tblStuff = self.ui.tableStuff tblGarage.itemChanged.connect(self.on_garage_changed) tblStuff.itemChanged.connect(self.on_stuff_changed) def init_ui(self): tblGarage = self.ui.tableGarage tblStuff = self.ui.tableStuff # clear garage tblGarage.setRowCount(1) # clear stuff ## tblStuff.clear() # tblStuff.setRowCount(0) # tblStuff.setRowCount(TBL_STUFF_ROW_COUNT) tblStuff.clearContents() # clear results self.ui.efVol_Garage.clear() self.ui.efVol_Stuff.clear() self.ui.efVol_Free.clear() self.ui.efWeight.clear() self.opened_file = None if self.opened_file: self.setWindowTitle(self.opened_file) else: self.setWindowTitle(f"{qApp.applicationName()} {APP_VERSION} - {APP_AUTHOR}") self.ui.efVol_Free.setStyleSheet("") self.is_modified = False def app_quit(self): if self.is_modified: msg = QCoreApplication.translate("main", TXT_UNSAVED_CHANGES) reply = QMessageBox.question(self, QCoreApplication.translate("main", "Quit"), msg, \ QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if reply == QMessageBox.No: return False QApplication.quit() def file_new(self): if self.is_modified: msg = QCoreApplication.translate("main", TXT_UNSAVED_CHANGES) reply = QMessageBox.question(self, QCoreApplication.translate("main", "New"), msg, \ QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if reply == QMessageBox.No: return False self.init_ui() self.ui.tableStuff.sortByColumn(-1, Qt.AscendingOrder) # reset sorting for col in range(self.ui.tableStuff.columnCount()): # optimize column width self.ui.tableStuff.resizeColumnToContents(col) self.ui.tableStuff.resizeRowsToContents() # optimize row height self.ui.tableStuff.setFocus() def file_save(self): tblGarage = self.ui.tableGarage tblStuff = self.ui.tableStuff is_file_saved = False fileName = self.opened_file if not self.opened_file: # if not file already open options = QFileDialog.Options() txt_title = QCoreApplication.translate("main", "Save") txt_file = QCoreApplication.translate("main", "CSV-file") txt_all_files = QCoreApplication.translate("main", "All files") fileName, _ = QFileDialog.getSaveFileName(None, txt_title, None, txt_file + " (*.csv);;" + txt_all_files + " (*)", options=options) if fileName: # if not file already open with open(fileName, mode='w', newline='') as garagecalc_file: writer = csv.writer(garagecalc_file, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL) garage_length = 0 garage_width = 0 garage_height = 0 garage_comment = "" item_length = tblGarage.item(0, 0) item_width = tblGarage.item(0, 1) item_height = tblGarage.item(0, 2) item_comment = tblGarage.item(0, 3) # loop over table Garage for row in range(tblGarage.rowCount()): # get garage length if item_length: garage_length = item_length.text() # get garage width if item_width: garage_width = item_width.text() # get garage height if item_height: garage_height = item_height.text() # get garage comment if item_comment: garage_comment = item_comment.text() if garage_length or garage_width or garage_height: writer.writerow([QCoreApplication.translate("main","Garage"), garage_length, garage_width, garage_height, garage_comment]) # loop over table Stuff for row in range(tblStuff.rowCount()): stuff_text = None length = None width = None height = None weight = None comment = None item_stuff = tblStuff.item(row, COL_STUFF_NAME) item_length = tblStuff.item(row, COL_STUFF_LENGTH) item_width = tblStuff.item(row, COL_STUFF_WIDTH) item_height = tblStuff.item(row, COL_STUFF_HEIGHT) item_weight = tblStuff.item(row, COL_STUFF_WEIGHT) item_comment = tblStuff.item(row, COL_STUFF_COMMENT) if item_stuff: stuff_text = item_stuff.text() if item_length: length = item_length.text() if item_width: width = item_width.text() if item_height: height = item_height.text() if item_weight: weight = item_weight.text() if item_comment: comment = item_comment.text() if stuff_text or length or width or height or weight: writer.writerow([stuff_text, length, width, height, weight, comment]) is_file_saved = True self.opened_file = os.path.basename(fileName) self.setWindowTitle(self.opened_file) self.is_modified = False if is_file_saved: msg = QCoreApplication.translate("main", "file") + " '" + fileName + "' " + QCoreApplication.translate("main", "saved") self.statusBar.showMessage(msg, 2000) def file_open(self): if self.is_modified: msg = QCoreApplication.translate("main", TXT_UNSAVED_CHANGES) reply = QMessageBox.question(self, QCoreApplication.translate("main", "Open"), msg, \ QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if reply == QMessageBox.No: return False tblGarage = self.ui.tableGarage tblStuff = self.ui.tableStuff options = QFileDialog.Options() txt_title = QCoreApplication.translate("main", "Open") txt_file = QCoreApplication.translate("main", "CSV-file") txt_all_files = QCoreApplication.translate("main", "All files") fileName, _ = QFileDialog.getOpenFileName(self, txt_title, None, txt_file + " (*.csv);;" + txt_all_files + " (*)", options=options) if fileName: self.init_ui() self.ui.tableStuff.sortByColumn(-1, Qt.AscendingOrder) # reset sorting file = open(fileName, "r", newline='') reader = csv.reader(file, delimiter=';') row_idx = 0 for row in reader: if row_idx == 0: # first row (index=0) ist always garage dimension try: garage_length = str(row[COL_GARAGE_LENGTH].replace(".", ",")) garage_width = str(row[COL_GARAGE_WIDTH].replace(".", ",")) garage_height = str(row[COL_GARAGE_HEIGHT].replace(".", ",")) garage_comment = row[COL_GARAGE_COMMENT] tblGarage.setItem(0, 0, QTableWidgetItem(garage_length)) tblGarage.setItem(0, 1, QTableWidgetItem(garage_width)) tblGarage.setItem(0, 2, QTableWidgetItem(garage_height)) tblGarage.setItem(0, 3, QTableWidgetItem(garage_comment)) except IndexError as ex: pass if row_idx > 0: try: stuff = row[COL_STUFF_NAME] stuff_length = str(row[COL_STUFF_LENGTH].replace(".", ",")) stuff_width = str(row[COL_STUFF_WIDTH].replace(".", ",")) stuff_height = str(row[COL_STUFF_HEIGHT].replace(".", ",")) stuff_weight = str(row[COL_STUFF_WEIGHT].replace(".", ",")) stuff_comment = row[COL_STUFF_COMMENT] tblStuff.setItem(row_idx - 1, COL_STUFF_NAME, QTableWidgetItem(stuff)) item = QTableWidgetItem() item.setData(Qt.DisplayRole, stuff_length) tblStuff.setItem(row_idx - 1, COL_STUFF_LENGTH, item) # tblStuff.setItem(row_idx - 1, COL_STUFF_WIDTH, QTableWidgetItem(float(stuff_width))) item = QTableWidgetItem() item.setData(Qt.DisplayRole, stuff_width) tblStuff.setItem(row_idx - 1, COL_STUFF_WIDTH, item) #tblStuff.setItem(row_idx - 1, COL_STUFF_HEIGHT, QTableWidgetItem(float(stuff_height))) item = QTableWidgetItem(stuff_height) item.setData(Qt.DisplayRole, stuff_height) tblStuff.setItem(row_idx - 1, COL_STUFF_HEIGHT, item) # tblStuff.setItem(row_idx - 1, COL_STUFF_WEIGHT, QTableWidgetItem(float(stuff_weight))) item = QTableWidgetItem(stuff_weight) item.setData(Qt.DisplayRole, stuff_weight) tblStuff.setItem(row_idx - 1, COL_STUFF_WEIGHT, item) tblStuff.setItem(row_idx - 1, COL_STUFF_COMMENT, QTableWidgetItem(stuff_comment)) except IndexError as ex: pass row_idx += 1 tblStuff.setRowCount(TBL_STUFF_ROW_COUNT) for col in range(self.ui.tableStuff.columnCount()): # optimize column width self.ui.tableStuff.resizeColumnToContents(col) self.ui.tableStuff.resizeRowsToContents() # optimize row height self.ui.tableStuff.setFocus() self.is_modified = False self.opened_file = os.path.basename(fileName) if fileName: self.setWindowTitle(self.opened_file) else: self.setWindowTitle(f"{qApp.applicationName()} {APP_VERSION} - {APP_AUTHOR}") def file_export(self): tblGarage = self.ui.tableGarage tblStuff = self.ui.tableStuff options = QFileDialog.Options() txt_title = QCoreApplication.translate("main", "Export") txt_file = QCoreApplication.translate("main", "EXCEL-file") txt_all_files = QCoreApplication.translate("main", "All files") file_name, _ = QFileDialog.getSaveFileName(None, txt_title, None, txt_file + " (*.xlsx);;" + txt_all_files + " (*)", options=options) if file_name: print(f"Exporting into file -> {file_name}") workbook = xlsxwriter.Workbook(file_name) worksheet = workbook.add_worksheet() # write col header start_row = 0 worksheet.write_string(start_row, 0, QCoreApplication.translate("main", "Dimension of the garage")) start_row = 1 worksheet.write_string(start_row, COL_STUFF_LENGTH, QCoreApplication.translate("main","Length") + " [m]") worksheet.write_string(start_row, COL_STUFF_WIDTH, QCoreApplication.translate("main","Width") + " [m]") worksheet.write_string(start_row, COL_STUFF_HEIGHT, QCoreApplication.translate("main","Height") + " [m]") worksheet.write_string(start_row, COL_STUFF_COMMENT, QCoreApplication.translate("main","Comment")) worksheet.set_column(0, 0, 25) worksheet.set_column(1, 3, 10) worksheet.set_column(4, 5, 20) start_row = 2 # loop over table Garage for row in range(tblGarage.rowCount()): garage_length = tblGarage.item(0, 0).text() garage_width = tblGarage.item(0, 1).text() garage_height = tblGarage.item(0, 2).text() garage_comment = tblGarage.item(0, 3).text() worksheet.write_number(start_row + row, COL_STUFF_LENGTH, float(garage_length.replace(',', '.'))) worksheet.write_number(start_row + row, COL_STUFF_WIDTH, float(garage_width.replace(',', '.'))) worksheet.write_number(start_row + row, COL_STUFF_HEIGHT, float(garage_height.replace(',', '.'))) worksheet.write_string(start_row + row, COL_STUFF_COMMENT, garage_comment) start_row = 4 worksheet.write_string(start_row, 0, QCoreApplication.translate("main", "Dimensions of the objects to be stored")) start_row = 5 worksheet.write_string(start_row, COL_STUFF_LENGTH, QCoreApplication.translate("main","Length") + " [m]") worksheet.write_string(start_row, COL_STUFF_WIDTH, QCoreApplication.translate("main","Width") + " [m]") worksheet.write_string(start_row, COL_STUFF_HEIGHT, QCoreApplication.translate("main","Height") + " [m]") worksheet.write_string(start_row, COL_STUFF_WEIGHT, QCoreApplication.translate("main","Weight") + " [kg]") worksheet.write_string(start_row, COL_STUFF_COMMENT, QCoreApplication.translate("main","Comment") ) start_row = 6 # loop over table Stuff formula = "" row_idx = start_row for row in range(tblStuff.rowCount()): item_stuff = tblStuff.item(row, COL_STUFF_NAME) item_length = tblStuff.item(row, COL_STUFF_LENGTH) item_width = tblStuff.item(row, COL_STUFF_WIDTH) item_height = tblStuff.item(row, COL_STUFF_HEIGHT) item_weight = tblStuff.item(row, COL_STUFF_WEIGHT) item_comment = tblStuff.item(row, COL_STUFF_COMMENT) if item_stuff: stuff_text = item_stuff.text() if len(stuff_text)>0: worksheet.write_string(start_row + row, COL_STUFF_NAME, stuff_text) if item_length: try: length = item_length.text() if length: worksheet.write_number(start_row + row, COL_STUFF_LENGTH, float(length.replace(',', '.'))) except ValueError: pass if item_width: try: width = item_width.text() if width: worksheet.write_number(start_row + row, COL_STUFF_WIDTH, float(width.replace(',', '.'))) except ValueError: pass if item_height: try: height = item_height.text() if height: worksheet.write_number(start_row + row, COL_STUFF_HEIGHT, float(height.replace(',', '.'))) except ValueError: pass if item_weight: try: weight = item_weight.text() if weight: worksheet.write_number(start_row + row, COL_STUFF_WEIGHT, float(weight.replace(',', '.'))) except ValueError: pass if item_comment: comment = item_comment.text() if len(comment)>0: worksheet.write_string(start_row + row, COL_STUFF_COMMENT, comment) if item_stuff or item_length or item_width or item_height or item_weight: row_idx += 1 formula = formula + str_iff(formula, "", "=ROUND(", " + ") + f"(B{row_idx} * C{row_idx} * D{row_idx})" formula += ", 2)" row_idx += 1 # loop over Results worksheet.write_string(row_idx, 0, QCoreApplication.translate("main","Result")) row_idx += 1 worksheet.write_string(row_idx, 0, QCoreApplication.translate("main","Volume of the garage") + ":") # worksheet.write(row_idx, 1, self.ui.efVol_Garage.text()) worksheet.write_formula(row_idx, 1, '=B3 * C3 * D3') row_idx += 1 worksheet.write_string(row_idx, 0, QCoreApplication.translate("main","Volume of the items") + ":") #worksheet.write_number(row_idx, 1, float(self.ui.efVol_Stuff.text().replace(',', '.'))) worksheet.write_formula(row_idx, 1, formula) row_idx += 1 worksheet.write_string(row_idx, 0, QCoreApplication.translate("main","Free space in the garage") + ":") # worksheet.write(row_idx, 1, self.ui.efVol_Free.text()) worksheet.write_formula(row_idx, 1, f"=B{row_idx-1}-B{row_idx}") row_idx += 1 worksheet.write_string(row_idx, 0, QCoreApplication.translate("main", "Total weight") + ":") # worksheet.write(row_idx, 1, self.ui.efWeight.text()) worksheet.write_formula(row_idx, 1, f"=SUM(E7:E{row_idx-5}") fit_col_widths(tblStuff, worksheet) workbook.close() msg = QCoreApplication.translate("main", "Successfully exported to EXCEL") + " :-)" self.statusBar.showMessage(msg, 5000) def on_garage_changed(self): self.is_modified = True self.calc_voluminae() def on_stuff_changed(self): self.is_modified = True self.calc_voluminae() self.calc_weight() def get_garage_vol(self): tblGarage = self.ui.tableGarage is_error = False garage_length = 0 garage_width = 0 garage_height = 0 # get garage length if tblGarage.item(0, 0): garage_length = tblGarage.item(0, 0).text() if garage_length: try: garage_length = float(garage_length.replace(',', '.')) except ValueError: garage_length = 0.0 is_error = True # get garage width if tblGarage.item(0, 1): garage_width = tblGarage.item(0, 1).text() if garage_width: try: garage_width = float(garage_width.replace(',', '.')) except ValueError: garage_width = 0.0 is_error = True # get garage height if tblGarage.item(0, 2): garage_height = tblGarage.item(0, 2).text() if garage_height: try: garage_height = float(garage_height.replace(',', '.')) except ValueError: garage_height = 0.0 is_error = True if not is_error: garage_vol = round(garage_length * garage_width * garage_height, 2) else: msg = QCoreApplication.translate("main", "Error in the garage dimension") + " :-(" self.statusBar.showMessage(msg, 5000) return garage_vol def get_stuff_vol(self): tblStuff = self.ui.tableStuff stuff_vol = 0 length = 0 width = 0 height = 0 # get number of rows row_count = tblStuff.rowCount() is_error = False # get stuff voluminae for row in range(row_count): vol = 0 length = 0 width = 0 height = 0 item_length = tblStuff.item(row, COL_STUFF_LENGTH) item_width = tblStuff.item(row, COL_STUFF_WIDTH) item_height = tblStuff.item(row, COL_STUFF_HEIGHT) if item_length: try: length = float(item_length.text().replace(',', '.')) except ValueError: length = 0 is_error = True if item_width: try: width = float(item_width.text().replace(',', '.')) except ValueError: width = 0 is_error = True if item_height: try: height = float(item_height.text().replace(',', '.')) except ValueError: height = 0 is_error = True vol = length * width * height stuff_vol = round(stuff_vol + vol, 2) if is_error: # stuff_vol = 0.0 msg = QCoreApplication.translate("main", "Error in the dimensions of the objects to be stored") + " :-(" self.statusBar.showMessage(msg, 5000) return stuff_vol def calc_voluminae(self): tblGarage = self.ui.tableGarage # get garage vol garage_vol = self.get_garage_vol() # print(f"{garage_vol=}") # get stuff vol stuff_vol = self.get_stuff_vol() # print(f"{stuff_vol=}") # get free space free_vol = garage_vol - stuff_vol # print(f"{free_vol=}") # display results self.ui.efVol_Garage.setText(f"{str(garage_vol).replace('.', ',')}") self.ui.efVol_Stuff.setText(f"{str(stuff_vol).replace('.', ',')}") self.ui.efVol_Free.setText(f"{str(free_vol).replace('.', ',')}") if free_vol < 0: self.ui.efVol_Free.setStyleSheet("border: 1px solid red;") else: self.ui.efVol_Free.setStyleSheet("") def calc_weight(self): tblStuff = self.ui.tableStuff weight_sum = 0 # get number of rows row_count = tblStuff.rowCount() for row in range(row_count): weight = 0.0 item = tblStuff.item(row, COL_STUFF_WEIGHT) if item: try: weight = float(str(item.text()).replace(',','.')) except ValueError: weight = 0.0 weight_sum = round(weight_sum + weight, 2) self.ui.efWeight.setText(f"{str(weight_sum).replace('.', ',')}") def store_selected_language(self, menu): """ Stores selected menu labels to ini-file. """ # [print(action.text()) for action in menu.actions() if action.isChecked()] global CONFIG print("Current dir:", os.getcwd()) language = "English" for action in menu.actions(): if action.isChecked(): language = action.text() CONFIG['DEFAULT']['language'] = language if not os.path.exists(os.path.join(DIR_APPDATA, APP_DISPNAME)): os.makedirs(os.path.join(DIR_APPDATA, APP_DISPNAME)) with open(os.path.join(DIR_APPDATA, APP_DISPNAME, APP_DISPNAME + '.ini'), 'w') as configfile: # save CONFIG.write(configfile) if language == "Deutsch": print("Loading german language file.") TRANSLATOR.load(resource_path('./i18n/de_DE')) elif language == "Magyar": print("Loading hungarian langauge file.") TRANSLATOR.load(resource_path('./i18n/hu_HU')) else: print(f"Unknown language setting '{language}' -> defaulting to english language.") TRANSLATOR.load("dummy") self.retranslateUi() #################################################################### if __name__ == "__main__": main()