class PredictionsTab(QWidget): def __init__(self, patient): QWidget.__init__(self) self.patient = patient self.prediction_views = set() self.toolbar = QToolBar() self.toolbar.setMovable(False) add_prediction = QAction(QIcon("resources/icon/plus.png"), "Dodaj predykcję", self) add_prediction.triggered.connect(self.addPredictionForm) add_prediction.setStatusTip("Dodaj pomiary") self.toolbar.addAction(add_prediction) delete_prediction = QAction(QIcon("resources/icon/trash-bin.png"), "Usuń predykcję", self) delete_prediction.triggered.connect(self.deletePrediction) delete_prediction.setStatusTip("Usuń pomiar") self.toolbar.addAction(delete_prediction) draw_predictions = QAction(QIcon("resources/icon/graph.png"), "Rysuj predykcje", self) draw_predictions.triggered.connect(self.showPredictions) draw_predictions.setStatusTip("Rysuj predykcje") self.toolbar.addAction(draw_predictions) self.table = QTableWidget() self.table.setSelectionMode(QAbstractItemView.ExtendedSelection) self.table.setSelectionBehavior(QAbstractItemView.SelectRows) self.table.setColumnCount(3) self.table.setHorizontalHeaderLabels(["Id", "Data", "Metoda"]) self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) self.table.verticalHeader().setVisible(False) self.fillTable() main_layout = QHBoxLayout(self) main_layout.setMenuBar(self.toolbar) main_layout.addWidget(self.table) def fillTable(self): for p in self.patient.predictions: self.addPrediction(p) def addPrediction(self, prediction: Prediction): row_count = self.table.rowCount() print(prediction) self.table.insertRow(row_count) self.table.setItem( row_count, 0, self.tableWidgetItem(str(prediction.db_id)), ) self.table.setItem( row_count, 1, self.tableWidgetItem( prediction.datetime_created.strftime(DATETIME_FORMAT)), ) self.table.setItem(row_count, 2, self.tableWidgetItem(prediction.method)) def tableWidgetItem(self, value): item = QTableWidgetItem(value) item.setFlags(item.flags() & ~Qt.ItemIsEditable) return item def addPredictionForm(self): self.predicion_form = PredictionForm(self, self.patient) self.predicion_form.exec() def deletePrediction(self): current_row = self.table.currentRow() if current_row == -1: QMessageBox.warning( self, "Usuwanie predykcji", "Brak danych w tabeli", ) return prediction_datetime = datetime.fromisoformat( self.table.item(current_row, 1).text()) delete_prediction_for_patient(self.patient, prediction_datetime) self.table.removeRow(current_row) def showPredictions(self): logging.debug( "All predictions %s", [(p.method, p.datetime_created) for p in self.patient.predictions], ) selected_rows = set( [ind.row() for ind in self.table.selectedIndexes()]) logging.debug("%s", selected_rows) chosen_predictions_ids: List[int] = [ int(self.table.item(ind, 0).text()) for ind in selected_rows ] logging.debug("Selected db_ids from table: %s", chosen_predictions_ids) chosen_predictions: Set[Prediction] = { prediction for prediction in self.patient.predictions if prediction.db_id in chosen_predictions_ids } logging.debug( "Selected predictions to graph: %s %d %s", chosen_predictions, len(chosen_predictions), type(chosen_predictions), ) predictions_view = PredictionsView( f"{self.patient.name} {self.patient.surname}", self.patient.measurements, chosen_predictions, ) predictions_view.show() self.prediction_views.add(predictions_view) logging.debug("Prediction views %s", self.prediction_views)
def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.sql = None self.filter = [[ "Файлы баз данных (*.db *.sdb *.sqlite *.db3 *.s3db *.sqlite3 *.sl3 *.db2 *.s2db *.sqlite2 " "*.sl2)" ], ["Все файлы (*)"]] self.action_widgets = [] self.filename = None self.action_4 = QAction("Выход") icon_000 = QIcon('ico/exit_closethesession_close_6317.ico') self.action_4.setIcon(icon_000) self.ui.menuFile.addAction(self.action_4) self.action_4.triggered.connect(self.exit) self.ui.action.triggered.connect(self.openFile) self.ui.action_2.triggered.connect(self.newFile) self.ui.action_3.triggered.connect(self.saveFile) self.action_widgets.append(self.ui.action_3) self.ui.menuFile.setTitle('Файл') toolbar = QToolBar() self.addToolBar(Qt.TopToolBarArea, toolbar) toolbar.setMovable(False) self.open_new_file = QWidgetAction(self.ui.menubar) icon01 = QIcon('ico/catalog_open.ico') self.open_new_file.setIcon(icon01) self.open_new_file.setToolTip('Открыть каталог') toolbar.addAction(self.open_new_file) self.open_new_file.triggered.connect(self.openFile) self.create_catalog = QWidgetAction(self.ui.menubar) icon03 = QIcon('ico/new-file_40454.ico') self.create_catalog.setIcon(icon03) self.create_catalog.setToolTip('Создать каталог') toolbar.addAction(self.create_catalog) self.create_catalog.triggered.connect(self.newFile) self.save_file = QWidgetAction(self.ui.menubar) icon02 = QIcon('ico/save_14949.ico') self.save_file.setIcon(icon02) self.save_file.setToolTip('Сохранить изменения') toolbar.addAction(self.save_file) self.save_file.triggered.connect(self.saveFile) self.action_widgets.append(self.save_file) self.search = QWidgetAction(self.ui.menubar) icon1 = QIcon('ico/android-search_icon-icons.com_50501.ico') self.search.setIcon(icon1) self.search.setToolTip('Найти запись') toolbar.addAction(self.search) self.search.triggered.connect(self.bookSearch) self.action_widgets.append(self.search) self.add_table_row = QWidgetAction(self.ui.menubar) icon2 = QIcon('ico/add-book_icon-icons.com_71795.ico') self.add_table_row.setIcon(icon2) self.add_table_row.setToolTip('Добавить запись') toolbar.addAction(self.add_table_row) self.add_table_row.triggered.connect(self.addRecord) self.action_widgets.append(self.add_table_row) self.del_table_row = QWidgetAction(self.ui.menubar) icon3 = QIcon('ico/open-book-with-minus-sign_icon-icons.com_70432.ico') self.del_table_row.setIcon(icon3) self.del_table_row.setToolTip('Удалить запись') toolbar.addAction(self.del_table_row) self.del_table_row.triggered.connect(self.removeRecord) self.action_widgets.append(self.del_table_row) self.clean_catalog = QWidgetAction(self.ui.menubar) icon4 = QIcon('ico/delete_4219.ico') self.clean_catalog.setIcon(icon4) self.clean_catalog.setToolTip('Очистить каталог') toolbar.addAction(self.clean_catalog) self.clean_catalog.triggered.connect(self.cleanCatalog) self.action_widgets.append(self.clean_catalog) self.undo_action = QWidgetAction( self.ui.menubar ) # TODO: Не отменяет добавление, удаление и очистку записей icon5 = QIcon('ico/undolinear_106178.ico') self.undo_action.setIcon(icon5) self.undo_action.setToolTip('Отмена действия') toolbar.addAction(self.undo_action) self.undo_action.triggered.connect(self.undoAction) self.action_widgets.append(self.undo_action) self.refresh_catalog = QWidgetAction(self.ui.menubar) icon6 = QIcon('ico/vcsupdaterequired_93493.ico') self.refresh_catalog.setIcon(icon6) self.refresh_catalog.setToolTip('Обновить') toolbar.addAction(self.refresh_catalog) self.refresh_catalog.triggered.connect(self.refresh) self.action_widgets.append(self.refresh_catalog) self.close_catalog = QWidgetAction(self.ui.menubar) icon7 = QIcon('ico/action_exit_close_remove_13915.ico') self.close_catalog.setIcon(icon7) self.close_catalog.setToolTip('Закрыть каталог') toolbar.addAction(self.close_catalog) self.close_catalog.triggered.connect(self.catalogClose) self.action_widgets.append(self.close_catalog) self.actionwidgetsOff()
class TreatmentsTab(QWidget): def __init__(self, patient): QWidget.__init__(self) self.patient = patient self.toolbar = QToolBar() self.toolbar.setMovable(False) add_treatment = QAction( QIcon("resources/icon/plus.png"), "Podaj lekarstwo", self ) add_treatment.triggered.connect(self.addTreatmentForm) add_treatment.setStatusTip("Dodaj pomiary") self.toolbar.addAction(add_treatment) delete_treatment = QAction( QIcon("resources/icon/trash-bin.png"), "Usuń podanie lekarstwa", self ) delete_treatment.triggered.connect(self.deleteCurrentTreatment) delete_treatment.setStatusTip("Usuń pomiar") self.toolbar.addAction(delete_treatment) self.table = QTableWidget() self.table.setColumnCount(2) self.table.setHorizontalHeaderLabels(["Data", "Zawartość lekarstwa"]) self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) self.fillTable(patient.treatments) main_layout = QHBoxLayout(self) main_layout.setMenuBar(self.toolbar) main_layout.addWidget(self.table) def addTreatmentForm(self): logging.debug("Entering TreatmentForm of patient %s", self.patient) self.treatment_form = TreatmentForm(self, self.patient) self.treatment_form.show() def fillTable(self, treatments): for tr in treatments: self.addTreatment(tr) def addTreatment(self, treatment): row_count = self.table.rowCount() self.table.insertRow(row_count) self.table.setItem( row_count, 0, self.tableWidgetItem(treatment.date.isoformat()) ) self.table.setItem(row_count, 1, self.tableWidgetItem(str(treatment.amount))) def tableWidgetItem(self, value): item = QTableWidgetItem(value) item.setFlags(item.flags() & ~Qt.ItemIsEditable) return item def deleteCurrentTreatment(self): if self.table.rowCount() == 0: QMessageBox.warning( self, "Usuwanie podania lekarstwa", "Brak danych w tabeli", ) return current_row = self.table.currentRow() if current_row == -1: QMessageBox.warning( self, "Usuwanie lekarstwa", "Brak wskazania na żaden pomiar", ) return treatment = self.patient.treatments[current_row] answer = QMessageBox.question( self, "Usuwanie pomiaru", f"Czy na pewno chcesz usunąć podanie lekarstwa {treatment}?", ) if answer == QMessageBox.Yes: delete_treatment_for_patient(self.patient, treatment) self.table.removeRow(current_row) logging.debug(f"Deleting {treatment}")
class PatientListView(QWidget): columns = ["Identyfikator", "Imię", "Nazwisko"] def __init__(self): QWidget.__init__(self) self.toolbar = QToolBar() self.toolbar.setMovable(False) btn_ac_adduser = QAction(QIcon("resources/icon/add-user.png"), "Add Patient", self) btn_ac_adduser.triggered.connect(self.addPatientForm) btn_ac_adduser.setStatusTip("Add Student") self.toolbar.addAction(btn_ac_adduser) btn_ac_delete = QAction(QIcon("resources/icon/remove-user.png"), "Delete Patient", self) btn_ac_delete.triggered.connect(self.deleteCurrentPatient) btn_ac_delete.setStatusTip("Delete User") self.toolbar.addAction(btn_ac_delete) self.table = QTableWidget() self.table.setSelectionBehavior(QAbstractItemView.SelectRows) self.table.setColumnCount(len(self.columns)) self.table.verticalHeader().setVisible(False) self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) self.table.setHorizontalHeaderLabels(self.columns) self.reload() layout = QHBoxLayout(self) layout.setMenuBar(self.toolbar) layout.addWidget(self.table) def fillTable(self): for patient in self.data: self.addPatient(patient) def addPatient(self, patient): ind = self.table.rowCount() self.table.insertRow(ind) self.table.setItem(ind, 0, self.tableWidgetItem(str(patient.db_id))) self.table.setItem(ind, 1, self.tableWidgetItem(patient.name)) self.table.setItem(ind, 2, self.tableWidgetItem(patient.surname)) def tableWidgetItem(self, value): item = QTableWidgetItem(value) item.setFlags(item.flags() & ~Qt.ItemIsEditable) return item def addPatientForm(self): logging.debug("Entering PatientForm") self.patient_form = PatientForm() answer = self.patient_form.exec() if answer == QDialog.Accepted: self.reload() logging.debug(f"Patient {self.patient_form.patient} added") def deleteCurrentPatient(self): if self.table.rowCount() == 0: QMessageBox.warning( self, "Usuwanie pacjenta", "Brak danych w tabeli", ) return current_row = self.table.currentRow() if current_row == -1: QMessageBox.warning( self, "Usuwanie pacjenta", "Brak wskazania na pacjenta", ) return patient = self.data[current_row] answer = QMessageBox.question( self, "Usuwanie pacjenta", f"Czy na pewno chcesz usunąć pacjenta {patient}?", ) if answer == QMessageBox.Yes: delete_patient(patient) self.reload() logging.debug("Deleting PatientForm") def reload(self): self.table.setRowCount(0) self.data = get_all_patients() self.fillTable()
class PlotPieWindow(QMainWindow): def __init__(self, title, labels=[], data=[], table_name="", field_name="", random_colors=False, has_explode=True, parent=None): super().__init__(parent) self._main_widget = QWidget(self) self._layout = QVBoxLayout(self._main_widget) self._title = title self._data = data self._df_data = {k:v for (k,v) in zip(labels, data)} self.setWindowTitle(title) # Pie chart, where the slices will be ordered and plotted counter-clockwise: self._labels = labels self._sizes = data self._legend_labels = [label+" - "+"{:.1f}".format(value)+"%" for label, value in zip(self._labels, self._sizes)] self._last_column = excelColumnFromNumber(len(self._labels)) self._plot_location = excelColumnFromNumber(len(self._data)+2) explode = [0 for value in data] explode[1] = 0.1 explode = tuple(explode) self._figure = plt.figure(figsize=(5, 4), dpi=100, facecolor=(1,1,1), edgecolor=(0,0,0)) self.ax = self._figure.add_subplot() self._canvas = FigureCanvas(self._figure) colors = ['yellowgreen', 'lightskyblue'] self._navigation_toolbar = NavigationToolbar(self._canvas, None) self.addToolBar(self._navigation_toolbar) if random_colors: if has_explode: self.ax.pie(self._sizes, explode=explode, autopct = "%1.1f%%", shadow=True, startangle=int(90)) else: self.ax.pie(self._sizes, autopct = "%1.1f%%", shadow=True, startangle=int(90)) else: if has_explode: self.ax.pie(self._sizes, explode=explode, colors=colors, autopct = "%1.1f%%", shadow=True, startangle=int(90)) else: self.ax.pie(self._sizes, colors=colors, autopct = "%1.1f%%", shadow=True, startangle=int(90)) self.ax.legend(labels=self._legend_labels, loc="best") # Equal aspect ratio ensures that pie is drawn as a circle. self.ax.axis("equal") self.ax.set_title(title) self._bottom_toolbar = QToolBar(self) self._bottom_toolbar.setMovable(False) self._bottom_toolbar.setFloatable(False) self._bottom_toolbar.setStyleSheet("QToolBar {border-bottom: None; border-top: 1px solid #BBBBBB;}") self._table_name_label = QLabel(" Table:") self._field_name_label = QLabel(" Field:") self._table_name = FormEntry(self) self._table_name.setMaximumHeight(20) self._field_name = FormEntry(self) self._field_name.setMaximumHeight(20) self._table_name.setReadOnly(True) self._field_name.setReadOnly(True) self._table_name.setText(table_name) self._field_name.setText(field_name) self._bottom_toolbar.addWidget(self._table_name_label) self._bottom_toolbar.addWidget(self._table_name) self._bottom_toolbar.addWidget(self._field_name_label) self._bottom_toolbar.addWidget(self._field_name) self._export_chart_button = QPushButton("Export") self._export_chart_button.setIcon(QIcon(QPixmap("export.png"))) self._export_chart_button.clicked.connect(self.exportChart) self._bottom_toolbar.addWidget(HorizontalFiller(self)) self._bottom_toolbar.addWidget(self._export_chart_button) self.addToolBar(Qt.BottomToolBarArea, self._bottom_toolbar) self.setCentralWidget(self._canvas) def exportChartFileDialog(self): file_dialog = QFileDialog() file_dialog.setNameFilters(["*. xlsx"]) file_name, ext = file_dialog.getSaveFileName(self, 'Export File', "", "Excel (*.xlsx)") if file_name and ext == "Excel (*.xlsx)": return file_name return "" def exportChart(self): file_name = self.exportChartFileDialog() if file_name != "": title = self.ax.title.get_text() df = pd.DataFrame(data=[self._df_data]) writer = pd.ExcelWriter(file_name, engine='xlsxwriter') df.to_excel(writer, sheet_name='Pie_Chart', index=False) workbook = writer.book worksheet = writer.sheets["Pie_Chart"] chart = workbook.add_chart({"type": 'pie'}) chart.set_title({"name": title}) chart.add_series({"categories": "=Pie_Chart!$A$1:${lc}$1".format(lc = self._last_column), "values": "=Pie_Chart!$A$2:${lc}$2".format(lc = self._last_column)}) worksheet.insert_chart(self._plot_location+"2", chart) writer.save() writer.close()
class DBWorkspace(QWidget): def __init__(self, db, table, parent=None): super().__init__(parent) self.main_layout = QVBoxLayout() self.tab_widget = None self.handler = None self.db = db self.table = table self.table_model = None self.create_tab_widget() self.main_table = DBTableView(self.tab_widget) self.main_table.setSelectionMode(QAbstractItemView.SingleSelection) self.main_table.setSelectionBehavior(QAbstractItemView.SelectRows) self.init_table() self.main_table.clicked.connect(self.row_selected) self.package = QVBoxLayout() self.package.addStretch(1) self.toolBar = QToolBar() self.toolBar.setMovable(True) self.up = QAction( QIcon("view/images/toolbar/baseline_expand_less_black_48dp.png"), "Up", self.main_table) self.up.setStatusTip("Move one up") self.up.triggered.connect(self.jump_up) self.down = QAction( QIcon("view/images/toolbar/baseline_expand_more_black_48dp.png"), "Down", self.main_table) self.down.setStatusTip("Move one down") self.down.triggered.connect(self.jump_down) self.first = QAction( QIcon("view/images/toolbar/baseline_first_page_black_48dp.png"), "Jump to first", self.main_table) self.first.setStatusTip("Jump to first") self.first.triggered.connect(self.jump_to_first) self.last = QAction( QIcon("view/images/toolbar/baseline_last_page_black_48dp.png"), "Jump to last", self.main_table) self.last.setStatusTip("Jump to last") self.last.triggered.connect(self.jump_to_last) self.toolBar.addAction(QIcon("view/images/toolbar/list_48px.png"), "Manage Data") self.toolBar.addAction(QIcon("view/images/toolbar/add_new_40px.png"), "Add Data") self.toolBar.addAction(self.first) self.toolBar.addAction(self.up) self.toolBar.addAction(self.down) self.toolBar.addAction(self.last) self.toolBar.addAction( QIcon("view/images/toolbar/close_window_26px.png"), "Close") self.manageData = DBManageData(self.main_table) self.addData = DBAddData(self.main_table) self.stacked_layout = QVBoxLayout() self.label = QLabel() self.label.setText("Work with data, choose state.") self.toolBar.actionTriggered.connect(self.toolbar_actions) self.package.addWidget(self.toolBar) self.package.addLayout(self.stacked_layout) self.package.addWidget(self.main_table) self.main_layout.addLayout(self.package) self.selected_row = 0 self.main_layout.addStretch(2) self.setLayout(self.main_layout) def toolbar_actions(self, action): if action.iconText() == "Manage Data": if self.stacked_layout.indexOf( self.addData) == -1 and self.stacked_layout.indexOf( self.manageData) == -1 and self.stacked_layout.indexOf( self.label) == -1: self.stacked_layout.addWidget(self.manageData) self.manageData.setVisible(True) return if self.stacked_layout.indexOf(self.addData) != -1: self.stacked_layout.removeWidget(self.addData) self.addData.setVisible(False) self.stacked_layout.addWidget(self.manageData) self.manageData.setVisible(True) return if self.stacked_layout.indexOf(self.label) != -1: self.stacked_layout.removeWidget(self.label) self.label.setVisible(False) self.stacked_layout.addWidget(self.manageData) self.manageData.setVisible(True) return return elif action.iconText() == "Add Data": if self.stacked_layout.indexOf( self.addData) == -1 and self.stacked_layout.indexOf( self.manageData) == -1 and self.stacked_layout.indexOf( self.label) == -1: self.stacked_layout.addWidget(self.addData) self.addData.setVisible(True) return if self.stacked_layout.indexOf(self.manageData) != -1: self.stacked_layout.removeWidget(self.manageData) self.manageData.setVisible(False) self.stacked_layout.addWidget(self.addData) self.addData.setVisible(True) return if self.stacked_layout.indexOf(self.label) != -1: self.stacked_layout.removeWidget(self.label) self.label.setVisible(False) self.stacked_layout.addWidget(self.addData) self.addData.setVisible(True) return return elif action.iconText() == "Close": if self.stacked_layout.indexOf( self.addData) == -1 and self.stacked_layout.indexOf( self.manageData) == -1 and self.stacked_layout.indexOf( self.label) == -1: self.stacked_layout.addWidget(self.label) self.label.setVisible(True) return if self.stacked_layout.indexOf(self.addData) != -1: self.stacked_layout.removeWidget(self.addData) self.addData.setVisible(False) self.stacked_layout.addWidget(self.label) self.label.setVisible(True) return if self.stacked_layout.indexOf(self.manageData) != -1: self.stacked_layout.removeWidget(self.manageData) self.manageData.setVisible(False) self.stacked_layout.addWidget(self.label) self.label.setVisible(True) return return def row_selected(self, index): if index.column() == len(self.main_table.model().columns): model = self.main_table.model() selected_data = model.get_element(index) self.selected_row = index.row() def create_tab_widget(self): self.tab_widget = QTabWidget() self.tab_widget.setTabsClosable(True) self.tab_widget.tabCloseRequested.connect(self.delete_tab) def delete_tab(self, index): self.tab_widget.removeTab(index) def init_table(self): self.handler = DBHandler(self.db, self.table, self) self.table_model = DBTableModel(self.handler) self.main_table.setModel(self.table_model) """ Table navigation jumps """ def jump_up(self): if self.selected_row != 0: self.selected_row -= 1 self.main_table.selectRow(self.selected_row) def jump_down(self): if self.selected_row < len(self.main_table.model().displayed_d) - 1: self.selected_row += 1 self.main_table.selectRow(self.selected_row) def jump_to_first(self): self.selected_row = 0 self.main_table.selectRow(self.selected_row) def jump_to_last(self): self.selected_row = len(self.main_table.model().displayed_d) - 1 self.main_table.selectRow(self.selected_row) def sub_up(self): if self.selected_row != 0: self.selected_row -= 1 self.subtable.selectRow(self.selected_row) def sub_down(self): if self.selected_row < len(self.subtable.model().displayed_d) - 1: self.selected_row += 1 self.subtable.selectRow(self.selected_row) def sub_first(self): self.selected_row = 0 self.subtable.selectRow(self.selected_row) def sub_last(self): self.selected_row = len(self.subtable.model().displayed_d) - 1 self.subtable.selectRow(self.selected_row)
class PlotBarWindow(QMainWindow): def __init__(self, title, labels=[], data=[], table_name="", field_name="", x_label=None, y_label=None, parent=None, already_sorted=False): super().__init__(parent) self._title = title self._labels = labels self._data = data self._last_column = excelColumnFromNumber(len(self._data)) self._plot_location = excelColumnFromNumber(len(self._data)+2) self._x_label = x_label self._y_label = y_label self._already_sorted = already_sorted self.setWindowTitle(self._title) self._figure = plt.figure(figsize=(5, 4), dpi=100, facecolor=(1,1,1), edgecolor=(0,0,0)) self.ax = self._figure.add_subplot() self.ax.set_title(self._title) self._canvas = FigureCanvas(self._figure) self._navigation_toolbar = NavigationToolbar(self._canvas, None) self.addToolBar(self._navigation_toolbar) self._bottom_toolbar = QToolBar(self) self._bottom_toolbar.setMovable(False) self._bottom_toolbar.setFloatable(False) self._bottom_toolbar.setStyleSheet("QToolBar {border-bottom: None; border-top: 1px solid #BBBBBB;}") self._table_name_label = QLabel(" Table:") self._field_name_label = QLabel(" Field:") self._table_name = FormEntry(self) self._table_name.setMaximumHeight(20) self._field_name = FormEntry(self) self._field_name.setMaximumHeight(20) self._table_name.setReadOnly(True) self._field_name.setReadOnly(True) self._table_name.setText(table_name) self._field_name.setText(field_name) self._bottom_toolbar.addWidget(self._table_name_label) self._bottom_toolbar.addWidget(self._table_name) self._bottom_toolbar.addWidget(self._field_name_label) self._bottom_toolbar.addWidget(self._field_name) self._export_chart_button = QPushButton("Export") self._export_chart_button.setIcon(QIcon(QPixmap("export.png"))) self._export_chart_button.clicked.connect(self.exportChart) self._bottom_toolbar.addWidget(HorizontalFiller(self)) self._bottom_toolbar.addWidget(self._export_chart_button) self.addToolBar(Qt.BottomToolBarArea, self._bottom_toolbar) self.ax.bar(self._labels, self._data) if self._x_label != None: self.ax.set_xlabel(self._x_label) if self._y_label != None: self.ax.set_ylabel(self._y_label) self.setCentralWidget(self._canvas) def exportChartFileDialog(self): file_dialog = QFileDialog() file_dialog.setNameFilters(["*. xlsx"]) file_name, ext = file_dialog.getSaveFileName(self, 'Export File', "", "Excel (*.xlsx)") if file_name and ext == "Excel (*.xlsx)": return file_name return "" def exportChart(self): file_name = self.exportChartFileDialog() field_name = self._field_name.text() if file_name != "": title = self.ax.title.get_text() last_row = len(self._data)+2 labels = sorted(self._labels) if self._already_sorted: sorted_data = {label:[self._data[i]] for i, label in enumerate(self._labels)} else: data = {label:[self._data[i]] for i, label in enumerate(self._labels)} sorted_data = {label:data[label] for label in labels} df = pd.DataFrame(data=sorted_data) writer = pd.ExcelWriter(file_name, engine='xlsxwriter') df.to_excel(writer, sheet_name=field_name, index=False) workbook = writer.book worksheet = writer.sheets[field_name] chart = workbook.add_chart({"type": 'column'}) chart.set_title({"name": title}) if self._x_label != None: chart.set_x_axis({'name': self._x_label}) if self._y_label != None: chart.set_y_axis({'name': self._y_label}) chart.add_series({"categories": "={fn}!$A$1:${lc}$1".format(lc=self._last_column, fn=field_name), "values": "={fn}!$A$2:${lc}$2".format(lc=self._last_column, fn=field_name), "fill": {'color': '#0000CC'}}) worksheet.insert_chart(self._plot_location+"2", chart) writer.save() writer.close()
class PlotHBarWindow(QMainWindow): def __init__(self, title, labels=[], data=[], table_name="", field_name="", parent=None): super().__init__(parent) self._title = title self._labels = labels self._data = data self._last_column = excelColumnFromNumber(len(self._data)) self._plot_location = excelColumnFromNumber(len(self._data)+2) self.setWindowTitle(self._title) self._figure = plt.figure(figsize=(5, 4), dpi=100, facecolor=(1,1,1), edgecolor=(0,0,0)) self.ax = self._figure.add_subplot() self.ax.set_title(self._title) self._canvas = FigureCanvas(self._figure) self._navigation_toolbar = NavigationToolbar(self._canvas, None) self.addToolBar(self._navigation_toolbar) self._bottom_toolbar = QToolBar(self) self._bottom_toolbar.setMovable(False) self._bottom_toolbar.setFloatable(False) self._bottom_toolbar.setStyleSheet("QToolBar {border-bottom: None; border-top: 1px solid #BBBBBB;}") self._table_name_label = QLabel(" Table:") self._field_name_label = QLabel(" Field:") self._table_name = FormEntry(self) self._table_name.setMaximumHeight(20) self._field_name = FormEntry(self) self._field_name.setMaximumHeight(20) self._table_name.setReadOnly(True) self._field_name.setReadOnly(True) self._table_name.setText(table_name) self._field_name.setText(field_name) self._bottom_toolbar.addWidget(self._table_name_label) self._bottom_toolbar.addWidget(self._table_name) self._bottom_toolbar.addWidget(self._field_name_label) self._bottom_toolbar.addWidget(self._field_name) self._export_chart_button = QPushButton("Export") self._export_chart_button.setIcon(QIcon(QPixmap("export.png"))) self._export_chart_button.clicked.connect(self.exportChart) self._bottom_toolbar.addWidget(HorizontalFiller(self)) self._bottom_toolbar.addWidget(self._export_chart_button) self.addToolBar(Qt.BottomToolBarArea, self._bottom_toolbar) y_pos = np.arange(len(data)) self.ax.barh(y_pos, data, align="center", color='lightskyblue', alpha=0.5) self.ax.set_xlabel(labels[len(labels)-1]) #self.ax.set_ylabel(labels[1]) rects = self.ax.patches low_rect = rects[0] high_rect = rects[len(rects)-1] width = low_rect.get_width() self.ax.text(low_rect.get_x()+width, low_rect.get_y()+1, "Lowest: $"+str(data[0])) width = high_rect.get_width() self.ax.text(high_rect.get_x(), high_rect.get_y()+1, "Highest: $"+str(data[len(data)-1])) self.setCentralWidget(self._canvas) def exportChartFileDialog(self): file_dialog = QFileDialog() file_dialog.setNameFilters(["*. xlsx"]) file_name, ext = file_dialog.getSaveFileName(self, 'Export File', "", "Excel (*.xlsx)") if file_name and ext == "Excel (*.xlsx)": return file_name return "" def exportChart(self): file_name = self.exportChartFileDialog() field_name = self._field_name.text() if file_name != "": title = self.ax.title.get_text() last_row = len(self._data)+2 col_1 = ["" for data in self._data] col_2 = col_1.copy() col_1[0] = self._data[0] col_2[0] = self._data[len(self._data)-1] data = { self._labels[0]: self._data, self._labels[1]: col_1, self._labels[2]: col_2 } df = pd.DataFrame(data=data) writer = pd.ExcelWriter(file_name, engine='xlsxwriter') df.to_excel(writer, sheet_name=field_name, index=False) workbook = writer.book worksheet = writer.sheets[field_name] chart = workbook.add_chart({"type": 'bar'}) chart.set_title({"name": title}) chart.set_x_axis({'name': self._labels[0]}) chart.add_series({"values": "={fn}!$A$2:$A${lr}".format(lr=last_row, fn=field_name), 'fill': {'color': '#0000CC'}, 'border': {'color': '#0000CC'}}) worksheet.insert_chart(self._plot_location+"2", chart) writer.save() writer.close()
class MainUI(QMainWindow): def __init__(self): super().__init__() self.setWindowFlags(Qt.FramelessWindowHint) #self.setAttribute(Qt.WA_TranslucentBackground, True) self.setFixedSize(601, 401) self.toolbar_selected = False self.toolbar = QToolBar() self.toolbar.setObjectName("toolbar") self.toolbar.setMovable(False) self.toolbar.setFloatable(False) self.toolbar.setContextMenuPolicy( Qt.PreventContextMenu) # no right-click on toolbar self.addToolBar(self.toolbar) self.toolbar.setStyleSheet("background-color: khaki") self.admin_btn = QPushButton("Admin", self) self.admin_btn.setObjectName("admin_btn") self.admin_btn.setFixedSize(65, 30) self.info_btn = QPushButton("Info", self) self.info_btn.setObjectName("info_btn") self.info_btn.setFixedSize(35, 30) self.spacer = QWidget() self.spacer.setObjectName("toolbar_spacer") self.spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self.toolbar_label = QLabel("") self.toolbar_label.setObjectName("toolbar_label") self.toolbar_label.setAlignment(Qt.AlignCenter) self.toolbar_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self.close_btn = QPushButton(" X") self.close_btn.setObjectName("close_btn") self.close_btn.setFixedSize(30, 30) self.toolbar.addWidget(self.admin_btn) # self.toolbar.addWidget(self.spacer) self.toolbar.addWidget(self.toolbar_label) # self.toolbar.addWidget(self.spacer) self.toolbar.addWidget(self.info_btn) self.toolbar.addWidget(self.close_btn) self.toolbar_label.mousePressEvent = self.mousePressEvent # to move window self.mousePressEvent = self.mousePressEvent_ # to check if window content is selected or not self.close_btn.pressed.connect(self.close_window) def mousePressEvent_(self, e): """ to be able to drag window just via toolbar I made this custome mousePressEvent to filter any click, other than toolbar. If we click on any place on the window(except the toolbar), this method will be activated and set the toolbar_selected=false, so that we won't be able do anything in normal mousePressEvent """ self.toolbar_selected = False def mousePressEvent(self, e): self.toolbar_selected = True """ If defiend section is pressed Activate the mouseMoveEvent to get the mouse positions """ self.mouse_pressed = True self.old_pos = e.globalPos() def mouseMoveEvent(self, e): """ move the whole window to mouse position """ if self.toolbar_selected: delta = QPoint(e.globalPos() - self.old_pos) self.move(self.x() + delta.x(), self.y() + delta.y()) self.old_pos = e.globalPos() def close_window(self): self.close()
class MainWindow(QMainWindow): """ Main application window :version: :author: pir """ #-------------------------------------------------------------------------- def __init__(self): super().__init__() self.setWindowTitle("Organiser") self.mainLayout = QVBoxLayout() # Create menu bar & menus self.fileMenu = self.menuBar().addMenu("&File") self.openMenuAction = self.fileMenu.addAction("&Open") self.openMenuAction.triggered.connect( self.on_open_action) # New-style connect! self.fileMenu.addSeparator() self.setPreferencesMenuAction = self.fileMenu.addAction( "Set Preferences") self.setPreferencesMenuAction.triggered.connect( self.on_set_preferences_action) self.fileMenu.addSeparator() self.quitMenuAction = self.fileMenu.addAction("&Quit") self.quitMenuAction.triggered.connect(self.on_quit_action) # Create main toolbar self.mainToolBar = QToolBar() self.mainToolBar.setMovable(False) self.addItemToolButton = self.mainToolBar.addAction( QIcon("./mainToolbarIcons/Gnome-item-add.svg"), "Add new item" ) # Icons from https://commons.wikimedia.org/wiki/GNOME_Desktop_icons self.addItemToolButton.triggered.connect(self.on_insert_item_action) self.addChildItemToolButton = self.mainToolBar.addAction( QIcon("./mainToolbarIcons/Gnome-item-add-child.svg"), "Add child item") self.addChildItemToolButton.triggered.connect( self.on_insert_child_item_action) self.mainLayout.addWidget(self.mainToolBar) # Configure window splitter self.splitter = QSplitter() self.splitter.setHandleWidth(2) # Configure item tree widget self.itemTree = ItemTree() self.splitter.addWidget(self.itemTree) self.splitter.addWidget(self.itemTree.editBox) self.mainLayout.addWidget(self.splitter) # Is a status bar needed in this application? #self.statusBar = QStatusBar() #self.mainLayout.addWidget(self.statusBar) # Set layout as the central widget self.mainWidget = QWidget() self.mainWidget.setLayout(self.mainLayout) self.setCentralWidget(self.mainWidget) # TEST ONLY self.uniqueCounter = 0 return #-------------------------------------------------------------------------- def on_insert_item_action(self): """Handler for 'add item' action""" # test code title = str(self.uniqueCounter) self.uniqueCounter += 1 # test code # TODO Get parameters of new task iconIndex = 0 #title = "" deadline = 0 self.itemTree.insert_task_item(iconIndex, title, deadline, True, False) print("adding an item") return #-------------------------------------------------------------------------- def on_insert_child_item_action(self): """Handler for 'add child item' action""" # Test code title = str(self.uniqueCounter) self.uniqueCounter += 1 # TODO Get parameters of new task iconIndex = 0 #title = "" deadline = 0 self.itemTree.insert_task_item(iconIndex, title, deadline, True, True) print("add a child item") return #-------------------------------------------------------------------------- def on_open_action(self): """Handler for 'open' action""" print("open file item") return #-------------------------------------------------------------------------- def on_set_preferences_action(self): """Handler for 'set preferences' action""" self.itemTree.set_item_tree_preferences() return #-------------------------------------------------------------------------- def on_quit_action(self): """Handler for 'quit' action""" print("quitting application") self.close() return
class SubtableWidget(QWidget): def __init__(self, subtable, parent=None): super().__init__(parent) self.subtable = subtable self.subtable.setSelectionMode(QAbstractItemView.SingleSelection) self.subtable.setSelectionBehavior(QAbstractItemView.SelectRows) self.subtable.clicked.connect(self.row_selected) self.selected_row = 0 self.package = QVBoxLayout() self.toolBar = QToolBar() self.toolBar.setMovable(True) sub_up = QAction( QIcon("view/images/toolbar/baseline_expand_less_black_48dp.png"), "Up", self.subtable) sub_up.setStatusTip("Move one up") sub_up.triggered.connect(self.sub_up) sub_down = QAction( QIcon("view/images/toolbar/baseline_expand_more_black_48dp.png"), "Down", self.subtable) sub_down.setStatusTip("Move one down") sub_down.triggered.connect(self.sub_down) sub_first = QAction( QIcon("view/images/toolbar/baseline_first_page_black_48dp.png"), "Jump to first", self.subtable) sub_first.setStatusTip("Jump to first") sub_first.triggered.connect(self.sub_first) sub_last = QAction( QIcon("view/images/toolbar/baseline_last_page_black_48dp.png"), "Jump to last", self.subtable) sub_last.setStatusTip("Jump to last") sub_last.triggered.connect(self.sub_last) self.toolBar.addAction(QIcon("view/images/toolbar/list_48px.png"), "Manage Data") self.toolBar.addAction(QIcon("view/images/toolbar/add_new_40px.png"), "Add Data") self.toolBar.addAction(sub_first) self.toolBar.addAction(sub_up) self.toolBar.addAction(sub_down) self.toolBar.addAction(sub_last) self.toolBar.addAction( QIcon("view/images/toolbar/close_window_26px.png"), "Close") self.manageData2 = ManageData(self.subtable) self.addData2 = AddData(self.subtable) self.label = QLabel() self.label.setText("Work with data, choose state.") self.stacked_layout_2 = QVBoxLayout() self.stacked_layout_2.addStretch(0) self.toolBar.actionTriggered.connect(self.sub_toolbar_actions) self.package.addWidget(self.toolBar) self.package.addLayout(self.stacked_layout_2) self.package.addWidget(self.subtable) self.setLayout(self.package) def sub_toolbar_actions(self, action): if action.iconText() == "Manage Data": if self.stacked_layout_2.indexOf( self.addData2) == -1 and self.stacked_layout_2.indexOf( self.manageData2 ) == -1 and self.stacked_layout_2.indexOf( self.label) == -1: self.stacked_layout_2.addWidget(self.manageData2) self.manageData2.setVisible(True) return if self.stacked_layout_2.indexOf(self.addData2) != -1: self.stacked_layout_2.removeWidget(self.addData2) self.addData2.setVisible(False) self.stacked_layout_2.addWidget(self.manageData2) self.manageData2.setVisible(True) return if self.stacked_layout_2.indexOf(self.label) != -1: self.stacked_layout_2.removeWidget(self.label) self.label.setVisible(False) self.stacked_layout_2.addWidget(self.manageData2) self.manageData2.setVisible(True) return return elif action.iconText() == "Add Data": if self.stacked_layout_2.indexOf( self.addData2) == -1 and self.stacked_layout_2.indexOf( self.manageData2 ) == -1 and self.stacked_layout_2.indexOf( self.label) == -1: self.stacked_layout_2.addWidget(self.addData2) self.addData2.setVisible(True) return if self.stacked_layout_2.indexOf(self.manageData2) != -1: self.stacked_layout_2.removeWidget(self.manageData2) self.manageData2.setVisible(False) self.stacked_layout_2.addWidget(self.addData2) self.addData2.setVisible(True) return if self.stacked_layout_2.indexOf(self.label) != -1: self.stacked_layout_2.removeWidget(self.label) self.label.setVisible(False) self.stacked_layout_2.addWidget(self.addData2) self.addData2.setVisible(True) return return elif action.iconText() == "Close": if self.stacked_layout_2.indexOf( self.addData2) == -1 and self.stacked_layout_2.indexOf( self.manageData2 ) == -1 and self.stacked_layout_2.indexOf( self.label) == -1: self.stacked_layout_2.addWidget(self.label) self.label.setVisible(True) return if self.stacked_layout_2.indexOf(self.addData2) != -1: self.stacked_layout_2.removeWidget(self.addData2) self.addData2.setVisible(False) self.stacked_layout_2.addWidget(self.label) self.label.setVisible(True) return if self.stacked_layout_2.indexOf(self.manageData2) != -1: self.stacked_layout_2.removeWidget(self.manageData2) self.manageData2.setVisible(False) self.stacked_layout_2.addWidget(self.label) self.label.setVisible(True) return return def row_selected(self, index): self.selected_row = index.row() def sub_up(self): if self.selected_row != 0: self.selected_row -= 1 self.subtable.selectRow(self.selected_row) def sub_down(self): if self.selected_row < len(self.subtable.model().displayed_d) - 1: self.selected_row += 1 self.subtable.selectRow(self.selected_row) def sub_first(self): self.selected_row = 0 self.subtable.selectRow(self.selected_row) def sub_last(self): self.selected_row = len(self.subtable.model().displayed_d) - 1 self.subtable.selectRow(self.selected_row)