/ qr_code_generator.py
qr_code_generator.py
1 import PIL.ImageQt 2 import PyQt6.QtGui 3 import PyQt6.QtWidgets 4 import json 5 import os 6 import qrcode 7 8 9 def json_file_read(filename): 10 """reads filename with json inside and returns file data as dict 11 12 param filename: filename to read 13 type filename: str 14 15 return: return dict of data from json file, empty dict returned if error in reading file or json 16 rtype: dict 17 """ 18 try: 19 with open(file=filename, mode='r') as file: 20 data = json.load(file) 21 except Exception as e: 22 print("Oops Error: {}".format(e)) 23 data = {} 24 return data 25 return data 26 27 28 class QRGuiApp: 29 """QT App to generate and show QR Codes""" 30 31 def __init__(self): 32 """QT App init""" 33 # read config 34 filename = "{}/{}".format(os.getcwd(), "config/config.json") 35 self.data = json_file_read(filename) 36 37 # init qt app 38 self.app = PyQt6.QtWidgets.QApplication([]) 39 self.main_window = PyQt6.QtWidgets.QWidget() 40 if self.data.get("icon", False): 41 self.main_window.setWindowIcon(PyQt6.QtGui.QIcon(self.data.get("icon", False))) 42 self.main_window.setWindowTitle(self.data.get("main_window_name", "TGA")) 43 44 # create layout with textbox, button, label, button 45 layout = PyQt6.QtWidgets.QVBoxLayout() 46 47 self.textbox = PyQt6.QtWidgets.QLineEdit(self.data.get("textbox", "https://vaultcity.net")) 48 layout.addWidget(self.textbox) 49 50 # add button to layout and connect button to function 51 button_generate = PyQt6.QtWidgets.QPushButton("Generate") 52 button_generate.clicked.connect(self.on_click_button_gen) 53 layout.addWidget(button_generate) 54 55 self.img_label = PyQt6.QtWidgets.QLabel() 56 self.on_click_button_gen() 57 layout.addWidget(self.img_label) 58 59 # add button to layout and connect button to function 60 button_save = PyQt6.QtWidgets.QPushButton("Save") 61 button_save.clicked.connect(self.on_click_button_save) 62 layout.addWidget(button_save) 63 64 # set generated layout on main window 65 self.main_window.setLayout(layout) 66 67 def on_click_button_gen(self): 68 """method to run after generate button clicked 69 70 generates new qr code from textbox and shows it 71 """ 72 img = qrcode.make(self.textbox.text()) 73 pixmap = PyQt6.QtGui.QPixmap.fromImage(PIL.ImageQt.ImageQt(img)) 74 self.img_label.setPixmap(pixmap) 75 76 def on_click_button_save(self): 77 """method to run after save button is clicked 78 79 open save file dialog and save qr code image 80 """ 81 self.on_click_button_gen() 82 filename = PyQt6.QtWidgets.QFileDialog.getSaveFileName(None, "Save QR Code", 83 self.data.get("filename", "test.png"), 84 "Image File (*.png)") # filename as String 85 if filename: 86 img = qrcode.make(self.textbox.text()) 87 img.save("{}".format(filename[0])) 88 89 def run(self): 90 """run qt app""" 91 self.main_window.show() 92 self.app.exec() 93 94 95 if __name__ == '__main__': 96 """main - just to instantiate qt app class and run it""" 97 gui = QRGuiApp() 98 gui.run()