def getDateRangeWidget(self, minDate, maxDate): dateRange = QDateEdit() dateRange.setCalendarPopup(True) dateRange.setDisplayFormat('MMM d yy') dateRange.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) dateRange.setMaximumDate(maxDate) dateRange.setMinimumDate(minDate) return dateRange
class ExchangeSpiderUI(QWidget): """ 数据抓取主页面 """ def __init__(self, *args, **kwargs): super(ExchangeSpiderUI, self).__init__(*args, **kwargs) layout = QVBoxLayout() layout.setContentsMargins(QMargins(2, 0, 2, 1)) main_splitter = QSplitter(self) main_splitter.setHandleWidth(1) self.tree_widget = ExchangeLibTree(self) main_splitter.addWidget(self.tree_widget) action_splitter = QSplitter(Qt.Vertical, self) action_splitter.setHandleWidth(1) spider_widget = QWidget(self) spider_widget.setAutoFillBackground(True) palette = QPalette() pix = QPixmap("images/spider_bg.png") pix = pix.scaled(QSize(700, 700), Qt.KeepAspectRatio) palette.setBrush(QPalette.Background, QBrush(pix)) spider_widget.setPalette(palette) spider_layout = QVBoxLayout() tips_layout = QHBoxLayout() tips_layout.setSpacing(1) tips_layout.addWidget(QLabel("当前交易所:", self)) self.spider_exchange_button = QPushButton("未选择", self) tips_layout.addWidget(self.spider_exchange_button) tips_layout.addWidget(QLabel(self)) tips_layout.addWidget(QLabel("当前操作:", self)) self.spider_action_button = QPushButton("未选择", self) tips_layout.addWidget(self.spider_action_button) tips_layout.addWidget(QLabel(self)) tips_layout.addWidget(QLabel("选择日期:", self)) self.spider_date_edit = QDateEdit(QDate.currentDate(), self) self.spider_date_edit.setCalendarPopup(True) self.spider_date_edit.setDisplayFormat("yyyy-MM-dd") tips_layout.addWidget(self.spider_date_edit) tips_layout.addWidget(QLabel(self)) self.spider_start_button = QPushButton("开始", self) tips_layout.addWidget(self.spider_start_button) tips_layout.addStretch() spider_layout.addLayout(tips_layout) self.spider_status = QLabel("等待开始抓取", self) self.spider_status.setWordWrap(True) self.spider_status.setAlignment(Qt.AlignCenter) spider_layout.addWidget(self.spider_status) spider_widget.setLayout(spider_layout) action_splitter.addWidget(spider_widget) # 解析部分 parser_widget = QWidget(self) parser_widget.setAutoFillBackground(True) palette = QPalette() pix = QPixmap("images/parser_bg.png") pix = pix.scaled(QSize(700, 700), Qt.KeepAspectRatio) palette.setBrush(QPalette.Background, QBrush(pix)) parser_widget.setPalette(palette) parser_layout = QVBoxLayout() tips_layout = QHBoxLayout() tips_layout.setSpacing(1) tips_layout.addWidget(QLabel("当前交易所:", self)) self.parser_exchange_button = QPushButton("未选择", self) tips_layout.addWidget(self.parser_exchange_button) tips_layout.addWidget(QLabel(self)) tips_layout.addWidget(QLabel("当前操作:", self)) self.parser_action_button = QPushButton("未选择", self) tips_layout.addWidget(self.parser_action_button) tips_layout.addWidget(QLabel(self)) tips_layout.addWidget(QLabel("选择日期:", self)) self.parser_date_edit = QDateEdit(QDate.currentDate(), self) self.parser_date_edit.setCalendarPopup(True) self.parser_date_edit.setDisplayFormat("yyyy-MM-dd") tips_layout.addWidget(self.parser_date_edit) tips_layout.addWidget(QLabel(self)) self.parser_start_button = QPushButton("开始", self) tips_layout.addWidget(self.parser_start_button) tips_layout.addStretch() parser_layout.addLayout(tips_layout) self.parser_status = QLabel("等待开始解析", self) self.parser_status.setAlignment(Qt.AlignCenter) parser_layout.addWidget(self.parser_status) parser_widget.setLayout(parser_layout) action_splitter.addWidget(parser_widget) main_splitter.addWidget(action_splitter) main_splitter.setStretchFactor(0, 4) main_splitter.setStretchFactor(1, 6) layout.addWidget(main_splitter) self.setLayout(layout) main_splitter.setObjectName("mainSplitter") action_splitter.setObjectName("actionSplitter") self.spider_exchange_button.setObjectName("tipButton") self.spider_action_button.setObjectName("tipButton") self.spider_status.setObjectName("spiderStatus") self.parser_exchange_button.setObjectName("tipButton") self.parser_action_button.setObjectName("tipButton") self.parser_status.setObjectName("parserStatus") self.setStyleSheet( "#mainSplitter::handle{background-color:rgba(50,50,50,100)}" "#actionSplitter::handle{background-color:rgba(50,50,50,100)}" "#tipButton{border:none;color:rgb(220,100,100)}" "#spiderStatus,#parserStatus{font-size:16px;font-weight:bold;color:rgb(230,50,50)}" )
def __init__(self, db_session, **kwargs): super(MainPage, self).__init__() self.db_session = db_session # Create central widget that will contain everything # (Bit odd design decision from QT, I would say, to separate widgets and # layouts. Now we need to have central _widget_ to contain layout to contain # widgets) central_widget = QWidget() central_widget.setStyleSheet("background: white;") # Add central widget to main window # Create main grid layout that will organize everything main_grid = qt.QGridLayout(central_widget) self.setLayout(main_grid) main_grid.setSpacing(0) main_grid.setMargin(0) # Yet again interesting design decision. On QT you cannot set style for layout. # Thus, we create widget that will contain layout and now we can set style for the widget. widget_that_would_not_be_needed_if_qt_would_not_be_so_stupid = QWidget( ) widget_that_would_not_be_needed_if_qt_would_not_be_so_stupid.setStyleSheet( ''' QObject { background: #FF005AA1; } QPushButton { background: #FF005AA1; color: white; text-align: center; border: none; font-weight: 500; font-size: 15px; height: 48px; width: 120px; } QPushButton:hover { background-color: #FF014a82; } QPushButton:checked { background: #FF01508c; } QPushButton:pressed { color: #FF005AA1; background: white; } QWidget{ background: #FF005AA1; } ''') # On left side we will have some (or at least one) button left_side_buttons = QVBoxLayout( widget_that_would_not_be_needed_if_qt_would_not_be_so_stupid) left_side_buttons.setSpacing(0) left_side_buttons.setMargin(0) # And add it to main box the left most cell main_grid.addWidget( widget_that_would_not_be_needed_if_qt_would_not_be_so_stupid, 0, 0) main_grid.setRowStretch(0, 1) # Column 0 must not stretch main_grid.setColumnStretch(0, 0) # Column 1 must stretch main_grid.setColumnStretch(1, 1) # Separator line line = qt.QFrame() line.setFrameShape(qt.QFrame.HLine) line.setFrameShadow(qt.QFrame.Sunken) # Add scan button self.scan_button = qt.QPushButton("Luo laskut") self.scan_button.clicked.connect(self.luo_lasku_pressed_handler) # Add widgets to container left_side_buttons.addWidget(self.scan_button) # Add separator line line = qt.QFrame() line.setFrameShape(qt.QFrame.HLine) line.setFrameShadow(qt.QFrame.Sunken) left_side_buttons.addWidget(line) # Add stretch that will stretch to fill rest of the space left_side_buttons.addStretch() self.list_of_visits = qt.QTreeWidget() self.list_of_visits.setColumnCount(3) self.list_of_visits.setHeaderLabels( ["Käyntipäivä", "Nimi", "Terapian laji", "Lisätiedot"]) self.list_of_visits.setSortingEnabled(True) # Allow multiselect self.list_of_visits.setSelectionMode( qt.QAbstractItemView.ExtendedSelection) third_stupid_widget = QWidget() right_side_layout = qt.QVBoxLayout(third_stupid_widget) main_grid.addWidget(third_stupid_widget, 0, 1) new_visit_date = QDateEdit(datetime.datetime.now()) new_visit_date.setCalendarPopup(True) new_visit_date.setDisplayFormat('dd.MM.yyyy') self.new_visit_customers_combobox = QComboBox() new_visit_type = QLineEdit() new_visit_type.setText("Terapia") self.update_page() self.new_visit_button = qt.QPushButton("Lisää käynti") second_stupid_widget = QWidget() new_visit_layout = QHBoxLayout(second_stupid_widget) right_side_layout.addWidget(second_stupid_widget) new_visit_layout.addWidget(new_visit_date) new_visit_layout.addWidget(self.new_visit_customers_combobox) new_visit_layout.addWidget(new_visit_type) new_visit_layout.addWidget(self.new_visit_button) right_side_layout.addWidget(self.list_of_visits) # Add properties view # main_grid.addWidget(qt.QPlainTextEdit(), 0, 2) def new_visit_handler(): for _customer in self.customers: if _customer.name == self.new_visit_customers_combobox.currentText( ): _customer.new_visit( cost=_customer.hour_price, visit_length_min=45, visit_date=new_visit_date.date().toPython(), visit_type=new_visit_type.text(), ) self.update_page() db_session.commit() self.new_visit_button.clicked.connect(new_visit_handler) # create context menu self.popMenu = qt.QMenu(self) self.popMenu.addAction( qt.QAction('Poista käynti', self.list_of_visits, triggered=self._delete_visit)) # set button context menu policy self.list_of_visits.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.list_of_visits.customContextMenuRequested.connect( self.on_context_menu)
class AcquistoForm(QDialog): ''' Widget per l'inserimento di un acquisto immediato. ''' def __init__(self, conn): ''' Parameters: conn : connection Connection to the database. ''' super().__init__() self.setWindowTitle('Aggiungi Acquisto') self.setWindowFlag(QtCore.Qt.WindowContextHelpButtonHint, False) self.conn = conn self.cursor = conn.cursor() self.books = dict() self.books_qt = dict() self.gen_layout = QVBoxLayout() self.form_layout = QFormLayout() self.form_layout.setRowWrapPolicy(QFormLayout.WrapLongRows) # Widgets self.client_field = QLineEdit() self.form_layout.addRow('Numero Cliente (facoltativo): ', self.client_field) self.dip_field = QLineEdit() self.form_layout.addRow('Dipendente (CF): ', self.dip_field) self.date_picker = QDateEdit(QDate.currentDate()) self.date_picker.setDisplayFormat("MM/dd/yyyy") self.date_picker.setCalendarPopup(True) self.form_layout.addRow('Data (mm/gg/aaaa): ', self.date_picker) self.importo_field = QDoubleSpinBox() self.importo_field.setMaximum(999999999.99) self.form_layout.addRow('Importo: ', self.importo_field) self.ins_layout = QHBoxLayout() self.libro_field = QLineEdit() self.quantita_field = QSpinBox() self.quantita_field.setMinimum(1) self.libro_button = QPushButton('Aggiungi') self.libro_button.clicked.connect(self.aggiungi_libro) self.ins_layout.addWidget(QLabel('Libro (ISBN): ')) self.ins_layout.addWidget(self.libro_field) self.ins_layout.addWidget(QLabel('Quantità: ')) self.ins_layout.addWidget(self.quantita_field) self.ins_layout.addWidget(self.libro_button) self.labels = ['ISBN', 'Quantità', ''] self.table = QTableWidget(0, 3) self.table.setHorizontalHeaderLabels(self.labels) self.table.horizontalHeader().setSectionResizeMode( 0, QHeaderView.Stretch) self.table.horizontalHeader().setSectionResizeMode( 1, QHeaderView.Stretch) self.table.horizontalHeader().setSectionResizeMode( 2, QHeaderView.ResizeToContents) self.confirm_button = QPushButton('Conferma') self.confirm_button.clicked.connect(self.post_acquisto) self.gen_layout.addLayout(self.form_layout) self.gen_layout.addLayout(self.ins_layout) self.gen_layout.addWidget(self.table) self.gen_layout.addWidget(self.confirm_button) self.setLayout(self.gen_layout) def aggiungi_libro(self): self.books[self.libro_field.text()] = self.quantita_field.value() self.update_table() def remove_libro(self, book): self.books.pop(book, None) self.update_table() def update_table(self): self.table.clearContents() while self.table.rowCount() > 0: self.table.removeRow(0) for book in self.books.keys(): row = self.table.rowCount() button = QPushButton('Rimuovi') button.clicked.connect(lambda: self.remove_libro(book)) self.table.insertRow(row) self.table.setItem(row, 0, QTableWidgetItem(book)) self.table.setItem(row, 1, QTableWidgetItem(str(self.books[book]))) self.table.setCellWidget(row, 2, button) def verif_qty(self): ''' Shows error messages based on the validity of inserted books, and returns False, or returns True if all the books are ok to sell right now. ''' if len(self.books.items()) == 0: self._show_error('Non ci sono libri nell\'acquisto') return 1 for book, qty in self.books.items(): self.cursor.execute(FIND_QUANTITA, (book, )) result = self.cursor.fetchall() if not result: self._show_error('\'{}\' non è un libro valido.'.format(book)) return 2 stored = result[0][0] if stored < qty: return self.__show_are_you_sure( 'L\'acquisto richiede {} libri {}, ma ne sono presenti solo {}.\nNon sarà possibile sottrarre i libri acquistati.\nVuoi proseguire ugualmente?' .format(qty, book, stored)) return 0 def verif_client_dip(self): ''' Returns false and displays and error message if cliente and dipendente are not valid tuples in the database, returns true if they are ok ''' cliente = self.client_field.text() if cliente: if not cliente.isdigit(): self._show_error('Il codice del Cliente deve essere numerico.') return 1 self.cursor.execute(FIND_CLIENTE, (cliente, )) result = self.cursor.fetchall() if not result or not result[0][0]: self._show_error('Cliente {} non esiste.'.format(cliente)) return 2 dipendente = self.dip_field.text() if not dipendente: self._show_error('Il Dipendente non può essere vuoto.') return 3 self.cursor.execute(FIND_DIPENDENTE, (dipendente, )) result = self.cursor.fetchall() if not result or not result[0][0]: self._show_error('Dipendente {} non esiste.'.format(dipendente)) return 4 return 0 def post_acquisto(self): if self.verif_client_dip(): return should_show = self.verif_qty() if should_show > 0: return cliente = self.client_field.text().strip() if self.client_field.text( ).strip() else None importo = self.importo_field.value() self.cursor.execute( INSERT_ACQUISTO, (self.date_picker.date().toString('MM/dd/yyyy'), self.importo_field.value(), self.dip_field.text())) new_id = self.cursor.fetchall()[0][0] self.cursor.execute(INSERT_IMMEDIATO, (new_id, cliente)) for book in self.books.keys(): self.cursor.execute(INSERT_COMPRENDE, (new_id, book, self.books[book])) self.conn.commit() if should_show == 0: self._show_confirm() self.accept() def __show_are_you_sure(self, msg=''): dialog = _AreYouSureDialog(msg) dialog.setWindowTitle('ATTENZIONE') result = dialog.exec_() return -1 if result == QDialog.Accepted else 3 def _show_confirm(self): dialog = _ScalaAcquistiDialog(self.books, self.conn) dialog.setWindowTitle('Rimozione libri') dialog.exec_() def _show_error(self, msg=''): dialog = QMessageBox() dialog.setWindowTitle('ERRORE') dialog.setText(msg) dialog.exec_()
class Window(QWidget): go_list = [] unit = None def __init__(self): super(Window, self).__init__() self.createCalendarBox() self.setup_database_dialog() self.database_utilities() self.ready_plots() layout = QGridLayout() layout.addWidget(self.db_dialog_groupbox, 0, 0) layout.addWidget(self.previewGroupBox, 0, 1) layout.addWidget(self.db_util_groupbox, 1, 0) layout.addWidget(self.ready_plt_groupbox, 1, 1) layout.setSizeConstraint(QLayout.SetFixedSize) self.setLayout(layout) self.previewLayout.setRowMinimumHeight(0, self.calendar.sizeHint().height()) self.previewLayout.setColumnMinimumWidth(0, self.calendar.sizeHint().width()) self.setWindowTitle("Data Visualization Application") def createCalendarBox(self): self.previewGroupBox = QGroupBox("Custom Plot") # db_entry_layout self.db_entry_layout = QHBoxLayout() self.db_entry_field = QLineEdit("tasos.db") self.db_entry_label = QLabel("Set Sensor") self.db_entry_set_button = QPushButton("Set") # Create available db QComboBox self.avail_db_combo = QComboBox() self.avail_db_combo.addItems(self.available_db_combo()) self.avail_db_combo_reload = QPushButton("Reload") # Create QHBoxLayout for avail_db_combo self.avail_db_combo_layout = QHBoxLayout() # Adds widgets to db_entry_ayout QHBoxLayout self.db_entry_layout.addWidget(self.db_entry_label) self.db_entry_layout.addWidget(self.avail_db_combo) self.db_entry_layout.addWidget(self.avail_db_combo_reload) self.db_entry_layout.addWidget(self.db_entry_set_button) self.db_entry_set_button.clicked.connect(self.set_db_entry_button_script) # Calendar Widget self.calendar = QCalendarWidget() self.calendar.setGridVisible(True) # Create main layout self.previewLayout = QGridLayout() # Creating sub layouts and adding their widgets self.cal_options = QGridLayout() self.chart_label = QLabel("&Chart") self.calendar_chart_field = QComboBox() self.calendar_chart_field.addItem("Lines") self.calendar_chart_field.addItem("Lines and Markers") self.calendar_chart_field.addItem("Scatter") self.calendar_chart_field.addItem("Bars") self.chart_label.setBuddy(self.calendar_chart_field) # Mode Layout self.h_mode_layout = QHBoxLayout() self.h_mode_layout.addWidget(self.chart_label) self.h_mode_layout.addWidget(self.calendar_chart_field) self.from_to_dates_layout = QVBoxLayout() # From Layout self.from_date_layout = QHBoxLayout() self.from_date_label = QLabel("From") self.from_date = QDateEdit() self.update_from_date = QPushButton("Set Date") self.from_date.setDisplayFormat('MMM d yyyy') self.from_date.setDate(self.calendar.selectedDate()) self.update_from_date.clicked.connect(self.from_selectedDateChanged) # Adds widgets to from_date_layout QHBoxLayout self.from_date_layout.addWidget(self.from_date) self.from_date_layout.addWidget(self.update_from_date) # To layout self.to_date_layout = QHBoxLayout() self.to_date_label = QLabel("To") self.to_date = QDateEdit() self.update_to_date = QPushButton("Set Date") self.to_date.setDisplayFormat('MMM d yyyy') self.to_date.setDate(self.calendar.selectedDate()) self.update_to_date.clicked.connect(self.to_selectedDateChanged) # Multiple graphic objects layout self.multi_go_label = QLabel("Plot multiple graph objects") self.multi_go_layout = QHBoxLayout() self.multi_go_add_button = QPushButton("Add Graph Object") self.multi_go_clear_button = QPushButton("Clear Graph Objects") self.multi_go_plot_button = QPushButton("Plot Graph Objects") # Adds widges to multi_go_layout self.multi_go_layout.addWidget(self.multi_go_add_button) self.multi_go_layout.addWidget(self.multi_go_clear_button) # Adds widgets to to_date_layout QHBoxLayout self.to_date_layout.addWidget(self.to_date) self.to_date_layout.addWidget(self.update_to_date) # Add widgets and QHBoxLayout to our QVBoxLayout self.from_to_dates_layout.addWidget(self.from_date_label) self.from_to_dates_layout.addLayout(self.from_date_layout) self.from_to_dates_layout.addWidget(self.to_date_label) self.from_to_dates_layout.addLayout(self.to_date_layout) self.custom_plot_button = QPushButton("Custom Plot") # self.available_db_combo() # self.cal_options.addLayout(self.avail_db_combo_layout, 0, 0) self.cal_options.addLayout(self.db_entry_layout, 0, 0) self.cal_options.addLayout(self.h_mode_layout, 1, 0) self.cal_options.addLayout(self.from_to_dates_layout, 2, 0) self.cal_options.addWidget(self.custom_plot_button, 3, 0) self.multi_qvbox_layout = QVBoxLayout() self.multi_qvbox_layout.addWidget(self.multi_go_label) self.multi_qvbox_layout.addLayout(self.multi_go_layout) self.multi_qvbox_layout.addWidget(self.multi_go_plot_button) self.avail_db_combo_reload.clicked.connect(self.reload_db_combo) self.custom_plot_button.clicked.connect(self.custom_plot_script) # Connect multi_go buttons self.multi_go_add_button.clicked.connect(self.add_go_script) self.multi_go_clear_button.clicked.connect(self.clear_go_script) self.multi_go_plot_button.clicked.connect(self.multi_go_plot_script) # Create QVBoxLayout that contains a QHBoxLayout with min,max,avg,count,sum self.stats_label = QLabel("Get Stats from The Selected Sensor and Dates") self.max = QPushButton("Get Max") self.min = QPushButton("Get Min") self.avg = QPushButton("Get Average") self.count = QPushButton("Get Count Of Measurements") self.sum = QPushButton("Get Total Sum") self.avg_to_max = QPushButton("Get Count Between Avg-Max") self.stats_first_qhbox_layout = QHBoxLayout() self.stats_first_qhbox_layout.addWidget(self.min) self.stats_first_qhbox_layout.addWidget(self.max) self.stats_first_qhbox_layout.addWidget(self.avg) self.stats_second_qhbox_layout = QHBoxLayout() self.stats_second_qhbox_layout.addWidget(self.count) self.stats_second_qhbox_layout.addWidget(self.sum) self.stats_second_qhbox_layout.addWidget(self.avg_to_max) self.stats_qvbox_layout = QVBoxLayout() self.stats_qvbox_layout.addWidget(self.stats_label) self.stats_qvbox_layout.addLayout(self.stats_first_qhbox_layout) self.stats_qvbox_layout.addLayout(self.stats_second_qhbox_layout) # Connect stats buttons when clicked self.min.clicked.connect(self.get_min_script) self.max.clicked.connect(self.get_max_script) self.avg.clicked.connect(self.get_avg_script) self.count.clicked.connect(self.get_count_script) self.sum.clicked.connect(self.get_sum_script) self.avg_to_max.clicked.connect(self.get_avg_to_max_count_script) # Add widgets and sub layout to main layout self.previewLayout.addWidget(self.calendar, 0, 0, Qt.AlignTop) # , Qt.AlignCenter self.previewLayout.addLayout(self.cal_options, 0, 1) self.previewLayout.addLayout(self.stats_qvbox_layout, 1, 0) self.previewLayout.addLayout(self.multi_qvbox_layout, 1, 1) self.previewGroupBox.setLayout(self.previewLayout) def get_avg_to_max_count_script(self): avgToMax_from_date = str(self.from_date.date().toPython()) avgToMax_to_date = str(self.to_date.date().toPython()) avgToMax_error = "Something went wrong while retrieving the percentage" avgToMax_db = self.avail_db_combo.currentText() + ".db" avgToMax_extr = Extractor(avgToMax_db) try: total_count = avgToMax_extr.get_count(avgToMax_from_date, avgToMax_to_date) avgToMax_avg = avgToMax_extr.get_avg(avgToMax_from_date, avgToMax_to_date) avgToMax_max = avgToMax_extr.get_max(avgToMax_from_date, avgToMax_to_date) atm_avg = avgToMax_avg[0][0] atm_max = avgToMax_max[0][0] avgToMax_count = avgToMax_extr.get_avg_to_max_count( str(atm_avg), str(atm_max), avgToMax_from_date, avgToMax_to_date) avgToMax_percentage = (avgToMax_count[0][0]/total_count[0][0]) print(avgToMax_count[0][0], total_count[0][0]) avgToMax_success = True except Exception as ex: avgToMax_success = False avgToMax_error = ex avgToMax_msg = QMessageBox() if avgToMax_success: avgToMax_msg.setIcon(QMessageBox.Information) avgToMax_msg.setText( "Percentage of values between average and max for the selected sensor and dates") avgToMax_msg.setInformativeText( "Avg to Max percentage: {0} %".format(avgToMax_percentage*100)) avgToMax_msg.setWindowTitle("Avg to Max percentage") copy_avgToMax_to_clip = avgToMax_msg.addButton( self.tr("Copy to clipboard"), QMessageBox.AcceptRole) avgToMax_msg.setStandardButtons(QMessageBox.Close) avgToMax_msg.setDefaultButton(copy_avgToMax_to_clip) else: avgToMax_msg.setIcon(QMessageBox.Critical) avgToMax_msg.setText("Getting Avg to Max Percentage Failed!") avgToMax_msg.setInformativeText( "Getting Avg to Max percentage from {0} failed!".format(self.avail_db_combo.currentText())) avgToMax_msg.setWindowTitle("ERROR!") avgToMax_msg.setDetailedText("ERROR:\n {0}".format(avgToMax_error)) avgToMax_msg.setStandardButtons(QMessageBox.Abort) avgToMax_retval = avgToMax_msg.exec_() copy_avgToMax_to_clip.clicked.connect(self.copy_to_clipboard(avgToMax_percentage)) avgToMax_msg.show() def get_sum_script(self): sum_from_date = str(self.from_date.date().toPython()) sum_to_date = str(self.to_date.date().toPython()) sum_error = "Something went wrong while retrieving sum" sum_db = self.avail_db_combo.currentText() + ".db" sum_extr = Extractor(sum_db) try: sum_stat = sum_extr.get_sum(sum_from_date, sum_to_date) sum_success = True except Exception as ex: sum_success = False sum_error = ex sum_msg = QMessageBox() if sum_success: sum_msg.setIcon(QMessageBox.Information) sum_msg.setText("Sum value for the selected sensor and dates") sum_msg.setInformativeText( "Sum value: {0}".format(sum_stat[0][0])) sum_msg.setWindowTitle("sum Value") copy_sum_to_clip = sum_msg.addButton( self.tr("Copy to clipboard"), QMessageBox.AcceptRole) sum_msg.setStandardButtons(QMessageBox.Close) sum_msg.setDefaultButton(copy_sum_to_clip) else: sum_msg.setIcon(QMessageBox.Critical) sum_msg.setText("Getting Sum Value Failed!") sum_msg.setInformativeText( "Getting sum value from {0} failed!".format(self.avail_db_combo.currentText())) sum_msg.setWindowTitle("ERROR!") sum_msg.setDetailedText("ERROR:\n {0}".format(sum_error)) sum_msg.setStandardButtons(QMessageBox.Abort) sum_retval = sum_msg.exec_() copy_sum_to_clip.clicked.connect(self.copy_to_clipboard(sum_stat[0][0])) sum_msg.show() def get_count_script(self): count_from_date = str(self.from_date.date().toPython()) count_to_date = str(self.to_date.date().toPython()) count_error = "Something went wrong while retrieving count" count_db = self.avail_db_combo.currentText() + ".db" count_extr = Extractor(count_db) try: count_stat = count_extr.get_count(count_from_date, count_to_date) count_success = True except Exception as ex: count_success = False count_error = ex count_msg = QMessageBox() if count_success: count_msg.setIcon(QMessageBox.Information) count_msg.setText("Count value for the selected sensor and dates") count_msg.setInformativeText( "count value: {0}".format(count_stat[0][0])) count_msg.setWindowTitle("Count Value") copy_count_to_clip = count_msg.addButton( self.tr("Copy to clipboard"), QMessageBox.AcceptRole) count_msg.setStandardButtons(QMessageBox.Close) count_msg.setDefaultButton(copy_count_to_clip) else: count_msg.setIcon(QMessageBox.Critical) count_msg.setText("Getting Count Value Failed!") count_msg.setInformativeText( "Getting count value from {0} failed!".format(self.avail_db_combo.currentText())) count_msg.setWindowTitle("ERROR!") count_msg.setDetailedText("ERROR:\n {0}".format(count_error)) count_msg.setStandardButtons(QMessageBox.Abort) count_retval = count_msg.exec_() copy_count_to_clip.clicked.connect(self.copy_to_clipboard(count_stat[0][0])) count_msg.show() def get_avg_script(self): avg_from_date = str(self.from_date.date().toPython()) avg_to_date = str(self.to_date.date().toPython()) avg_error = "Something went wrong while retrieving avg" avg_db = self.avail_db_combo.currentText() + ".db" avg_extr = Extractor(avg_db) try: avg_stat = avg_extr.get_avg(avg_from_date, avg_to_date) avg_success = True except Exception as ex: avg_success = False avg_error = ex avg_msg = QMessageBox() if avg_success: avg_msg.setIcon(QMessageBox.Information) avg_msg.setText("Avg value for the selected sensor and dates") avg_msg.setInformativeText( "Avg value: {0}".format(avg_stat[0][0])) avg_msg.setWindowTitle("Avg Value") copy_avg_to_clip = avg_msg.addButton( self.tr("Copy to clipboard"), QMessageBox.AcceptRole) avg_msg.setStandardButtons(QMessageBox.Close) avg_msg.setDefaultButton(copy_avg_to_clip) else: avg_msg.setIcon(QMessageBox.Critical) avg_msg.setText("Getting Avg Value Failed!") avg_msg.setInformativeText( "Getting avg value from {0} failed!".format(self.avail_db_combo.currentText())) avg_msg.setWindowTitle("ERROR!") avg_msg.setDetailedText("ERROR:\n {0}".format(avg_error)) avg_msg.setStandardButtons(QMessageBox.Abort) avg_retval = avg_msg.exec_() copy_avg_to_clip.clicked.connect(self.copy_to_clipboard(avg_stat[0][0])) avg_msg.show() def get_max_script(self): max_from_date = str(self.from_date.date().toPython()) max_to_date = str(self.to_date.date().toPython()) max_error = "Something went wrong while retrieving max" max_db = self.avail_db_combo.currentText() + ".db" max_extr = Extractor(max_db) try: max_stat = max_extr.get_max(max_from_date, max_to_date) max_success = True except Exception as ex: max_success = False max_error = ex max_msg = QMessageBox() if max_success: max_msg.setIcon(QMessageBox.Information) max_msg.setText("Max value for the selected sensor and dates") max_msg.setInformativeText( "Max value: {0}".format(max_stat[0][0])) max_msg.setWindowTitle("Max Value") copy_max_to_clip = max_msg.addButton( self.tr("Copy to clipboard"), QMessageBox.AcceptRole) max_msg.setStandardButtons(QMessageBox.Close) max_msg.setDefaultButton(copy_max_to_clip) else: max_msg.setIcon(QMessageBox.Critical) max_msg.setText("Getting Max Value Failed!") max_msg.setInformativeText( "Getting max value from {0} failed!".format(self.avail_db_combo.currentText())) max_msg.setWindowTitle("ERROR!") max_msg.setDetailedText("ERROR:\n {0}".format(max_error)) max_msg.setStandardButtons(QMessageBox.Abort) max_retval = max_msg.exec_() copy_max_to_clip.clicked.connect(self.copy_to_clipboard(max_stat[0][0])) max_msg.show() def get_min_script(self): min_from_date = str(self.from_date.date().toPython()) min_to_date = str(self.to_date.date().toPython()) min_error = "Something went wrong while retrieving min" min_db = self.avail_db_combo.currentText() + ".db" min_extr = Extractor(min_db) try: min_stat = min_extr.get_min(min_from_date, min_to_date) min_success = True except Exception as ex: min_success = False min_error = ex min_msg = QMessageBox() if min_success: min_msg.setIcon(QMessageBox.Information) min_msg.setText("Min value for the selected sensor and dates") min_msg.setInformativeText( "Min value: {0}".format(min_stat[0][0])) min_msg.setWindowTitle("Min Value") copy_min_to_clip = min_msg.addButton( self.tr("Copy to clipboard"), QMessageBox.AcceptRole) min_msg.setStandardButtons(QMessageBox.Close) min_msg.setDefaultButton(copy_min_to_clip) else: min_msg.setIcon(QMessageBox.Critical) min_msg.setText("Getting Min Value Failed!") min_msg.setInformativeText( "Getting min value from {0} failed!".format(self.avail_db_combo.currentText())) min_msg.setWindowTitle("ERROR!") min_msg.setDetailedText("ERROR:\n {0}".format(min_error)) min_msg.setStandardButtons(QMessageBox.Abort) min_retval = min_msg.exec_() copy_min_to_clip.clicked.connect(self.copy_to_clipboard(min_stat[0][0])) min_msg.show() def copy_to_clipboard(self, var): pyperclip.copy(var) def add_go_script(self): current_index_chart = self.calendar_chart_field.currentIndex() if current_index_chart == 0: chart_mode = "lines" elif current_index_chart == 1: chart_mode = "lines+markers" elif current_index_chart == 2: chart_mode = "markers" elif current_index_chart == 3: chart_mode = "Bars" else: cm_error = "Something went wrong" print(cm_error) multi_go_db = self.avail_db_combo.currentText() + ".db" multi_go_extr = Extractor(multi_go_db) multi_go_plt = Plotter() multi_go_lists = [] # converts Qdate object to python date object go_from_date = str(self.from_date.date().toPython()) go_to_date = str(self.to_date.date().toPython()) multi_go_lists = multi_go_extr.custom_select(go_from_date, go_to_date) if chart_mode == "lines" or chart_mode == "lines+markers" or chart_mode == "markers": go_data = multi_go_plt.go_scatter( chart_mode, multi_go_lists[0], multi_go_lists[1], multi_go_db) Window.go_list.append(go_data) if Window.unit is None: Window.unit = multi_go_lists[2][0] elif chart_mode == "Bars": go_data = multi_go_plt.go_bar( chart_mode, multi_go_lists[0], multi_go_lists[1], multi_go_db) Window.go_list.append(go_data) if Window.unit is None: Window.unit = multi_go_lists[2][0] else: print("Something went wrong") def clear_go_script(self): Window.go_list.clear() Window.unit = None def multi_go_plot_script(self): multi_go_plt = Plotter() current_index_chart = self.calendar_chart_field.currentIndex() if current_index_chart == 0: chart_mode = "lines" elif current_index_chart == 1: chart_mode = "lines+markers" elif current_index_chart == 2: chart_mode = "markers" elif current_index_chart == 3: chart_mode = "Bars" else: cm_error = "Something went wrong" print(cm_error) if chart_mode == "lines" or chart_mode == "lines+markers" or chart_mode == "markers": multi_go_plt.go_plot("Multiple Graphs", "TIME", Window.unit, Window.go_list) elif chart_mode == "Bars": multi_go_plt.go_bar_plot("Multiple Graphs", "TIME", Window.unit, Window.go_list) else: print("Something went wrong") Window.go_list.clear() Window.unit = None def custom_plot_script(self): current_index_chart = self.calendar_chart_field.currentIndex() if current_index_chart == 0: chart_mode = "lines" elif current_index_chart == 1: chart_mode = "lines+markers" elif current_index_chart == 2: chart_mode = "markers" elif current_index_chart == 3: chart_mode = "Bars" else: cm_error = "Something went wrong" print(cm_error) custom_db = self.avail_db_combo.currentText() + ".db" custom_extr = Extractor(custom_db) custom_plt = Plotter() custom_plot_lists = [] custom_plot_title = custom_db[:-3] # converts Qdate object to python date object custom_from_date = str(self.from_date.date().toPython()) custom_to_date = str(self.to_date.date().toPython()) custom_plot_lists = custom_extr.custom_select(custom_from_date, custom_to_date) if chart_mode == "lines" or chart_mode == "lines+markers" or chart_mode == "markers": custom_plt.scatter_plot( chart_mode, custom_plot_lists[0], custom_plot_lists[1], custom_plot_title, "TIME", custom_plot_lists[2][0]) elif chart_mode == "Bars": custom_plt.bar_plot(custom_plot_lists[0], custom_plot_lists[1], custom_plot_title, "TIME", custom_plot_lists[2][0]) else: print("Something went wrong") def setup_database_dialog(self): # Create Groupbox self.db_dialog_groupbox = QGroupBox("Sensor Declaration and Data Import") # Create widgets self.db_label = QLabel("Provide a name for the sensor") self.path_label = QLabel("Provide path to search for .xml files") self.db_field = QLineEdit("") self.path_field = QLineEdit(str(os.path.dirname(os.path.realpath(__file__)))) self.button = QPushButton("Get started") # Create layout and add widgets self.db_dialog_layout = QVBoxLayout() self.db_dialog_layout.addWidget(self.db_label) self.db_dialog_layout.addWidget(self.db_field) self.db_dialog_layout.addWidget(self.path_label) self.db_dialog_layout.addWidget(self.path_field) self.db_dialog_layout.addWidget(self.button) # Set dialog layout self.db_dialog_groupbox.setLayout(self.db_dialog_layout) self.db_field.textChanged.connect(self.db_field_changed) self.button.clicked.connect(self.run_script) def run_script(self): error = "Error parsing files or path" db = self.db_field.text() + ".db" db_interaction = DatabaseInteraction(db) # returns object of class DatabaseInteraction path = self.path_field.text() xml_importer = XMLImporter(db_interaction.name, path) try: success = xml_importer.import_xml() except Exception as ex: success = False error = ex msg = QMessageBox() if success: msg.setIcon(QMessageBox.Information) msg.setText("Sensor declaration successful") msg.setInformativeText("The sensor: {0} has been created.".format(self.db_field.text())) msg.setWindowTitle("Sensor declared!") msg.setDetailedText("The details are as follows:\nSensor name: {0} \nPath of .xml " "files: {1}".format(self.db_field.text(), path)) msg.setStandardButtons(QMessageBox.Ok) else: msg.setIcon(QMessageBox.Critical) msg.setText("Sensor declaration failed!") msg.setInformativeText( "Declaration of the sensor: {0} failed!".format(self.db_field.text())) msg.setWindowTitle("Sensor declaration failed!") msg.setDetailedText("ERROR:\n {0}".format(error)) msg.setStandardButtons(QMessageBox.Abort) retval = msg.exec_() msg.show() def database_utilities(self): # Create Groupbox self.db_util_groupbox = QGroupBox("Utilities") # Create Widgets self.db_update_label = QLabel("Select the Sensor you wish to update") self.path_label = QLabel("Xml File Path") self.update_path_field = QLineEdit(str(os.path.dirname(os.path.realpath(__file__)))) self.update_button = QPushButton("Update") self.update_title = QLabel("Update Sensor") # self.db_clear_field = QLineEdit("example.db") self.db_clear_label = QLabel("Select Sensor") self.clear_button = QPushButton("Remove") self.clear_title = QLabel("Remove a sensor") # Create available db QComboBox for update self.update_avail_db_combo = QComboBox() self.update_avail_db_combo.addItems(self.available_db_combo()) self.update_avail_db_combo_reload = QPushButton("Reload") # Create available db QComboBox for clear table self.clear_avail_db_combo = QComboBox() self.clear_avail_db_combo.addItems(self.available_db_combo()) self.clear_avail_db_combo_reload = QPushButton("Reload") # Add Widgets self.db_util_db_update = QHBoxLayout() self.db_util_db_update.addWidget(self.db_update_label) self.db_util_db_update.addWidget(self.update_avail_db_combo) self.db_util_db_update.addWidget(self.update_avail_db_combo_reload) self.db_util_path = QHBoxLayout() self.db_util_path.addWidget(self.path_label) self.db_util_path.addWidget(self.update_path_field) self.db_util_clear = QHBoxLayout() self.db_util_clear.addWidget(self.db_clear_label) self.db_util_clear.addWidget(self.clear_avail_db_combo) self.db_util_clear.addWidget(self.clear_avail_db_combo_reload) self.db_util_vbox_layout = QVBoxLayout() self.db_util_vbox_layout.addWidget(self.update_title) self.db_util_vbox_layout.addLayout(self.db_util_db_update) self.db_util_vbox_layout.addLayout(self.db_util_path) self.db_util_vbox_layout.addWidget(self.update_button) self.db_util_vbox_layout.addWidget(self.clear_title) self.db_util_vbox_layout.addLayout(self.db_util_clear) self.db_util_vbox_layout.addWidget(self.clear_button) # Set dialog layout self.db_util_groupbox.setLayout(self.db_util_vbox_layout) self.update_button.clicked.connect(self.update_script) self.clear_button.clicked.connect(self.clear_table_script) self.update_avail_db_combo_reload.clicked.connect(self.reload_db_combo) self.clear_avail_db_combo_reload.clicked.connect(self.reload_db_combo) def update_script(self): db = self.update_avail_db_combo.currentText() + ".db" database_interaction = DatabaseInteraction(db) path = self.update_path_field.text() xml_importer = XMLImporter(database_interaction.name, path) update_error = "Something went wrong during update" try: success = xml_importer.import_xml() except Exception as ex: success = False update_error = ex update_msg = QMessageBox() if success: update_msg.setIcon(QMessageBox.Information) update_msg.setText("Sensor update successful") update_msg.setInformativeText("The sensor: {0} has been updated.".format(db[:-3])) update_msg.setWindowTitle("Sensor updated!") update_msg.setDetailedText("The details are as follows:\Sensor name: {0} \nPath of .xml " "files: {1}".format(db[:-3], path)) update_msg.setStandardButtons(QMessageBox.Ok) else: update_msg.setIcon(QMessageBox.Critical) update_msg.setText("Sensor update failed!") update_msg.setInformativeText("Update of the sensor: {0} failed!".format(db[:-3])) update_msg.setWindowTitle("Sensor update failed!") update_msg.setDetailedText("ERROR:\n {0}".format(update_error)) update_msg.setStandardButtons(QMessageBox.Abort) update_retval = update_msg.exec_() update_msg.show() def ready_plots(self): # Create Groupbox self.ready_plt_groupbox = QGroupBox("Ready-to-use plots") # Create Widgets self.choose_db_label = QLabel( "Provide the database that contains the data you wish to plot") self.choose_db_field = QLineEdit("") self.chart_label = QLabel("Chart") self.chart_field = QComboBox() self.chart_field.addItem("Lines") self.chart_field.addItem("Lines and Markers") self.chart_field.addItem("Scatter") self.chart_field.addItem("Bars") self.plot_mode_label = QLabel("Choose what time period to plot") self.plot_mode_field = QComboBox() self.plot_mode_field.addItem("Daily") self.plot_mode_field.addItem("Weekly") self.plot_mode_field.addItem("Monthly") self.plot_mode_field.addItem("Yearly") self.plot_button = QPushButton("Plot") # Create available db QComboBox for ready-plots self.ready_plot_avail_db_combo = QComboBox() self.ready_plot_avail_db_combo.addItems(self.available_db_combo()) self.ready_plot_avail_db_combo_reload = QPushButton("Reload") # Add QComboBox and QPushButton to a QHBoxLayout self.ready_plot_qhbox_layout = QHBoxLayout() self.ready_plot_qhbox_layout.addWidget(self.ready_plot_avail_db_combo) self.ready_plot_qhbox_layout.addWidget(self.ready_plot_avail_db_combo_reload) # Add Widgets self.plot_vbox_layout = QVBoxLayout() self.plot_vbox_layout.addWidget(self.choose_db_label) self.plot_vbox_layout.addLayout(self.ready_plot_qhbox_layout) self.plot_vbox_layout.addWidget(self.chart_label) self.plot_vbox_layout.addWidget(self.chart_field) self.plot_vbox_layout.addWidget(self.plot_mode_label) self.plot_vbox_layout.addWidget(self.plot_mode_field) self.plot_vbox_layout.addWidget(self.plot_button) # Set layout to groupbox self.ready_plt_groupbox.setLayout(self.plot_vbox_layout) self.plot_button.clicked.connect(self.ready_plot_script) self.ready_plot_avail_db_combo_reload.clicked.connect(self.reload_db_combo) def db_field_changed(self): self.db_field.setText(self.db_field.text()) def db_clear_field_changed(self): self.db_clear_field.setText(self.db_clear_field.text()) def db_update_field_changed(self): self.db_update_field.setText(self.db_update_field.text()) def from_selectedDateChanged(self): self.from_date.setDate(self.calendar.selectedDate()) def to_selectedDateChanged(self): self.to_date.setDate(self.calendar.selectedDate()) def clear_table_script(self): clear_error = "Something went wrong during clearing sensor" db = self.clear_avail_db_combo.currentText() + ".db" try: # db_int.clear_table() os.remove(db) clear_success = True except Exception as ex: clear_success = False clear_error = ex clear_msg = QMessageBox() if clear_success: clear_msg.setIcon(QMessageBox.Information) clear_msg.setText("Sensor has been removed") clear_msg.setInformativeText( "The {0} sensor have been removed.".format(db[:-3])) clear_msg.setWindowTitle("Sensor has been removed!") clear_msg.setStandardButtons(QMessageBox.Ok) else: clear_msg.setIcon(QMessageBox.Critical) clear_msg.setText("Removing sensor has failed!") clear_msg.setInformativeText("Removing the sensor: {0} has failed!".format(db[:-3])) clear_msg.setWindowTitle("Removing this sensor has failed!") clear_msg.setDetailedText("ERROR:\n {0}".format(clear_error)) clear_msg.setStandardButtons(QMessageBox.Abort) clear_retval = clear_msg.exec_() clear_msg.show() def set_db_entry_button_script(self): db_name_fixed = self.avail_db_combo.currentText() + ".db" self.db = DatabaseInteraction(db_name_fixed) extr = Extractor(self.db.name) # Create datetime objects of the first and last strings of date self.datetime_first = datetime.strptime(extr.select_first_row()[ 0][0], "%Y-%m-%dT%H:%M:%S.%fZ") self.datetime_last = datetime.strptime(extr.select_last_row()[ 0][0], "%Y-%m-%dT%H:%M:%S.%fZ") self.first_row = QDate.fromString(str(self.datetime_first.date()), "yyyy-MM-dd") self.last_row = QDate.fromString(str(self.datetime_last.date()), "yyyy-MM-dd") self.calendar.setMinimumDate(self.first_row) self.calendar.setMaximumDate(self.last_row) self.first_row = QDate.fromString(str(self.datetime_first.date()), "yyyy-MM-dd") self.last_row = QDate.fromString(str(self.datetime_last.date()), "yyyy-MM-dd") self.calendar.setMinimumDate(self.first_row) self.calendar.setMaximumDate(self.last_row) def reload_db_combo(self): self.avail_db_combo.clear() self.avail_db_combo.addItems(self.available_db_combo()) self.clear_avail_db_combo.clear() self.clear_avail_db_combo.addItems(self.available_db_combo()) self.update_avail_db_combo.clear() self.update_avail_db_combo.addItems(self.available_db_combo()) self.ready_plot_avail_db_combo.clear() self.ready_plot_avail_db_combo.addItems(self.available_db_combo()) def available_db_combo(self): db_files = [] db_list_model = QStringListModel() for subdir, dirs, files in os.walk(os.path.dirname(os.path.realpath(__file__))): for file in files: filepath = subdir + os.path.sep + file if filepath.endswith(".db"): if filepath not in db_files: db_files.append(file[:-3]) db_list_model.setStringList(db_files) return db_list_model.stringList() def ready_plot_script(self): db = self.ready_plot_avail_db_combo.currentText() + ".db" extr = Extractor(db) plt = Plotter() ready_plot_title = db[:-3] if self.chart_field.currentIndex() == 0: chart_mode = "lines" elif self.chart_field.currentIndex() == 1: chart_mode = "lines+markers" elif self.chart_field.currentIndex() == 2: chart_mode = "markers" elif self.chart_field.currentIndex() == 3: chart_mode = "Bars" else: print("Something went wrong") if self.plot_mode_field.currentIndex() == 0: plot_mode = "daily_select" elif self.plot_mode_field.currentIndex() == 1: plot_mode = "weekly_select" elif self.plot_mode_field.currentIndex() == 2: plot_mode = "monthly_select" elif self.plot_mode_field.currentIndex() == 3: plot_mode = "yearly_select" else: print("Something went wrong") plot_lists = [] # Extract from the database the data for x-y axis and the unit plot_lists = extr.extract(plot_mode) if chart_mode == "lines" or chart_mode == "lines+markers" or chart_mode == "markers": plt.scatter_plot(chart_mode, plot_lists[0], plot_lists[1], ready_plot_title, "TIME", plot_lists[2][0]) elif chart_mode == "Bars": plt.bar_plot(plot_lists[0], plot_lists[1], ready_plot_title, "TIME", plot_lists[2][0]) else: print("Something went wrong")
class VentanaAdministradorDePersonas(QFrame): def __init__(self, parent=None): super(VentanaAdministradorDePersonas, self).__init__(parent) raiz.setWindowTitle("Administracion de personas") self.operacionesConPersonas = OperacionesConPersonas() self.instanciarVentana() def instanciarVentana(self): #Contenedor De todas las cosas de arriba a abajo layoutGeneral = QVBoxLayout() #Cosas de Derecha layoutDerecha = QVBoxLayout() #Ordena cosas de arriba a abajo layoutDerecha.setMargin(20) self.btnAgregarPersona = QPushButton("Agregar persona") self.btnAgregarPersona.setToolTip("Toma los datos ") self.btnAgregarPersona.clicked.connect(self.agregarPersona) layoutDerecha.addWidget(self.btnAgregarPersona) self.btnBuscarPersona = QPushButton("Buscar persona") self.btnBuscarPersona.setToolTip("Busca por cedula a una persona") self.btnBuscarPersona.clicked.connect(self.buscarPersona) layoutDerecha.addWidget(self.btnBuscarPersona) self.btnEliminarPersona = QPushButton("Eliminar persona") self.btnEliminarPersona.setToolTip( "Elimina a la persona que esta en busqueda") self.btnEliminarPersona.clicked.connect(self.eliminarPersona) layoutDerecha.addWidget(self.btnEliminarPersona) self.btnActualizarPersona = QPushButton("Actualizar persona") self.btnActualizarPersona.setToolTip( "Cambia los datos de la persona seleccionada") self.btnActualizarPersona.clicked.connect(self.actualizarPersona) layoutDerecha.addWidget(self.btnActualizarPersona) self.btnLimpiarTexto = QPushButton("Limpiar") self.btnLimpiarTexto.setToolTip( "Limpia los campos de texto para ingresar datos") self.btnLimpiarTexto.clicked.connect(self.limpiarCampos) layoutDerecha.addWidget(self.btnLimpiarTexto) self.btnVolverAlMenu = QPushButton("Volver") self.btnVolverAlMenu.setToolTip("Vuelve al menu principal") self.btnVolverAlMenu.clicked.connect(self.volverAlMenu) layoutDerecha.addWidget(self.btnVolverAlMenu) #Cosas de Izquierda layoutIzquierda = QVBoxLayout() #ordena cosas de arriba a abajo self.lblDNI = QLabel("DNI: ") layoutIzquierda.addWidget(self.lblDNI) self.DNI = QLineEdit() layoutIzquierda.addWidget(self.DNI) self.lblPrimerNombre = QLabel("Primer nombre: ") layoutIzquierda.addWidget(self.lblPrimerNombre) self.PrimerNombre = QLineEdit() layoutIzquierda.addWidget(self.PrimerNombre) self.lblSegundoNombre = QLabel("Segundo nombre: ") layoutIzquierda.addWidget(self.lblSegundoNombre) self.SegundoNombre = QLineEdit() layoutIzquierda.addWidget(self.SegundoNombre) self.lblPrimerApellido = QLabel("Primer apellido: ") layoutIzquierda.addWidget(self.lblPrimerApellido) self.PrimerApellido = QLineEdit() layoutIzquierda.addWidget(self.PrimerApellido) self.lblSegundoApellido = QLabel("Segundo apellido: ") layoutIzquierda.addWidget(self.lblSegundoApellido) self.SegundoApellido = QLineEdit() layoutIzquierda.addWidget(self.SegundoApellido) self.lblFechaDeNacimiento = QLabel("Fecha de nacimiento") layoutIzquierda.addWidget(self.lblFechaDeNacimiento) self.fechaDeNacimiento = QDateEdit() self.fechaDeNacimiento.setDisplayFormat("yyyy-MM-dd") self.fechaDeNacimiento.setCalendarPopup(True) self.fechaDeNacimiento.setDate(date.today()) layoutIzquierda.addWidget(self.fechaDeNacimiento) #Cosas de layout de arriba layoutSuperior = QHBoxLayout() #Ordena cosas de derecha a izquierda layoutSuperior.addLayout(layoutIzquierda) layoutSuperior.addLayout(layoutDerecha) #Cosas layout de abajo layoutInferior = QVBoxLayout() self.mostrarError = QPlainTextEdit(readOnly=True) layoutInferior.addWidget(self.mostrarError) #cosas del layout general layoutGeneral.addLayout(layoutSuperior) layoutGeneral.addLayout(layoutInferior) self.setLayout(layoutGeneral) #Redimensionar raiz.adjustSize() self.adjustSize() def agregarPersona(self): self.limpiarErrores() try: laPersona = self.llenarPersona() salida = self.operacionesConPersonas.insertarPersona(laPersona) self.mostrarError.insertPlainText(str(salida)) self.limpiarCampos( ) #habilitamos la edicion y evitamos dejar datos basura except Exception as e: self.mostrarError.insertPlainText(''.join(e.args)) pass def buscarPersona(self): self.limpiarErrores() try: laPersona = self.operacionesConPersonas.buscarPersonaPorDNI( int(''.join(self.DNI.text()))) if type(laPersona) == type(""): self.mostrarError.insertPlainText(''.join(laPersona)) return None self.llenarCampos(laPersona) except Exception as e: self.mostrarError.insertPlainText(''.join(e.args)) def eliminarPersona(self): self.limpiarErrores() try: laPersona = self.llenarPersona() mensajeDeConfirmacion = "DNI: " + self.DNI.text() opcionElegida = QMessageBox.question( self, "Desea eliminar a la persona?", mensajeDeConfirmacion, QMessageBox.Yes, QMessageBox.No) if opcionElegida == QMessageBox.Yes: respuesta = self.operacionesConPersonas.eliminarPersona( laPersona) if type(respuesta) == type(""): self.mostrarError.insertPlainText(''.join(respuesta)) self.limpiarCampos() return None except Exception as e: self.mostrarError.insertPlainText(''.join(e.args)) def actualizarPersona(self): self.limpiarErrores() try: laPersona = self.llenarPersona() mensajeDeConfirmacion = "DNI: " + self.DNI.text() opcionElegida = QMessageBox.question( self, "Desea eliminar a la persona?", mensajeDeConfirmacion, QMessageBox.Yes, QMessageBox.No) if opcionElegida == QMessageBox.Yes: respuesta = self.operacionesConPersonas.actualizarPersona( laPersona) if type(respuesta) == type(""): self.mostrarError.insertPlainText(''.join(respuesta)) self.limpiarCampos() return None except Exception as e: print(e.args) def llenarCampos(self, laPersona): self.limpiarCampos() self.DNI.setText(str(laPersona.getDNI())) self.DNI.setReadOnly(True) self.PrimerNombre.setText(laPersona.getPrimerNombre()) self.SegundoNombre.setText(laPersona.getSegundoNombre()) self.PrimerApellido.setText(laPersona.getPrimerApellido()) self.SegundoApellido.setText(laPersona.getSegundoApellido()) self.fechaDeNacimiento.setDate(laPersona.getFechaDeNacimiento()) def llenarPersona(self): return Persona(int(''.join(self.DNI.text())), ''.join(self.PrimerNombre.text()), ''.join(self.SegundoNombre.text()), ''.join(self.PrimerApellido.text()), ''.join(self.SegundoApellido.text()), ''.join(self.fechaDeNacimiento.text())) def limpiarCampos(self): self.DNI.clear() self.DNI.setReadOnly(False) self.PrimerNombre.clear() self.SegundoNombre.clear() self.PrimerApellido.clear() self.SegundoApellido.clear() self.fechaDeNacimiento.setDate(date.today()) #limpiar campos de texto y permitir la edicion de todos ellos def limpiarErrores(self): self.mostrarError.clear() def volverAlMenu(self): raiz.setCentralWidget(None) raiz.setCentralWidget(VentanaPrincipal())
class TradeWidget(AbstractOperationDetails): def __init__(self, parent=None): AbstractOperationDetails.__init__(self, parent) self.name = "Trade" self.date_label = QLabel(self) self.settlement_label = QLabel() self.number_label = QLabel(self) self.account_label = QLabel(self) self.symbol_label = QLabel(self) self.qty_label = QLabel(self) self.price_label = QLabel(self) self.fee_label = QLabel(self) self.comment_label = QLabel(self) self.main_label.setText(g_tr("TradeWidget", "Buy / Sell")) self.date_label.setText(g_tr("TradeWidget", "Date/Time")) self.settlement_label.setText(g_tr("TradeWidget", "Settlement")) self.number_label.setText(g_tr("TradeWidget", "#")) self.account_label.setText(g_tr("TradeWidget", "Account")) self.symbol_label.setText(g_tr("TradeWidget", "Asset")) self.qty_label.setText(g_tr("TradeWidget", "Qty")) self.price_label.setText(g_tr("TradeWidget", "Price")) self.fee_label.setText(g_tr("TradeWidget", "Fee")) self.comment_label.setText(g_tr("TradeWidget", "Note")) self.timestamp_editor = QDateTimeEdit(self) self.timestamp_editor.setCalendarPopup(True) self.timestamp_editor.setTimeSpec(Qt.UTC) self.timestamp_editor.setFixedWidth(self.timestamp_editor.fontMetrics().width("00/00/0000 00:00:00") * 1.25) self.timestamp_editor.setDisplayFormat("dd/MM/yyyy hh:mm:ss") self.settlement_editor = QDateEdit(self) self.settlement_editor.setCalendarPopup(True) self.settlement_editor.setTimeSpec(Qt.UTC) self.settlement_editor.setFixedWidth(self.settlement_editor.fontMetrics().width("00/00/0000") * 1.5) self.settlement_editor.setDisplayFormat("dd/MM/yyyy") self.account_widget = AccountSelector(self) self.asset_widget = AssetSelector(self) self.qty_edit = AmountEdit(self) self.qty_edit.setAlignment(Qt.AlignRight) self.price_edit = AmountEdit(self) self.price_edit.setAlignment(Qt.AlignRight) self.fee_edit = AmountEdit(self) self.fee_edit.setAlignment(Qt.AlignRight) self.number = QLineEdit(self) self.comment = QLineEdit(self) self.layout.addWidget(self.date_label, 1, 0, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.account_label, 2, 0, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.symbol_label, 3, 0, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.comment_label, 4, 0, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.timestamp_editor, 1, 1, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.account_widget, 2, 1, 1, 4) self.layout.addWidget(self.asset_widget, 3, 1, 1, 4) self.layout.addWidget(self.comment, 4, 1, 1, 4) self.layout.addWidget(self.settlement_label, 1, 2, 1, 1, Qt.AlignRight) self.layout.addWidget(self.settlement_editor, 1, 3, 1, 1, Qt.AlignLeft) self.layout.addWidget(self.number_label, 1, 5, 1, 1, Qt.AlignRight) self.layout.addWidget(self.qty_label, 2, 5, 1, 1, Qt.AlignRight) self.layout.addWidget(self.price_label, 3, 5, 1, 1, Qt.AlignRight) self.layout.addWidget(self.fee_label, 4, 5, 1, 1, Qt.AlignRight) self.layout.addWidget(self.number, 1, 6, 1, 1) self.layout.addWidget(self.qty_edit, 2, 6, 1, 1) self.layout.addWidget(self.price_edit, 3, 6, 1, 1) self.layout.addWidget(self.fee_edit, 4, 6, 1, 1) self.layout.addWidget(self.commit_button, 0, 8, 1, 1) self.layout.addWidget(self.revert_button, 0, 9, 1, 1) self.layout.addItem(self.verticalSpacer, 6, 6, 1, 1) self.layout.addItem(self.horizontalSpacer, 1, 6, 1, 1) super()._init_db("trades") self.mapper.setItemDelegate(TradeWidgetDelegate(self.mapper)) self.account_widget.changed.connect(self.mapper.submit) self.asset_widget.changed.connect(self.mapper.submit) self.mapper.addMapping(self.timestamp_editor, self.model.fieldIndex("timestamp")) self.mapper.addMapping(self.settlement_editor, self.model.fieldIndex("settlement")) self.mapper.addMapping(self.account_widget, self.model.fieldIndex("account_id")) self.mapper.addMapping(self.asset_widget, self.model.fieldIndex("asset_id")) self.mapper.addMapping(self.number, self.model.fieldIndex("number")) self.mapper.addMapping(self.qty_edit, self.model.fieldIndex("qty")) self.mapper.addMapping(self.price_edit, self.model.fieldIndex("price")) self.mapper.addMapping(self.fee_edit, self.model.fieldIndex("fee")) self.mapper.addMapping(self.comment, self.model.fieldIndex("note")) self.model.select() def prepareNew(self, account_id): new_record = self.model.record() new_record.setNull("id") new_record.setValue("timestamp", int(datetime.now().replace(tzinfo=tz.tzutc()).timestamp())) new_record.setValue("settlement", int(datetime.now().replace(tzinfo=tz.tzutc()).timestamp())) new_record.setValue("number", '') new_record.setValue("account_id", account_id) new_record.setValue("asset_id", 0) new_record.setValue("qty", 0) new_record.setValue("price", 0) new_record.setValue("fee", 0) new_record.setValue("note", None) return new_record def copyToNew(self, row): new_record = self.model.record(row) new_record.setNull("id") new_record.setValue("timestamp", int(datetime.now().replace(tzinfo=tz.tzutc()).timestamp())) new_record.setValue("settlement", int(datetime.now().replace(tzinfo=tz.tzutc()).timestamp())) new_record.setValue("number", '') return new_record
class PrenotazioneForm(QDialog): ''' Widget per l'inserimento di un acquisto immediato. ''' def __init__(self, conn): ''' Parameters: conn : connection Connection to the database. ''' super().__init__() self.setWindowTitle('Aggiungi Prenotazione') self.setWindowFlag(QtCore.Qt.WindowContextHelpButtonHint, False) self.conn = conn self.cursor = conn.cursor() self.books = dict() self.books_qt = dict() self.gen_layout = QVBoxLayout() self.form_layout = QFormLayout() self.form_layout.setRowWrapPolicy(QFormLayout.WrapLongRows) # Widgets self.client_field = QLineEdit() self.form_layout.addRow('Numero Cliente: ', self.client_field) self.dip_field = QLineEdit() self.form_layout.addRow('Dipendente (CF): ', self.dip_field) self.date_picker = QDateEdit(QDate.currentDate()) self.date_picker.setDisplayFormat("MM/dd/yyyy") self.date_picker.setCalendarPopup(True) self.form_layout.addRow('Data (mm/gg/aaaa): ', self.date_picker) self.importo_field = QDoubleSpinBox() self.importo_field.setMaximum(999999999.99) self.form_layout.addRow('Importo: ', self.importo_field) self.ins_layout = QHBoxLayout() self.libro_field = QLineEdit() self.quantita_field = QSpinBox() self.quantita_field.setMinimum(1) self.libro_button = QPushButton('Aggiungi') self.libro_button.clicked.connect(self.aggiungi_libro) self.ins_layout.addWidget(QLabel('Libro (ISBN): ')) self.ins_layout.addWidget(self.libro_field) self.ins_layout.addWidget(QLabel('Quantità: ')) self.ins_layout.addWidget(self.quantita_field) self.ins_layout.addWidget(self.libro_button) self.labels = ['ISBN', 'Quantità', ''] self.table = QTableWidget(0, 3) self.table.setHorizontalHeaderLabels(self.labels) self.table.horizontalHeader().setSectionResizeMode( 0, QHeaderView.Stretch) self.table.horizontalHeader().setSectionResizeMode( 1, QHeaderView.Stretch) self.table.horizontalHeader().setSectionResizeMode( 2, QHeaderView.ResizeToContents) self.info_label = QLabel( 'Le prenotazioni non riducono i libri disponibili.') self.confirm_button = QPushButton('Conferma') self.confirm_button.clicked.connect(self.post_prenotazione) self.gen_layout.addLayout(self.form_layout) self.gen_layout.addLayout(self.ins_layout) self.gen_layout.addWidget(self.table) self.gen_layout.addWidget(self.info_label) self.gen_layout.addWidget(self.confirm_button) self.setLayout(self.gen_layout) def aggiungi_libro(self): self.books[self.libro_field.text()] = self.quantita_field.value() self.update_table() def remove_libro(self, book): self.books.pop(book, None) self.update_table() def update_table(self): self.table.clearContents() while self.table.rowCount() > 0: self.table.removeRow(0) for book in self.books.keys(): row = self.table.rowCount() button = QPushButton('Rimuovi') button.clicked.connect(lambda: self.remove_libro(book)) self.table.insertRow(row) self.table.setItem(row, 0, QTableWidgetItem(book)) self.table.setItem(row, 1, QTableWidgetItem(str(self.books[book]))) self.table.setCellWidget(row, 2, button) def verif_libri(self): ''' Shows error messages based on the validity of inserted books, and returns False, or returns True if all the books are ok to sell right now. ''' if len(self.books.items()) == 0: self._show_error('Non ci sono libri nell\'acquisto') return False for book in self.books.keys(): self.cursor.execute('SELECT * FROM libro WHERE isbn = %s', (book, )) result = self.cursor.fetchall() if not result: self._show_error('\'{}\' non è un libro valido.'.format(book)) return False return True def verif_client_dip(self): ''' Returns false and displays and error message if cliente and dipendente are not valid tuples in the database, returns true if they are ok ''' cliente = self.client_field.text() if not cliente: self._show_error('Il Cliente è necessario per una Prenotazione.') return False if cliente: if not cliente.isdigit(): self._show_error('Il codice del Cliente deve essere numerico.') return False self.cursor.execute(FIND_CLIENTE, (cliente, )) result = self.cursor.fetchall() if not result or not result[0][0]: self._show_error('Cliente {} non esiste.'.format(cliente)) return False dipendente = self.dip_field.text() if not dipendente: self._show_error('Il Dipendente non può essere vuoto.') return False self.cursor.execute(FIND_DIPENDENTE, (dipendente, )) result = self.cursor.fetchall() if not result or not result[0][0]: self._show_error('Dipendente {} non esiste.'.format(dipendente)) return False return True def post_prenotazione(self): if not self.verif_libri(): return if not self.verif_client_dip(): return cliente = self.client_field.text().strip() if self.client_field.text( ).strip() else None importo = self.importo_field.value() self.cursor.execute( INSERT_ACQUISTO, (self.date_picker.date().toString('MM/dd/yyyy'), self.importo_field.value(), self.dip_field.text())) new_id = self.cursor.fetchall()[0][0] self.cursor.execute(INSERT_PRENOTAZIONE, (new_id, cliente)) for book in self.books.keys(): self.cursor.execute(INSERT_COMPRENDE, (new_id, book, self.books[book])) self.conn.commit() self._show_confirm() self.accept() def _show_confirm(self): dialog = QMessageBox() dialog.setWindowTitle('Conferma Prenotazione') msg = 'Registrato prenotazione per i seguenti libri:\n{}' dialog.setText( msg.format('\n'.join( ['{} x {}'.format(k, v) for k, v in self.books.items()]))) dialog.exec_() def _show_error(self, msg=''): dialog = QMessageBox() dialog.setWindowTitle('ERRORE') dialog.setText(msg) dialog.exec_()
class SpotPriceUI(QTabWidget): def __init__(self, *args, **kwargs): super(SpotPriceUI, self).__init__(*args, **kwargs) self.extra_data_widget = QWidget(self) # 提取数据tab layout = QVBoxLayout() # 现货价格源数据 source_layout = QHBoxLayout() self.current_date = QDateEdit(self) self.current_date.setDisplayFormat("yyyy-MM-dd") self.current_date.setDate(QDate.currentDate()) self.current_date.setCalendarPopup(True) source_layout.addWidget(self.current_date) source_layout.addWidget(QLabel("源数据:", self)) self.source_edit = QLineEdit(self) source_layout.addWidget(self.source_edit) layout.addLayout(source_layout) # 分析 analysis_layout = QHBoxLayout() self.analysis_button = QPushButton("提取数据", self) analysis_layout.addWidget(self.analysis_button) self.tip_label = QLabel("输入源数据后,点击提取数据进行数据提取.", self) analysis_layout.addWidget(self.tip_label) analysis_layout.addStretch() layout.addLayout(analysis_layout) # 预览数据的表格 self.preview_table = QTableWidget(self) self.preview_table.setColumnCount(5) self.preview_table.setHorizontalHeaderLabels(["日期", "品种", "交易代码", "现货价", "增减"]) layout.addWidget(self.preview_table) # 提交按钮 commit_layout = QHBoxLayout() commit_layout.addStretch() self.commit_button = QPushButton("确认提交", self) commit_layout.addWidget(self.commit_button) layout.addLayout(commit_layout) self.extra_data_widget.setLayout(layout) self.addTab(self.extra_data_widget, "数据提取") # 提取数据tab # 修改数据的tab self.modify_data_widget = QWidget(self) modify_layout = QVBoxLayout() params_layout = QHBoxLayout() params_layout.addWidget(QLabel("选择日期:", self)) self.modify_date_edit = QDateEdit(self) self.modify_date_edit.setDate(QDate.currentDate()) self.modify_date_edit.setCalendarPopup(True) self.modify_date_edit.setDisplayFormat("yyyy-MM-dd") params_layout.addWidget(self.modify_date_edit) self.modify_query_button = QPushButton("查询", self) params_layout.addWidget(self.modify_query_button) self.modify_tip_label = QLabel("选择日期查询出数据,双击要修改的数据编辑正确的数据,点击行尾修改.", self) params_layout.addWidget(self.modify_tip_label) params_layout.addStretch() modify_layout.addLayout(params_layout) # 数据表格 self.modify_table = QTableWidget(self) self.modify_table.setColumnCount(6) self.modify_table.setHorizontalHeaderLabels(["ID", "日期", "品种", "现货价", "增减", "修改"]) modify_layout.addWidget(self.modify_table) self.modify_data_widget.setLayout(modify_layout) self.addTab(self.modify_data_widget, "修改数据") self.setStyleSheet( "#modifyButton{border:none;color:rgb(180,30,50)}#modifyButton:hover{color:rgb(20,50,160)}" )
def createButtonView(self): buttons = [] datePickers = [] buttonPanel = QWidget() buttonPanel.setContentsMargins(0, 0, 0, 0) buttonCurrent = QPushButton('Current tasks') buttonCurrent.setCheckable(True) buttonFinished = QPushButton('Finished tasks') buttonFinished.setCheckable(True) buttonFilter = QPushButton("Filter by end date") buttonApply = QPushButton("Apply") buttonFilter.setCheckable(True) buttonCurrent.setMaximumWidth(100) buttonFinished.setMaximumWidth(100) buttonFilter.setMaximumWidth(100) buttonApply.setMaximumWidth(100) buttonCurrent.setMinimumWidth(100) buttonFinished.setMinimumWidth(100) buttonFilter.setMinimumWidth(100) buttonApply.setMinimumWidth(100) buttons.append(buttonFilter) # labelStart = QLabel("Date start") datePickers.append(labelStart) dateStart = QDateEdit() dateStart.setDisplayFormat('dd/MM/yyyy') dateStart.setCalendarPopup(True) dateStart.setDate(QDate.currentDate()) datePickers.append(dateStart) labelEnd = QLabel("Date end") datePickers.append(labelEnd) dateEnd = QDateEdit() dateEnd.setDisplayFormat('dd/MM/yyyy') dateEnd.setCalendarPopup(True) dateEnd.setDate(QDate.currentDate()) datePickers.append(dateEnd) datePickers.append(buttonApply) buttonCurrent.clicked.connect( self.switchCurrentTask(buttonFinished, buttonCurrent, buttons)) buttonFinished.clicked.connect( self.switchFinishedTask(buttonCurrent, buttonFinished, buttons)) buttonFilter.clicked.connect( self.openDatePickerFilter(datePickers, buttonFilter)) buttonApply.clicked.connect( self.ApplyDateFilterArchive(dateStart, dateEnd)) buttonCurrent.setChecked(True) vBox = QVBoxLayout() vBox.addWidget(buttonCurrent) vBox.addWidget(buttonFinished) vBox.addSpacing(30) for bnt in buttons: bnt.setVisible(False) vBox.addWidget(bnt) for datePicker in datePickers: datePicker.setVisible(False) vBox.addWidget(datePicker) vBox.addStretch(1) buttonPanel.setLayout(vBox) return buttonPanel
class ClienteForm(QDialog): ''' Dialog per l'inserimento di un ordine. ''' def __init__(self, conn): ''' Parameters: conn : connection Connection to the database. ''' super().__init__() self.setWindowTitle('Aggiungi Cliente') self.setWindowFlag(QtCore.Qt.WindowContextHelpButtonHint, False) self.conn = conn self.cursor = conn.cursor() self.gen_layout = QVBoxLayout() self.form_layout = QFormLayout() self.form_layout.setRowWrapPolicy(QFormLayout.WrapLongRows) # Widgets self.nome_field = QLineEdit() self.form_layout.addRow('Nome: ', self.nome_field) self.cognome_field = QLineEdit() self.form_layout.addRow('Cognome: ', self.cognome_field) self.date_field = QDateEdit(QDate.currentDate()) self.date_field.setDisplayFormat("MM/dd/yyyy") self.date_field.setCalendarPopup(True) self.form_layout.addRow('Data di nascita (mm/gg/aaaa): ', self.date_field) self.phone_field = QLineEdit() self.form_layout.addRow('Telefono (solo cifre): ', self.phone_field) self.email_field = QLineEdit() self.form_layout.addRow('E-Mail: ', self.email_field) self.confirm_button = QPushButton('Conferma') self.confirm_button.clicked.connect(self.post_cliente) self.gen_layout.addLayout(self.form_layout) self.gen_layout.addWidget(self.confirm_button) self.setLayout(self.gen_layout) def verif_data(self): if not self.nome_field.text().strip(): self._show_error('Il nome non può essere vuoto.') return False if not self.cognome_field.text().strip(): self._show_error('Il cognome non può essere vuoto.') return False phone = self.phone_field.text().strip() email = self.email_field.text().strip() if not phone and not email: self._show_error( 'Almeno uno fra telefono ed e-mail deve essere non vuoto.') return False if phone and not re.match('[0-9]{3,15}', phone): self._show_error('Numero di telefono non valido.') return False if email and not re.match('[A-Za-z0-9\.]{1,}@[A-Za-z0-9\.]{1,}', email): self._show_error('E-Mail non valida.') return False return True def post_cliente(self): if not self.verif_data(): return nome = self.nome_field.text().strip() cognome = self.cognome_field.text().strip() data = self.date_field.date().toString('MM/dd/yyyy') phone = self.phone_field.text().strip() if not phone: phone = None email = self.email_field.text().strip() if not email: email = None self.cursor.execute(INSERT_CLIENTE, (nome, cognome, data, phone, email)) self.conn.commit() self.accept() def _show_error(self, msg=''): dialog = QMessageBox() dialog.setWindowTitle('ERRORE') dialog.setText(msg) dialog.exec_()