def add_bar_chart(self): Plotter.draw_and_print(self.input_data) layout = self.barChart.layout() if layout != None: QObjectCleanupHandler().add(self.barChart.layout()) layout = QtWidgets.QVBoxLayout() label = QtWidgets.QLabel(self) pixmap = QPixmap('plt/bar_chart.png') pixmap = pixmap.scaled(451,331, Qt.KeepAspectRatio, Qt.FastTransformation) label.setPixmap(pixmap) layout.addWidget(label) self.barChart.setLayout(layout)
def add_main_plot(self): layout = self.mainPlot.layout() if layout != None: QObjectCleanupHandler().add(self.mainPlot.layout()) layout = QtWidgets.QVBoxLayout() self.scGlowny = MplCanvas(self) for dane in self.input_data: self.scGlowny.axes.plot(dane[1],dane[4],label = dane[0], linewidth = 4) #sc.axes.text(1,3.6,"Wyniki firm względem czynników", horizontalalignment = 'center', verticalalignment = 'center', fontsize=12) self.scGlowny.axes.set_title("Wykres wyników firm względem czynników.") self.scGlowny.axes.grid(axis = 'y',color = 'gray', linestyle='-', linewidth = 1) self.scGlowny.axes.legend() self.scGlowny.correct_ticks() layout.addWidget(self.scGlowny) self.mainPlot.setLayout(layout)
def add_pie_chart(self): layout = self.pieChart.layout() if layout != None: QObjectCleanupHandler().add(self.pieChart.layout()) layout = QtWidgets.QVBoxLayout() self.scPie = MplCanvas(self) wyniki = [] labele = [] for dane in self.input_data: wyniki.append(sum(dane[4])) labele.append(dane[0]) explode = [] dex = wyniki.index(max(wyniki)) for i in range(0,len(wyniki)): if i == dex: explode.append(0.05) else: explode.append(0.01) wyniki = array(wyniki) labele = array(labele) self.scPie.axes.pie(x = wyniki,labels = labele, explode = explode, shadow = False, autopct='%1.1f%%') self.scPie.axes.set_title("Udział w wynikach każdej z firm") layout.addWidget(self.scPie) self.pieChart.setLayout(layout)
return else: Plotter.export_bar_chart(self.input_data,filepath) def savePlotDialog(self, filename): options = QtWidgets.QFileDialog.Options() fileName, _ = QtWidgets.QFileDialog.getSaveFileName(self,"Zapisz wykres jako...", filename,"PNG files (*.png);; PDF files (*.pdf)", options=options) return fileName class MplCanvas(FigureCanvas): def __init__(self, parent=None, width=5, height=4, dpi=100): self.fig = Figure(figsize=(width, height), dpi=dpi) self.axes = self.fig.add_subplot(111) super(MplCanvas, self).__init__(self.fig) def correct_ticks(self): for xtick in self.axes.get_xticklabels(): xtick.set_rotation(20) def export(self, filepath): self.fig.savefig(filepath) if __name__ == "__main__": app = QtWidgets.QApplication([]) window = MainWindow() window.show() if window.sample_xl_created_flag: window.view_starting_popup() else: pass app.exec_()
def main(): # parse command-line parameters parser = argparse.ArgumentParser() parser.add_argument('-s', '--settings', help='Load settings from file') parser.add_argument('-o', '--open', help='Open crossword file') parser.add_argument('-n', '--new', action='store_true', help='Create crossword') parser.add_argument('--cols', type=int, default=15, help='Number of columns') parser.add_argument('--rows', type=int, default=15, help='Number of rows') parser.add_argument('--pattern', type=int, default=1, choices=[1, 2, 3, 4, 5, 6], help='Pattern type for new crossword') parser.add_argument('-e', '--empty', action='store_true', help='Do not open/restore or create a crossword') parser.add_argument( '-a', '--addsrc', default='', action='append', help='Add word source' ) # see WordSrcDialog definition in forms.py for source string format args = parser.parse_args() from utils.globalvars import readSettings, switch_lang, DEBUGGING # read settings if args.settings: settings_file = args.settings elif args.open and os.path.splitext(args.open)[1][1:].lower() == 'pxjson': settings_file = args.open args.open = None else: settings_file = None settings = readSettings(settings_file) # switch language switch_lang(settings['common']['lang']) from gui import QtCore, QtWidgets, MainWindow try: # change working dir to current for correct calls to git os.chdir(os.path.dirname(os.path.abspath(__file__))) # initialize Qt Core App settings QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling) # create QApplication instance app = QtWidgets.QApplication(sys.argv) # localize Qt widgets lang = settings['common']['lang'] or 'en' locale = QtCore.QLocale(lang) locale_name = locale.name() #print(locale_name) QtCore.QLocale.setDefault(locale) if lang != 'en': qts = ('qtbase_', 'qt_') for qt in qts: translator = QtCore.QTranslator() if translator.load(locale, qt, '', f"locale/{locale_name}/qt"): if not app.installTranslator(translator) and DEBUGGING: print( _("Cannot install QT translator for locale '{}' and domain '{}'!" ).format(locale_name, qt)) # create main window (passing all found command-line args) MainWindow(**vars(args)) # run app's event loop sys.exit(app.exec_()) except SystemExit as err: if str(err) != '0': traceback.print_exc(limit=None) except Exception as err: traceback.print_exc(limit=None) sys.exit(1) except: traceback.print_exc(limit=None) sys.exit(1)
def main(): if len(sys.argv) != 2: print("Error 4. Doesn't have path to the config-file as argument") exit(1) else: config_path = sys.argv[1] worker_data = {} if os.path.exists(os.path.dirname(config_path)): try: import json with open(config_path, 'r') as infile: worker_data = json.load(infile) except IOError as ex: if ex.errno == 2: print("Error 1. The config file doesn't exist") exit(1) except ValueError as ex: print("Error 2. Incorrect Json in the config file: " + str(ex)) exit(1) else: print("Error 3. The config file doesn't exist") exit(1) if worker_data["gui"]: # больше одного worker как отдельного процесса вроде как не запустить! # https://pythonworld.ru/osnovy/instrukciya-if-elif-else-proverka-istinnosti-trexmestnoe-vyrazhenie-ifelse.html # A = Y if X else Z app = QtWidgets.QApplication( sys.argv) # Новый экземпляр QApplication global window window = MainWindowApp() # Создаём объект класса ExampleApp window.show() # Показываем окно # create_threads(1, finder, db, source, target, worker_data["finder"]["search_interval"], worker_data["finder"]["mkdir_interval"], wq, worker_data["rules"]["include"], worker_data["rules"]["exclude"], worker_data["db"]["key"], worker_data["db"]["default_record"], logger) # create_threads(worker_data["mover_count"], mover, target, source, wq, logger) app.exec_() # и запускаем приложение return 0 else: if worker_data["enable"]: logger = get_logger(worker_data["name"], worker_data["logger"]["log_level"], worker_data["logger"]["console_output"], worker_data["logger"]["log_path"]) db = JsonArray(worker_data["db_backup"]["db_path"], worker_data["db_backup"]["autosave_interval"], logger) wq = Queue() for record in db: if not record['downloaded'] or not record[ 'uploaded'] or not record['dropped']: wq.put(record) m1 = __import__(worker_data["source"]["device"]) worker_data["source"]["args"]["logger"] = logger source = getattr(m1, worker_data["source"]["device"])( **worker_data["source"]["args"]) m2 = __import__(worker_data["target"]["device"]) worker_data["target"]["args"]["logger"] = logger target = getattr(m2, worker_data["target"]["device"])( **worker_data["target"]["args"]) def create_threads(count, function, *args): for i in range(count): t = Thread(target=function, args=( i + 1, args, )) t.daemon = True t.start() window = None create_threads(1, finder, window, db, source, target, worker_data["finder"]["search_interval"], worker_data["finder"]["mkdir_interval"], wq, worker_data["rules"]["include"], worker_data["rules"]["exclude"], worker_data["db"]["key"], worker_data["db"]["default_record"], logger) create_threads(worker_data["mover_count"], mover, window, target, source, wq, logger) try: while True: time.sleep(10) except KeyboardInterrupt: # del db # smart_buffer.dump() return 0