def show_calendar(self, date_initial: 'QDate'): """ Calendar widget to select date from :return: None """ self.cal_widget = QWidget() self.cal_widget.setWindowModality(Qt.ApplicationModal) self.cal_widget.main_layout = QGridLayout(self.cal_widget) self.cal_widget.setWindowTitle('Calendar') self.cal_widget.setLayout(self.cal_widget.main_layout) cal = QCalendarWidget(self.cal_widget) cal.setGridVisible(True) cal.setSelectedDate(date_initial) self.cal_widget.main_layout.addWidget(cal, 0, 0) cal.clicked[QtCore.QDate].connect(self.showDate) button_set = QPushButton( QApplication.style().standardIcon( QtWidgets.QStyle.SP_DialogOkButton), " Set", self.cal_widget) button_set.clicked.connect(partial(self.set_date, cal)) self.cal_widget.main_layout.addWidget(button_set, 1, 1) self.cal_widget.lbl = QLabel(self.cal_widget) self.cal_widget.main_layout.addWidget(self.cal_widget.lbl, 1, 0) self.showDate(cal.selectedDate()) self.cal_widget.show()
class MyCalendarWidget(QWidget): updated_date = pyqtSignal(date, name='updated_date') def __init__(self, name=None, parent=None): super().__init__(parent) self.name = name self.cal = QCalendarWidget(self) initial_date = QDate.currentDate().addDays(-1) self.cal.setSelectedDate(initial_date) self.cal.setGridVisible(True) self.cal.clicked[QDate].connect(self.show_date) self.text_area = QLabel(self) date = self.cal.selectedDate() self.text_area.setText(date.toString()) hbox_layout = QHBoxLayout() hbox_layout.addWidget(self.cal) vbox_layout = QVBoxLayout() vbox_layout.addLayout(hbox_layout) vbox_layout.addWidget(self.text_area) self.setLayout(vbox_layout) def show_date(self, date): self.updated_date.emit(date.toPyDate()) self.text_area.setText(date.toString())
class CalendarDemo(QWidget): global currentYear, currentMonth currentYear = datetime.now().year currentMonth = datetime.now().month def __init__(self): super().__init__() self.setWindowTitle("Calendar PyQt5 & Python") self.setGeometry(300, 300, 450, 300) self.initUI() def initUI(self): self.calendar = QCalendarWidget(self) self.calendar.move(20, 20) self.calendar.setGridVisible(True) self.calendar.setMinimumDate(QDate(currentYear, currentMonth - 1, 1)) self.calendar.setMaximumDate( QDate(currentYear, currentMonth + 1, calendar.monthrange(currentYear, currentMonth)[1])) self.calendar.setSelectedDate(QDate(currentYear, currentMonth, 1)) self.calendar.clicked.connect(self.printDateInfo) def printDateInfo(self, qDate): print("{0}/{1}/{2}".format(qDate.month(), qDate.day(), qDate.year())) print("Day Number of the year: {}".format(qDate.dayOfYear())) print("Day Number of the week: {}".format(qDate.dayOfWeek()))
def get_calendar_widget(self): calendar = QCalendarWidget(self.cw) calendar.setGridVisible(True) calendar.setSelectedDate( QDate(int(self.current_year), int(self.current_month), int(self.current_date))) calendar.selectionChanged.connect(self.change_date_and_value) return calendar
def admin_app(self): dialog = AuthQInputDialog() dialog.exec_() if self.auth.password_verification(dialog.textValue()): admin_modal = QDialog(self.centralwidget) admin_modal.setGeometry(QRect(0, 0, 800, 600)) grid = QGridLayout() empty = QWidget() empty.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) old_pass = QLabel() old_pass.setText('Введите старый пароль:') old_pass_line = QLineEdit() old_pass_line.setEchoMode(QLineEdit.Password) new_pass = QLabel() new_pass.setText('Введите новый пароль:') new_pass_line = QLineEdit() new_pass_line.setEchoMode(QLineEdit.Password) btn_accept = QPushButton('Изменить пароль') btn_accept.clicked.connect( partial(self.auth.set_lecturer_pass, new_pass_line, old_pass_line)) expired_date = QLabel() expired_date.setText('Дата действия программы:') date_widget = QCalendarWidget() try: date_widget.setSelectedDate( QDate(*[int(i) for i in self.auth.date.split('-')])) except ValueError: pass btn_license = QPushButton('Применить') btn_license.clicked.connect( partial(self.auth.update_date, date_widget)) grid.addWidget(old_pass, 1, 0) grid.addWidget(old_pass_line, 1, 1) grid.addWidget(new_pass, 2, 0) grid.addWidget(new_pass_line, 2, 1) grid.addWidget(btn_accept, 3, 0) grid.addWidget(expired_date, 4, 0) grid.addWidget(date_widget, 5, 0) grid.addWidget(btn_license, 6, 0) grid.addWidget(empty, 10, 0) admin_modal.setLayout(grid) admin_modal.exec_()
class CalendarDialog(QDialog): def __init__(self, xlim): super(CalendarDialog, self).__init__() self.initUI(xlim) def initUI(self, xlim): Vl = QVBoxLayout() Grid = QGridLayout() ## number of Headerlines Grid.addWidget(QLabel('Select start time'), 0, 0) Grid.addWidget(QLabel('Select end time'), 0, 1) xs = num2date(xlim[0]) xt = num2date(xlim[1]) xmin = QDate(xs.year, xs.month, xs.day) xmax = QDate(xt.year, xt.month, xt.day) self.tstart = QCalendarWidget() self.tstart.setDateRange(xmin, xmax) self.tstart.setSelectedDate(xmin) self.tend = QCalendarWidget() self.tend.setDateRange(xmin, xmax) self.tend.setSelectedDate(xmax) Grid.addWidget(self.tstart, 1, 0) Grid.addWidget(self.tend, 1, 1) Vl.addLayout(Grid) self.buttons = QDialogButtonBox() self.ok_button = self.buttons.addButton(self.buttons.Ok) self.buttons.addButton(self.buttons.Cancel) self.buttons.accepted.connect(self.accept) self.buttons.rejected.connect(self.closeWindow) Vl.addWidget(self.buttons) self.setLayout(Vl) self.setWindowTitle('Select time') self.setGeometry(300, 300, 250, 150) self.show() def getResults(self): if self.exec_() == QDialog.Accepted: # get all values tstart = self.tstart.selectedDate().getDate() tend = self.tend.selectedDate().getDate() return tstart, tend else: return None def closeWindow(self): self.close() return None
class Calendar(QWidget): def __init__(self): super().__init__() self.calendar = QCalendarWidget(self) # self.calendar.setGridVisible(True) self.calendar.setContentsMargins(0,0,0,0) self.calendar.setSelectedDate(QDate(datetime.now().year, datetime.now().month, 1)) self.calendar.clicked.connect(self.printDateInfo) def printDateInfo(self, qDate): print('{0}/{1}/{2}'.format(qDate.month(), qDate.day(), qDate.year())) print(f'Day Number of the year: {qDate.dayOfYear()}') print(f'Day Number of the week: {qDate.dayOfWeek()}')
class Calendar(QDialog): currentDay = datetime.now().day currentMonth = datetime.now().month currentYear = datetime.now().year def __init__(self): super().__init__() self.setWindowTitle('Calendar') self.setGeometry(300, 300, 300, 300) self.initUI() def initUI(self): self.layout = QVBoxLayout() self.calendar = QCalendarWidget(self) self.calendar.setGridVisible(True) self.calendar.setMinimumDate( QDate(self.currentYear - 123, self.currentMonth, 1)) self.calendar.setMaximumDate( QDate(self.currentYear, self.currentMonth, self.currentDay)) self.calendar.setSelectedDate( QDate(self.currentYear, self.currentMonth, self.currentDay)) self.setDate(self.calendar.selectedDate()) self.calendar.clicked.connect(self.setDate) self.exit_button = QPushButton(text="Save", parent=self) self.exit_button.clicked.connect(self.close) self.layout.addWidget(self.calendar) self.layout.addWidget(self.exit_button) self.setLayout(self.layout) def printDateInfo(self, qDate): print('{0}/{1}/{2}'.format(qDate.day(), qDate.month(), qDate.year())) print(f'Day Number of the year: {qDate.dayOfYear()}') print(f'Day Number of the week: {qDate.dayOfWeek()}') def setDate(self, qDate): self.selectedDate = '{0} {1} {2}'.format( qDate.day(), qDate.longMonthName(qDate.month())[:3].capitalize(), qDate.year()) def getDate(self): return self.selectedDate
def on_date_edit_clicked(): dlg = QDialog(self.window) dlg.setWindowTitle(popup_title) layout = QVBoxLayout() cal = QCalendarWidget() cal.setMaximumDate(QDate(max_date)) cal.setSelectedDate(QDate(getattr(self.args, name))) cal.selectionChanged.connect(lambda: dlg.accept()) layout.addWidget(cal) okay = QPushButton('Select') okay.clicked.connect(lambda: dlg.accept()) layout.addWidget(okay) dlg.setLayout(layout) dlg.exec() setattr(self.args, name, cal.selectedDate().toPyDate()) date_edit.setText(str(getattr(self.args, name)))
def init_calendario(self): calendario = QCalendarWidget(self) currentMonth = datetime.now().month currentYear = datetime.now().year calendario.setMinimumDate(QDate(currentYear, currentMonth, 1)) calendario.setMaximumDate( QDate(currentYear + 1, currentMonth, calendar.monthrange(currentYear, currentMonth)[1])) calendario.setSelectedDate(QDate(currentYear, currentMonth, 1)) calendario.setFont(QFont('Georgia', 10)) calendario.setStyleSheet('background-color: lightblue') calendario.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) calendario.setGeometry(200, 200, 300, 200) calendario.setGridVisible(True) return calendario
class CalendarDemo(QWidget): global currentYear, currentMonth, final_date currentMonth = datetime.now().month currentYear = datetime.now().year final_date = '{0}-{1}-{2}'.format(datetime.now().day, datetime.now().month, datetime.now().year) def __init__(self): super().__init__() self.setWindowTitle('Calendario') self.setGeometry(300, 300, 680, 460) self.initUI() def initUI(self): self.calendar = QCalendarWidget(self) self.calendar.setGeometry(20, 20, 630, 410) self.calendar.setGridVisible(True) self.button = QPushButton('Confirmar') self.calendar.layout().addWidget(self.button) self.calendar.setMinimumDate(QDate(currentYear - 10, currentMonth, 1)) self.calendar.setMaximumDate( QDate(currentYear, currentMonth + 1, calendar.monthrange(currentYear, currentMonth)[1])) self.calendar.setSelectedDate(QDate(currentYear, currentMonth, 1)) self.calendar.clicked.connect(self.printDateInfo) self.button.clicked.connect(self.on_button_clicked) def printDateInfo(self, qDate): self.final_date = '{0}-{1}-{2}'.format(qDate.day(), qDate.month(), qDate.year()) # print(self.final_date) # print(f'Day Number of the year: {qDate.dayOfYear()}') # print(f'Day Number of the week: {qDate.dayOfWeek()}') def on_button_clicked(self): # print(self.final_date) PullData.main(self.final_date) alert = QMessageBox() alert.setText('Baixando processos') alert.exec_()
class Scheduler(QDialog): def __init__(self, photo, caption, ig): super(Scheduler, self).__init__() self.photo = photo self.caption = caption self.ig = ig self.init_ui() self.exec_() def init_ui(self): self.setWindowTitle("Schedule Post") self.date_edit = QDateTimeEdit(QDateTime.currentDateTime()) self.date_edit.setDisplayFormat("dd.MM.yyyy hh:mm") self.date_edit.setMinimumDateTime(QDateTime.currentDateTime()) self.calendar = QCalendarWidget(self) self.calendar.setGridVisible(True) self.calendar.setMinimumDate(QDate.currentDate()) self.calendar.setSelectedDate(QDate.currentDate()) self.calendar.clicked.connect(self.set_date_time) self.confirm_button = QPushButton("Confirm") self.confirm_button.clicked.connect(self.set_schedule) vbox = QVBoxLayout(self) vbox.addWidget(self.date_edit) vbox.addWidget(self.calendar) vbox.addWidget(self.confirm_button) def set_date_time(self, qDate): self.date_edit.setDate(qDate) def set_schedule(self): self.date_time = self.date_edit.dateTime() schedule = self.date_time.toPyDateTime() now = datetime.now() delta_t = schedule - now secs = delta_t.seconds + 1 t = Timer(secs, self.ig.upload, [self.photo, self.caption]) t.start() self.accept()
class CalendarDialog(QDialog): def __init__(self, *arg, **kwargs): super().__init__(*arg, **kwargs) self.setWindowTitle("Выберите дату") vbox = QVBoxLayout(self) self.calendar = QCalendarWidget() self.calendar.setGridVisible(True) self.calendar.setDateEditEnabled(False) button_save = QPushButton("Ок") button_save.clicked.connect(self.accept) vbox.addWidget(self.calendar) hbox = QHBoxLayout() hbox.addStretch(1) hbox.addWidget(button_save) vbox.addLayout(hbox) def get_date(self): date = self.calendar.selectedDate().toString(Qt.ISODate) date = datetime.strptime(date, "%Y-%m-%d").date() return date def set_date(self, date): self.calendar.setSelectedDate(date)
class CurrencyConverter(QDialog): def __init__(self, parent=None): super().__init__(parent) # initialize variables and download / parse the data file self.data = {} self.last_date = QDate().currentDate() self.currencies = [] self.period = [] self.download_unzip() # initialize widgets self.from_currency_label = QLabel("From currency:") self.from_currency = QComboBox() self.from_currency.addItems(self.currencies) self.to_currency_label = QLabel("To currency:") self.to_currency = QComboBox() self.to_currency.addItems(self.currencies) self.from_amount_label = QLabel("Amount to convert:") self.from_amount = QDoubleSpinBox() self.from_amount.setRange(0.01, 100000000.00) self.from_amount.setValue(1.00) self.to_amount_label = QLabel( "Result of conversion based on most recent rates: ") self.to_amount = QLabel("%.02f" % 1.00) self.from_date = QCalendarWidget() self.to_date = QCalendarWidget() self.rates_plot = pg.PlotWidget() self.legend = self.rates_plot.addLegend() # set widgets into layout grid = QGridLayout() grid.addWidget(self.from_currency_label, 0, 0) grid.addWidget(self.from_currency, 0, 1) grid.addWidget(self.to_currency_label, 0, 2) grid.addWidget(self.to_currency, 0, 3) grid.addWidget(self.from_amount_label, 1, 0) grid.addWidget(self.from_amount, 1, 1) grid.addWidget(self.to_amount_label, 1, 2) grid.addWidget(self.to_amount, 1, 3) grid.addWidget(self.from_date, 2, 0, 1, 2) grid.addWidget(self.to_date, 2, 2, 1, 2) grid.addWidget(self.rates_plot, 4, 0, 1, 4) self.setLayout(grid) self.setWindowTitle( "Currency Converter - Assignment 1 - Dommerc - 2982021") # refresh data today = QDate.currentDate() self.from_date.setSelectedDate(today.addDays(-10)) self.update_ui() # set event when input change (refresh ui) self.from_currency.currentIndexChanged.connect(self.update_ui) self.to_currency.currentIndexChanged.connect(self.update_ui) self.from_amount.valueChanged.connect(self.update_ui) self.from_date.selectionChanged.connect(self.update_ui) self.to_date.selectionChanged.connect(self.update_ui) # Method that return the 1st valid date by subtraction or addition one day def get_valid_date(self, date, sign): tmp = date while tmp not in self.data["USD"]: if sign == '+': tmp = tmp.addDays(+1) else: tmp = tmp.addDays(-1) return tmp # Method that set the period according to the two selected dates def set_period(self, from_date, to_date): tmp = from_date to_date = self.get_valid_date(to_date, '-') self.period.clear() while tmp <= to_date: tmp = self.get_valid_date(tmp, '+') if tmp <= to_date: self.period.append(tmp) tmp = tmp.addDays(+1) # Method that return rates according to the period and a currency def get_rates(self, currency): rates = [] for date in self.period: rates.append(self.data[currency][date]) return rates # Method that return conversion rates according to the rates of the two selected currencies @staticmethod def get_conversion_rates(rates_from, rates_to): rates_cv = [] i = 0 while i < len(rates_from): if rates_from[i] == 0 or rates_to[i] == 0: rates_cv.append(0) else: rates_cv.append(rates_to[i] / rates_from[i]) i += 1 return rates_cv # Refresh all data displayed in the window def update_ui(self): try: # set maximum and minimum date for the two date picker self.to_date.setMaximumDate(QDate.currentDate()) self.to_date.setMinimumDate(self.from_date.selectedDate()) self.from_date.setMaximumDate(self.to_date.selectedDate()) self.from_date.setMinimumDate(self.last_date) # compute the conversion value date = self.get_valid_date(QDate.currentDate(), '-') from_cur = self.from_currency.currentText() to_cur = self.to_currency.currentText() from_rate = self.data[from_cur][date] to_rate = self.data[to_cur][date] amount = self.from_amount.value() if from_rate > 0 and to_rate > 0: res = (to_rate / from_rate) * amount self.to_amount.setText("%.02f" % res) else: self.to_amount.setText("no data") # set period and get rates from_date = self.from_date.selectedDate() to_date = self.to_date.selectedDate() self.set_period(from_date, to_date) rates_from = self.get_rates(from_cur) rates_to = self.get_rates(to_cur) rates_cv = self.get_conversion_rates(rates_from, rates_to) # clear plots and legend self.rates_plot.clear() self.legend.scene().removeItem(self.legend) self.legend = self.rates_plot.addLegend() if len(self.period) == 0: return # set labels and ranges self.rates_plot.setLabel('left', 'Rate') self.rates_plot.setLabel('bottom', 'Days') date_range = range(0, len(self.period)) self.rates_plot.setXRange(0, len(self.period) - 1) min_ = min(min(rates_from), min(rates_to), min(rates_cv)) max_ = max(max(rates_from), max(rates_to), max(rates_cv)) self.rates_plot.setYRange(min_, max_) # set plots self.rates_plot.plot(date_range, rates_from, pen='b', symbol='o', symbolPen='b', symbolBrush=0.2, name=from_cur) self.rates_plot.plot(date_range, rates_to, pen='g', symbol='x', symbolPen='g', symbolBrush=0.2, name=to_cur) self.rates_plot.plot(date_range, rates_cv, pen="r", symbol='+', symbolPen='r', symbolBrush=0.2, name="conversion rate") except Exception as e: print(e) # Method that download data file and proceed to parsing def download_unzip(self): # download the file url = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist.zip' raw, _ = urlretrieve(url) zip_file_object = zipfile.ZipFile(raw, 'r') first_file = zip_file_object.namelist()[0] file = zip_file_object.open(first_file) content = file.read() # parsing the file lines = content.decode().split("\n") print(len(lines)) # get the last date of the file last_line = lines[len(lines) - 1] array = last_line.split(",") array = array[0].split("-") self.last_date = QDate(int(array[0]), int(array[1]), int(array[2])) # get all available currencies self.currencies = lines[0].split(",") self.currencies.pop(0) self.currencies.pop(len(self.currencies) - 1) for cur in self.currencies: self.data[cur] = {} lines.pop(0) # get value of each currency for each date for line in lines: items = line.split(",") array = items[0].split("-") date = QDate(int(array[0]), int(array[1]), int(array[2])) items.pop(0) items.pop(len(items) - 1) for idx, item in enumerate(items): if item == "N/A": self.data[self.currencies[idx]][date] = 0.0000 else: self.data[self.currencies[idx]][date] = float(item)
class CalendarDialog(QDialog): # ++++++++++++++++++++++++++++ __init__ +++++++++++++++++++++++++++++++ def __init__(self, parent=None): QDialog.__init__(self, parent) self.applayState = False self.dateRange = {'calendarRange': {'start_date': '', 'stop_date': ''}} self.vbox_general = QVBoxLayout() self.hbox_general = QHBoxLayout() self.hbox_buttons = QHBoxLayout() self.vbox_calendar1 = QVBoxLayout() self.vbox_calendar2 = QVBoxLayout() self.range_from = QLabel("from") self.range_to = QLabel("to") self.fromCalendar = QCalendarWidget(self) self.toCalendar = QCalendarWidget(self) self.setWindowTitle("კალენდარი") self.setWindowIcon(QtGui.QIcon("icon/calendar.svg")) self.vbox_calendar1.addWidget(self.range_from) self.vbox_calendar1.addWidget(self.fromCalendar) self.vbox_calendar2.addWidget(self.range_to) self.vbox_calendar2.addWidget(self.toCalendar) self.hbox_general.addLayout(self.vbox_calendar1) self.hbox_general.addLayout(self.vbox_calendar2) # ----------------- Create apply and cancel buttons ------------------- self.ApplySet = QPushButton("დასტური", self) self.CancelSet = QPushButton("გაუქმება", self) self.ApplySet.clicked.connect(self.applyCalendar) self.CancelSet.clicked.connect(self.CancelCalendar) # ------------- Add apply and cancel buttons on layout ---------------- self.hbox_buttons.addWidget(self.ApplySet) self.hbox_buttons.addWidget(self.CancelSet) # -------------------------- Set Layouts ------------------------------ self.vbox_general.addLayout(self.hbox_general) self.vbox_general.addLayout(self.hbox_buttons) self.setLayout(self.vbox_general) self.show() # -------------------------- Set calendar ----------------------------- def setCalendarRange(self, dateRange): self.dateRange = dateRange self.fromCalendar.setSelectedDate( QDate( QDate.fromString(self.dateRange['start_date'], 'dd.MM.yyyy').getDate()[0], QDate.fromString(self.dateRange['start_date'], 'dd.MM.yyyy').getDate()[1], QDate.fromString(self.dateRange['start_date'], 'dd.MM.yyyy').getDate()[2])) self.toCalendar.setSelectedDate( QDate( QDate.fromString(self.dateRange['stop_date'], 'dd.MM.yyyy').getDate()[0], QDate.fromString(self.dateRange['stop_date'], 'dd.MM.yyyy').getDate()[1], QDate.fromString(self.dateRange['stop_date'], 'dd.MM.yyyy').getDate()[2])) # +++++++++++++++++++++++++++ get Range +++++++++++++++++++++++++++++++ def getRange(self): return self.dateRange, self.applayState # ++++++++++++++++++++++++ Apply calendar +++++++++++++++++++++++++++++ def applyCalendar(self): self.dateRange['start_date'] = self.fromCalendar.selectedDate( ).toString("dd.MM.yyyy") self.dateRange['stop_date'] = self.toCalendar.selectedDate().toString( "dd.MM.yyyy") self.applayState = True self.close() # ++++++++++++++++++++++++ Cancel calendar ++++++++++++++++++++++++++++ def CancelCalendar(self): self.applayState = False self.close()
class SideBar(QWidget): analyze_button_clicked = pyqtSignal(dict) def __init__(self): super().__init__() self.analyzer = DataAnalyzer() self.cleaned_data = pd.DataFrame() self.min_date_selector = QCalendarWidget(self) self.max_date_selector = QCalendarWidget(self) self.target_line = QLineEdit(self) self.account_number_line = QLineEdit(self) self.message_line = QLineEdit(self) self.min_value_line = QLineEdit(self) self.max_value_line = QLineEdit(self) self.analyze_button = QPushButton('Analyze data') self.load_button = QPushButton('Load data') self.analyze_button.setDisabled(True) self._set_layout() self._set_connections() def _set_layout(self): self.layout = QVBoxLayout() self.layout.addWidget(QLabel('Min date')) self.layout.addWidget(self.min_date_selector) self.layout.addWidget(QLabel('Max date')) self.layout.addWidget(self.max_date_selector) self.layout.addWidget(QLabel('Min value')) self.layout.addWidget(self.min_value_line) self.layout.addWidget(QLabel('Max value')) self.layout.addWidget(self.max_value_line) self.layout.addWidget(QLabel('Target contains')) self.layout.addWidget(self.target_line) self.layout.addWidget(QLabel('Account number contains')) self.layout.addWidget(self.account_number_line) self.layout.addWidget(QLabel('Message contains')) self.layout.addWidget(self.message_line) self.layout.addWidget(self.analyze_button) self.layout.addWidget(self.load_button) def _set_connections(self): self.load_button.clicked.connect(self._handle_load_data) self.analyze_button.clicked.connect(self._handle_analyze_data) def _handle_load_data(self): file_paths = self._get_file_paths() if not file_paths: return None self.cleaned_data = load_and_clean_data(file_paths) self._set_dates_based_on_data() self.analyze_button.setDisabled(False) self._handle_analyze_data() def _set_dates_based_on_data(self): datetime_min = self.cleaned_data.time.min() datetime_max = self.cleaned_data.time.max() self.min_date_selector.setSelectedDate( QtCore.QDate(datetime_min.year, datetime_min.month, datetime_min.day)) self.max_date_selector.setSelectedDate( QtCore.QDate(datetime_max.year, datetime_max.month, datetime_max.day)) def _handle_analyze_data(self): analyzed_data = self.analyzer.analyze_data( self.cleaned_data, min_date=self._get_min_date(), max_date=self._get_max_date(), target=self._get_target(), account_number=self._get_account_number(), message=self._get_message(), min_value=self._get_min_value(), max_value=self._get_max_value()) if analyzed_data["by_event"].empty: show_warning("Warning", "No data to analyze") else: self.analyze_button_clicked.emit(analyzed_data) def _get_file_paths(self) -> List[str]: file_paths, _ = QFileDialog.getOpenFileNames( caption='Choose files for analysis', directory=DEFAULT_DATA_DIR) return file_paths def _get_min_date(self) -> datetime: return self.min_date_selector.selectedDate().toPyDate() def _get_max_date(self) -> datetime: return self.max_date_selector.selectedDate().toPyDate() def _get_target(self) -> str: return self.target_line.text() def _get_account_number(self) -> str: return self.account_number_line.text() def _get_message(self) -> str: return self.message_line.text() def _get_min_value(self) -> float: try: return float(self.min_value_line.text()) except (ValueError, TypeError): return None def _get_max_value(self) -> float: try: return float(self.max_value_line.text()) except (ValueError, TypeError): return None
class YuToolsDailyPlan(QWidget): def __init__(self): super().__init__() ActionDao.auto_update_action() self.txt_content = QPlainTextEdit(self) self.txt_content.setGeometry(10, 10, 350, 50) self.rb_begin = QRadioButton(self) self.rb_begin.setText('Begin') self.rb_begin.setChecked(True) self.rb_begin.setGeometry(10, 70, 50, 22) self.de_begin = QDateEdit(self) self.de_begin.setDate(QDate.currentDate()) self.de_begin.setGeometry(70, 70, 90, 22) self.rb_begin.clicked.connect( lambda: self.rb_select_date(self.de_begin)) self.rb_deadline = QRadioButton(self) self.rb_deadline.setText("Deadline") self.rb_deadline.setGeometry(180, 70, 60, 22) self.de_deadline = QDateEdit(self) self.de_deadline.setDate(QDate.currentDate().addDays(7)) self.de_deadline.setGeometry(250, 70, 90, 22) self.rb_deadline.clicked.connect( lambda: self.rb_select_date(self.de_deadline)) self.calendar_select = QCalendarWidget(self) self.calendar_select.setGeometry(10, 100, 256, 190) self.calendar_select.clicked.connect(self.select_date) self.combo_frequency = QComboBox(self) self.combo_frequency.addItem(PlanFrequency.NoRepeat.name) self.combo_frequency.addItem(PlanFrequency.Day.name) self.combo_frequency.addItem(PlanFrequency.Week.name) self.combo_frequency.addItem(PlanFrequency.Month.name) self.combo_frequency.addItem(PlanFrequency.Quarter.name) self.combo_frequency.addItem(PlanFrequency.Year.name) self.combo_frequency.setGeometry(280, 100, 80, 26) self.sb_repeat = QSpinBox(self) self.sb_repeat.setMinimum(1) self.sb_repeat.setGeometry(280, 130, 80, 26) self.cb_include = QCheckBox(self) self.cb_include.setText("Include Begin") self.cb_include.setChecked(True) self.cb_include.setGeometry(280, 160, 80, 26) self.combo_importance = QComboBox(self) self.combo_importance.addItem('Important') self.combo_importance.addItem('Unimportant') self.combo_importance.setGeometry(280, 190, 80, 26) self.combo_urgency = QComboBox(self) self.combo_urgency.addItem('Urgent') self.combo_urgency.addItem('Non-Urgent') self.combo_urgency.setGeometry(280, 220, 80, 26) self.btn_save = QPushButton(self) self.btn_save.setGeometry(280, 260, 80, 26) self.btn_save.setText("Save") self.btn_save.clicked.connect(self.save_plan) self.tb_plan = QTableView(self) self.tb_plan.horizontalHeader().setStretchLastSection(True) self.tb_plan.horizontalHeader().setSectionResizeMode( QHeaderView.Custom) self.tb_plan.verticalHeader().hide() self.tb_plan.setGeometry(370, 10, 421, 281) self.line_importance = QFrame(self) self.line_importance.setGeometry(390, 295, 20, 435) self.line_importance.setFrameShape(QFrame.VLine) self.line_importance.setFrameShadow(QFrame.Sunken) self.line_urgency = QFrame(self) self.line_urgency.setGeometry(5, 480, 791, 16) self.line_urgency.setFrameShape(QFrame.HLine) self.line_urgency.setFrameShadow(QFrame.Sunken) self.combo_ac_list_filter = QComboBox(self) self.combo_ac_list_filter.addItem('Wait') self.combo_ac_list_filter.addItem('Going') self.combo_ac_list_filter.addItem('Done') self.combo_ac_list_filter.addItem('Cancel') self.combo_ac_list_filter.addItem('Expire') self.combo_ac_list_filter.addItem('Will') self.combo_ac_list_filter.addItem('All') self.combo_ac_list_filter.setCurrentIndex(1) self.combo_ac_list_filter.setGeometry(375, 478, 50, 20) self.combo_ac_list_filter.currentIndexChanged.connect( self.change_tb_ac_list) self.tb_ac_first = QTableView(self) self.tb_ac_first.horizontalHeader().setStretchLastSection(True) self.tb_ac_first.horizontalHeader().setSectionResizeMode( QHeaderView.Custom) self.tb_ac_first.verticalHeader().hide() self.tb_ac_first.setItemDelegateForColumn( 3, ActionStatusDelegate(self.tb_ac_first)) self.tb_ac_first.setGeometry(410, 300, 381, 178) self.tb_ac_second = QTableView(self) self.tb_ac_second.horizontalHeader().setStretchLastSection(True) self.tb_ac_second.horizontalHeader().setSectionResizeMode( QHeaderView.Custom) self.tb_ac_second.verticalHeader().hide() self.tb_ac_second.setItemDelegateForColumn( 3, ActionStatusDelegate(self.tb_ac_second)) self.tb_ac_second.setGeometry(10, 300, 381, 178) self.tb_ac_third = QTableView(self) self.tb_ac_third.horizontalHeader().setStretchLastSection(True) self.tb_ac_third.horizontalHeader().setSectionResizeMode( QHeaderView.Custom) self.tb_ac_third.verticalHeader().hide() self.tb_ac_third.setItemDelegateForColumn( 3, ActionStatusDelegate(self.tb_ac_third)) self.tb_ac_third.setGeometry(10, 498, 381, 178) self.tb_ac_fourth = QTableView(self) self.tb_ac_fourth.horizontalHeader().setStretchLastSection(True) self.tb_ac_fourth.horizontalHeader().setSectionResizeMode( QHeaderView.Custom) self.tb_ac_fourth.verticalHeader().hide() self.tb_ac_fourth.setItemDelegateForColumn( 3, ActionStatusDelegate(self.tb_ac_fourth)) self.tb_ac_fourth.setGeometry(410, 498, 381, 178) self.tb_acs = { 1: self.tb_ac_first, 2: self.tb_ac_second, 3: self.tb_ac_third, 4: self.tb_ac_fourth } self.refresh_tb_plan() for index in range(1, 5): self.refresh_tb_action(index) def rb_select_date(self, de_target): self.calendar_select.setSelectedDate(de_target.date()) def select_date(self): date = self.calendar_select.selectedDate() if self.rb_begin.isChecked(): self.de_begin.setDate(date) elif self.rb_deadline.isChecked(): self.de_deadline.setDate(date) def save_plan(self): code, data = self.valid_check() if code == -1: QMessageBox.critical(self, 'Error', data) return code2, actions = self.generate_actions(data) if code2 == -1: QMessageBox.critical(self, 'Error', actions) return plan_id = PlanDao.add_plan(data) ActionDao.add_actions(actions, plan_id) self.txt_content.clear() self.refresh_tb_plan() self.refresh_tb_action(tb_index=code) def valid_check(self): content = self.txt_content.toPlainText().replace('\n', '.') if content.strip(' ').strip('.').strip(' ') == '': return -1, 'Content must be a normal string!' begin = self.de_begin.date() deadline = self.de_deadline.date() now = QDate.currentDate() diff_begin = now.daysTo(begin) diff_deadline = now.daysTo(deadline) if diff_begin < 0 or diff_deadline < 0 or diff_deadline < diff_begin: return -1, 'Deadline date must be farther than begin date and both of them must be farther than Now' begin_date = datetime.date(begin.year(), begin.month(), begin.day()) deadline = datetime.date(deadline.year(), deadline.month(), deadline.day()) frequency = self.combo_frequency.currentText() repeat = self.sb_repeat.value() importance = self.combo_importance.currentText() degree_importance = False if importance.lower().startswith( 'un') else True urgent = self.combo_urgency.currentText() degree_urgent = False if urgent.lower().startswith('non') else True plan = Plan(content=content, begin_date=begin_date, deadline=deadline, frequency=PlanFrequency[frequency], repeat=repeat, degree_importance=degree_importance, degree_urgency=degree_urgent) if degree_importance and degree_urgent: code = 1 elif degree_importance and not degree_urgent: code = 2 elif not degree_importance and not degree_urgent: code = 3 elif not degree_importance and degree_urgent: code = 4 return code, plan def generate_actions(self, plan): action_list = [] begin = QDate(plan.begin_date) deadline = QDate(plan.deadline) include = self.cb_include.isChecked() if plan.frequency == PlanFrequency.NoRepeat: days = begin.daysTo(deadline) if not include: if days == 0: return -1, 'There is not time to complete the plan' for i in range(plan.repeat): action = Action(content=plan.content, begin_date=plan.begin_date, deadline=plan.deadline, degree_importance=plan.degree_importance, degree_urgency=plan.degree_urgency, status=1) action_list.append(action) elif plan.frequency == PlanFrequency.Day: days = begin.daysTo(deadline) if not include: if days == 0: return -1, 'There is not time to complete the plan' for day in range(days + 1): if not include and day == 0: continue begin_date = begin.addDays(day) begin_date = datetime.date(begin_date.year(), begin_date.month(), begin_date.day()) for i in range(plan.repeat): action = Action(content=plan.content, begin_date=begin_date, deadline=begin_date, degree_importance=plan.degree_importance, degree_urgency=plan.degree_urgency, status=1) action_list.append(action) elif plan.frequency == PlanFrequency.Week: begin_week, begin_year = begin.weekNumber() begin_day_of_week = begin.dayOfWeek() deadline_week, deadline_year = deadline.weekNumber() weeks = deadline_week + (deadline_year - begin_year) * 52 - begin_week if not include: if weeks == 0: return -1, 'There is not time to complete the plan' current_week_deadline = begin.addDays(7 - begin_day_of_week) for week in range(weeks + 1): if not include and week == 0: continue current_week_deadline = current_week_deadline.addDays(7 * week) current_week_begin = current_week_deadline.addDays(-6) if week == 0: begin_date = plan.begin_date if week == weeks: deadline = plan.deadline else: deadline = datetime.date(current_week_deadline.year(), current_week_deadline.month(), current_week_deadline.day()) elif week == weeks: begin_date = datetime.date(current_week_begin.year(), current_week_begin.month(), current_week_begin.day()) deadline = plan.deadline else: begin_date = datetime.date(current_week_begin.year(), current_week_begin.month(), current_week_begin.day()) deadline = datetime.date(current_week_deadline.year(), current_week_deadline.month(), current_week_deadline.day()) for i in range(plan.repeat): action = Action(content=plan.content, begin_date=begin_date, deadline=deadline, degree_importance=plan.degree_importance, degree_urgency=plan.degree_urgency, status=1) action_list.append(action) elif plan.frequency == PlanFrequency.Month: begin_year = begin.year() deadline_year = deadline.year() years = deadline_year - begin_year begin_month = begin.month() deadline_month = deadline.month() months = deadline_month + 12 * years - begin_month if not include: if months == 0: return -1, 'There is not time to complete the plan' current_year = begin_year for month in range(months + 1): if not include and month == 0: continue current_month = begin_month + month if current_month > 12: current_month -= 12 current_year += 1 if month == 0: begin_date = plan.begin_date if month == months: deadline = plan.deadline else: deadline = datetime.date(current_year, current_month, begin.daysInMonth()) elif month == months: begin_date = datetime.date(current_year, current_month, 1) deadline = plan.deadline else: begin_date = datetime.date(current_year, current_month, 1) deadline = datetime.date(current_year, current_month, 1) deadline = datetime.date( current_year, current_month, QDate(deadline.year(), deadline.month(), deadline.day()).daysInMonth()) for i in range(plan.repeat): action = Action(content=plan.content, begin_date=begin_date, deadline=deadline, degree_importance=plan.degree_importance, degree_urgency=plan.degree_urgency, status=1) action_list.append(action) elif plan.frequency == PlanFrequency.Quarter: begin_year = begin.year() deadline_year = deadline.year() years = deadline_year - begin_year begin_month = begin.month() deadline_month = deadline.month() begin_quarter = (begin_month + 2) / 3 deadline_quarter = (deadline_month + 2) / 3 quarters = deadline_quarter + years * 4 - begin_quarter if not include: if quarters == 0: return -1, 'There is not time to complete the plan' current_year = begin_year for quarter in range(quarters + 1): if not include and quarter == 0: continue current_quarter = begin_quarter + quarter if current_quarter > 4: current_quarter -= 4 current_year += 1 begin_month = (current_quarter - 1) * 3 + 1 deadline_month = begin_month + 2 if quarter == 0: begin_date = plan.begin_date if quarter == quarters: deadline = plan.deadline else: deadline = datetime.date( current_year, deadline_month, (30 if deadline_month == 4 else 31)) elif quarter == quarters: begin_date = datetime.date(current_year, begin_month, 1) deadline = plan.deadline else: begin_date = datetime.date(current_year, begin_month, 1) deadline = datetime.date( current_year, deadline_month, (30 if deadline_month == 4 else 31)) for i in range(plan.repeat): action = Action(content=plan.content, begin_date=begin_date, deadline=deadline, degree_importance=plan.degree_importance, degree_urgency=plan.degree_urgency, status=1) action_list.append(action) elif plan.frequency == PlanFrequency.Year: begin_year = begin.year() deadline_year = deadline.year() years = deadline_year - begin_year if not include: if years == 0: return -1, 'There is not time to complete the plan' for year in range(years + 1): if not include and year == 0: continue current_year = begin_year + year if year == 0: begin_date = plan.begin_date if year == years: deadline = plan.deadline else: deadline = datetime.date(current_year, 12, 31) elif year == years: begin_date = datetime.date(current_year, 1, 1) deadline = plan.deadline else: begin_date = datetime.date(current_year, 1, 1) deadline = datetime.date(current_year, 12, 31) for i in range(plan.repeat): action = Action(content=plan.content, begin_date=begin_date, deadline=deadline, degree_importance=plan.degree_importance, degree_urgency=plan.degree_urgency, status=1) action_list.append(action) return 0, action_list def change_tb_ac_list(self): for index in range(1, 5): self.refresh_tb_action(index) def refresh_tb_plan(self): plans = PlanDao.query_plans() model = QStandardItemModel(len(plans), 3) model.setHorizontalHeaderLabels(['Content', 'Frequency', 'Flag']) row_index = 0 for plan in plans: qsi_content = QStandardItem(plan.content) qsi_content.setEditable(False) qsi_frequency = QStandardItem(plan.frequency.name) qsi_frequency.setEditable(False) qsi_flag = QStandardItem('{},{}'.format( 'Important' if plan.degree_importance else 'Unimportant', 'Urgency' if plan.degree_urgency else 'Non-urgency')) qsi_flag.setEditable(False) model.setItem(row_index, 0, qsi_content) model.setItem(row_index, 1, qsi_frequency) model.setItem(row_index, 2, qsi_flag) row_index += 1 self.tb_plan.setModel(model) self.tb_plan.setColumnWidth(0, 220) self.tb_plan.setColumnWidth(1, 70) self.tb_plan.setColumnWidth(2, 100) def refresh_tb_action(self, tb_index): tb_action = self.tb_acs[tb_index] ac_list_filter = self.combo_ac_list_filter.currentIndex() actions = ActionDao.query_actions(tb_index, ac_list_filter) model = QStandardItemModel(len(actions), 3) model.setHorizontalHeaderLabels( ['Content', 'Begin', 'Deadline', 'Status']) row_index = 0 for action in actions: qsi_content = QStandardItem(action.content) qsi_content.setEditable(False) qsi_begin_date = QStandardItem( action.begin_date.strftime("%Y/%m/%d")) qsi_content.setEditable(False) qsi_deadline = QStandardItem(action.deadline.strftime("%Y/%m/%d")) qsi_deadline.setEditable(False) qsi_status = QStandardItem() qsi_status.setData({'id': action.id, 'status': action.status}) qsi_status.setEditable(False) model.setItem(row_index, 0, qsi_content) model.setItem(row_index, 1, qsi_begin_date) model.setItem(row_index, 2, qsi_deadline) model.setItem(row_index, 3, qsi_status) row_index += 1 tb_action.setModel(model) tb_action.setColumnWidth(0, 150) tb_action.setColumnWidth(1, 75) tb_action.setColumnWidth(2, 75) tb_action.setColumnWidth(3, 40) def change_status(self, tb_action, act_id, status): if status == 0: QMessageBox.information(self, 'Tip', 'Please wait for beginning') elif status == 1: menu = QMenu(tb_action) done_act = menu.addAction(QIcon('icons/daily_plan/done.png'), 'Done') cancel_act = menu.addAction(QIcon('icons/daily_plan/cancel.png'), 'Cancel') act = menu.exec_( tb_action.mapToGlobal( QPoint(self.sender().x(), self.sender().y() + 10))) refresh = False if act == done_act: ActionDao.update_action(act_id, 2) refresh = True elif act == cancel_act: ActionDao.update_action(act_id, 3) refresh = True if refresh: self.refresh_tb_action( list(self.tb_acs.keys())[list( self.tb_acs.values()).index(tb_action)]) elif status == 2: QMessageBox.information( self, 'Tip', 'You are good that had completed the task') elif status == 3: QMessageBox.information(self, 'Tip', 'It is sadly you had canceled this task') elif status == 4: QMessageBox.information( self, 'Tip', 'It is sorry that this task had expired and you cannot operate it' )
class PyAlarm(QMainWindow): LIBREELEC_URL = "http://libreelec" def __init__(self): super().__init__() self.__config = Config() self.initUI() def initUI(self): self.setWindowFlags(QtCore.Qt.FramelessWindowHint) self.setGeometry(0, 0, 800, 480) self.setWindowTitle("PyAlarm") self.setWindowIcon(QIcon("pyalarm.png")) self.mousePressEvent = self.__windowClicked self.background = QLabel(self) self.background.setGeometry(0, 0, 800, 480) self.background.setPixmap( QPixmap( "C:\\Users\\V-Modder\\projects\\pyalarm\\pyalarm\\pyalarm.png") ) self.time = QLabel(self) self.time.setGeometry(122, 50, 250, 50) self.time.setText("00:00") font = QFont("SansSerif", pointSize=45) font.setBold(True) self.time.setFont(font) self.time.setObjectName("time") self.time.setStyleSheet("QLabel#time {color: white}") self.calender = QCalendarWidget(self) self.calender.setGeometry(50, 130, 320, 250) self.calender.setEnabled(False) self.timer = QTimer() self.timer.timeout.connect(self.__timerTick) self.timer.start(1000) settings = QWebEngineSettings.globalSettings() settings.setAttribute(QWebEngineSettings.ShowScrollBars, False) settings.setAttribute(QWebEngineSettings.ErrorPageEnabled, False) self.browser = QWebEngineView(self) self.browser.load(QUrl(self.LIBREELEC_URL)) self.browser.setGeometry(410, 10, 380, 460) self.browser.loadFinished.connect(self.__browserLoadFinished) self.contextButton = StripedButton(self) self.contextButton.setGeometry(3, 3, 50, 50) self.contextButton.clicked.connect(self.__contextClicked) self.__contextMenu = ContextMenu(self) self.__contextMenu.show() self.__contextMenu.setVisible(False) self.__alarmWidget = AlarmWidget(self) self.__alarmWidget.show() self.__alarmWidget.setVisible(False) self.show() def __timerTick(self): currentDate = datetime.now() self.time.setText(currentDate.strftime("%H:%M")) self.calender.setSelectedDate(QDate()) alarmManager = AlarmManager(self.__config) holiday = HolidayCalendar(self.__config.getHolidayUser(), self.__config.getHolidayPassword) if alarmManager.alarmAvailable( currentDate) and not holiday.isHolidayToday(): self.__alarmWidget.activate() def __contextClicked(self): self.__contextMenu.activate(self.__config) def __windowClicked(self, event): self.__contextMenu.setVisible(False) def __browserLoadFinished(self, success): if success == False: time.sleep(1) self.browser.load(QUrl(self.LIBREELEC_URL))
class MainWidget(QWidget): def __init__(self): QWidget.__init__(self) # Set Time One Group self.time_one_calendar = QCalendarWidget() self.time_one_country_combobox = QComboBox() self.time_one_vbox = QVBoxLayout() self.time_one_groupbox = QGroupBox("Time One") self.time_one_bottom_hbox = QHBoxLayout() self.time_one_time_edit = QTimeEdit() self.time_one_default_button = QPushButton() self.time_one_default_button.setIcon(QIcon("%s/gnome-set-time.png" % icon_path)) self.time_one_default_button.setMaximumSize(50, 50) self.time_one_bottom_hbox.addWidget(self.time_one_time_edit) self.time_one_bottom_hbox.addWidget(self.time_one_default_button) self.time_one_vbox.addWidget(self.time_one_country_combobox) self.time_one_vbox.addWidget(self.time_one_calendar) self.time_one_vbox.addLayout(self.time_one_bottom_hbox) self.time_one_groupbox.setLayout(self.time_one_vbox) # Set Time Two Group self.time_two_groupbox = QGroupBox("Time Two") self.time_two_calendar = QCalendarWidget() self.time_two_vbox = QVBoxLayout() self.time_two_country_combobox = QComboBox() self.time_two_bottom_hbox = QHBoxLayout() self.time_two_time_edit = QTimeEdit() self.time_two_default_button = QPushButton() self.time_two_default_button.setIcon(QIcon("%s/gnome-set-time.png" % icon_path)) self.time_two_default_button.setMaximumSize(50, 50) self.time_two_bottom_hbox.addWidget(self.time_two_time_edit) self.time_two_bottom_hbox.addWidget(self.time_two_default_button) self.time_two_vbox.addWidget(self.time_two_country_combobox) self.time_two_vbox.addWidget(self.time_two_calendar) self.time_two_vbox.addLayout(self.time_two_bottom_hbox) self.time_two_groupbox.setLayout(self.time_two_vbox) # Set main layout self.main_layout = QHBoxLayout() self.main_layout.addWidget(self.time_one_groupbox) self.main_layout.addWidget(self.time_two_groupbox) self.setLayout(self.main_layout) # Wire-up your widgets! self.time_one_connect() self.time_two_connect() self.time_one_default_button.clicked.connect(self.set_local_time_one) self.time_two_default_button.clicked.connect(self.set_local_time_two) # Set the local time for time one self.set_local_country() self.set_local_time_one() # Finally, convert the second time based on the first self.convert_timeone_to_timetwo() def set_local_country(self): global_timezone_list = timezone_info.get_global_timezone_list() local_tz_index = global_timezone_list.index(str(self.get_local_timezone())) self.time_one_country_combobox.addItems(global_timezone_list) self.time_one_country_combobox.setCurrentIndex(local_tz_index) self.time_two_country_combobox.addItems(global_timezone_list) # To-do: Current solution works for Debian systems. Need to find repo solution that # allows for something like "from tzlocal import get_localzone" @staticmethod def get_local_timezone(): timezone_file = '/etc/timezone' try: file = open(timezone_file, 'r') system_timezone = file.read().rstrip() except IOError: print("Unable to open %s") & timezone_file system_timezone = 'UTC' return system_timezone @staticmethod def get_local_times(): local_hour = datetime.datetime.now().strftime("%H") local_minute = datetime.datetime.now().strftime("%M") local_current_time = QTime(int(local_hour), int(local_minute), 0, 0) return local_current_time def set_local_time_one(self): # Set time for one time local_current_time = self.get_local_times() self.time_one_time_edit.setTime(local_current_time) # Set date for one calendar self.time_one_calendar.setSelectedDate(QDate.currentDate()) # Convert the second time based on the first self.convert_timeone_to_timetwo() def set_local_time_two(self): # Set time for one time local_current_time = self.get_local_times() self.time_two_time_edit.setTime(local_current_time) # Set date for one calendar self.time_two_calendar.setSelectedDate(QDate.currentDate()) # Convert the first time based on the second self.convert_timetwo_to_timeone() def time_one_connect(self): self.time_one_country_combobox.activated.connect(self.convert_timeone_to_timetwo) self.time_one_calendar.clicked.connect(self.convert_timeone_to_timetwo) self.time_one_calendar.currentPageChanged.connect(self.convert_timeone_to_timetwo) self.time_one_time_edit.timeChanged.connect(self.convert_timeone_to_timetwo) def time_two_connect(self): self.time_two_country_combobox.activated.connect(self.convert_timeone_to_timetwo) self.time_two_calendar.clicked.connect(self.convert_timetwo_to_timeone) self.time_two_calendar.currentPageChanged.connect(self.convert_timetwo_to_timeone) self.time_two_time_edit.timeChanged.connect(self.convert_timetwo_to_timeone) def time_one_disconnect(self): self.time_one_calendar.clicked.disconnect() self.time_one_country_combobox.activated.disconnect() self.time_one_time_edit.timeChanged.disconnect() def time_two_disconnect(self): self.time_two_calendar.clicked.disconnect() self.time_two_country_combobox.activated.disconnect() self.time_two_time_edit.timeChanged.disconnect() def clear_combo_boxes(self): self.time_one_country_combobox.clear() self.time_two_country_combobox.clear() def __amend_country_region(self): """ Used to add the regional header before converting if a region outside of global is used. """ current_region = timezone_info.get_city_region(self.time_one_country_combobox.currentText()) time_one_country = self.time_one_country_combobox.currentText() time_two_country = self.time_two_country_combobox.currentText() if '/' not in time_one_country: time_one_country = current_region+'/'+self.time_one_country_combobox.currentText() time_two_country = current_region+'/'+self.time_two_country_combobox.currentText() return time_one_country, time_two_country def convert_timeone_to_timetwo(self): # Disconnect time two widgets,so that they do not run self.time_two_disconnect() time_one_country, time_two_country = self.__amend_country_region() date_time_one = datetime.datetime(self.time_one_calendar.yearShown(), self.time_one_calendar.monthShown(), self.time_one_calendar.selectedDate().day(), self.time_one_time_edit.time().hour(), self.time_one_time_edit.time().minute()) first_tz = timezone(time_one_country) second_tz = timezone(time_two_country) first_dt = first_tz.localize(date_time_one) second_dt = first_dt.astimezone(second_tz) new_date_two = QDate(second_dt.year, second_dt.month, second_dt.day) self.time_two_calendar.setSelectedDate(new_date_two) new_time_two = QTime(int(second_dt.hour), int(second_dt.minute)) self.time_two_time_edit.setTime(new_time_two) # Reconnect time one widgets. self.time_two_connect() def convert_timetwo_to_timeone(self): # Disconnect time one widgets,so that they do not run self.time_one_disconnect() time_one_country, time_two_country = self.__amend_country_region() date_time_two = datetime.datetime(self.time_two_calendar.yearShown(), self.time_two_calendar.monthShown(), self.time_two_calendar.selectedDate().day(), self.time_two_time_edit.time().hour(), self.time_two_time_edit.time().minute()) first_tz = timezone(time_one_country) second_tz = timezone(time_two_country) second_dt = second_tz.localize(date_time_two) first_dt = second_dt.astimezone(first_tz) new_date_one = QDate(first_dt.year, first_dt.month, first_dt.day) self.time_one_calendar.setSelectedDate(new_date_one) new_time_one = QTime(int(first_dt.hour), int(first_dt.minute)) self.time_one_time_edit.setTime(new_time_one) # Reconnect time one widgets self.time_one_connect()
class CalendarGUI(QWidget): def __init__(self): super().__init__() self.initializeUI() def initializeUI(self): """ Initialize the window and display its contents to the screen. """ self.setMinimumSize(500, 400) self.setWindowTitle('12.4 – Calendar GUI') self.createCalendar() self.show() def createCalendar(self): """ Set up calendar, others widgets and layouts for main window. """ self.calendar = QCalendarWidget() self.calendar.setGridVisible(True) self.calendar.setMinimumDate(QDate(1900, 1, 1)) self.calendar.setMaximumDate(QDate(2200, 1, 1)) # Connect to newDateSelection slot when currently selected date is changed self.calendar.selectionChanged.connect(self.newDateSelection) current = QDate.currentDate().toString(Qt.DefaultLocaleLongDate) self.current_label = QLabel(current) self.current_label.setObjectName("DateSelected") # Create current, minimum and maximum QDateEdit widgets min_date_label = QLabel("Minimum Date:") self.min_date_edit = QDateEdit() self.min_date_edit.setDisplayFormat("MMM d yyyy") self.min_date_edit.setDateRange(self.calendar.minimumDate(), self.calendar.maximumDate()) self.min_date_edit.setDate(self.calendar.minimumDate()) self.min_date_edit.dateChanged.connect(self.minDatedChanged) current_date_label = QLabel("Current Date:") self.current_date_edit = QDateEdit() self.current_date_edit.setDisplayFormat("MMM d yyyy") self.current_date_edit.setDate(self.calendar.selectedDate()) self.current_date_edit.setDateRange(self.calendar.minimumDate(), self.calendar.maximumDate()) self.current_date_edit.dateChanged.connect(self.selectionDateChanged) max_date_label = QLabel("Maximum Date:") self.max_date_edit = QDateEdit() self.max_date_edit.setDisplayFormat("MMM d yyyy") self.max_date_edit.setDateRange(self.calendar.minimumDate(), self.calendar.maximumDate()) self.max_date_edit.setDate(self.calendar.maximumDate()) self.max_date_edit.dateChanged.connect(self.maxDatedChanged) # Add widgets to group box and add to grid layout dates_gb = QGroupBox("Set Dates") dates_grid = QGridLayout() dates_grid.addWidget(self.current_label, 0, 0, 1, 2, Qt.AlignAbsolute) dates_grid.addWidget(min_date_label, 1, 0) dates_grid.addWidget(self.min_date_edit, 1, 1) dates_grid.addWidget(current_date_label, 2, 0) dates_grid.addWidget(self.current_date_edit, 2, 1) dates_grid.addWidget(max_date_label, 3, 0) dates_grid.addWidget(self.max_date_edit, 3, 1) dates_gb.setLayout(dates_grid) # Create and set main window's layout main_h_box = QHBoxLayout() main_h_box.addWidget(self.calendar) main_h_box.addWidget(dates_gb) self.setLayout(main_h_box) def selectionDateChanged(self, date): """ Update the current_date_edit when the calendar's selected date changes. """ self.calendar.setSelectedDate(date) def minDatedChanged(self, date): """ Update the calendar's minimum date. Update max_date_edit to avoid conflicts with maximum and minimum dates. """ self.calendar.setMinimumDate(date) self.max_date_edit.setDate(self.calendar.maximumDate()) def maxDatedChanged(self, date): """ Update the calendar's maximum date. Update min_date_edit to avoid conflicts with minimum and maximum dates. """ self.calendar.setMaximumDate(date) self.min_date_edit.setDate(self.calendar.minimumDate()) def newDateSelection(self): """ Update date in current_label and current_date_edit widgets when user selects a new date. """ date = self.calendar.selectedDate().toString(Qt.DefaultLocaleLongDate) self.current_date_edit.setDate(self.calendar.selectedDate()) self.current_label.setText(date)
class mainwindow(QWidget): def __init__(self, username, dataoptions, driver, semesters): self.username = username self.dataoptions = dataoptions self.driver = driver self.semesters = semesters self.subThread = submitThread(self) self.subThread.finished.connect(self.completed) super().__init__() self.initUI() def initUI(self): self.center() #add the data type label and C C C combobox self.datatypelabel = QLabel(self) self.datatypelabel.setText("Data Pull Type") self.datatypelabel.setAlignment(Qt.AlignCenter) self.datacombo = QComboBox(self) #Sorted by alphabet self.datacombo.addItems(sorted(self.dataoptions.keys())) self.datacombo.currentTextChanged.connect(self.combochange) #add the filter label self.filterlabel = QLabel(self) self.filterlabel.setText('Filters') self.filterlabel.setAlignment(Qt.AlignCenter) #add all of the other filter things self.usernamelabel = QLabel(self) self.usernamelabel.setText("Created By: ") self.usernamecombo = QComboBox(self) self.assignedlabel = QLabel(self) self.assignedlabel.setText("Assigned To: ") self.assignedcombo = QComboBox(self) self.locationlabel = QLabel(self) self.locationlabel.setText("Location: ") self.locationcombo = QComboBox(self) self.categorylabel = QLabel(self) self.categorylabel.setText("Category: ") self.categorycombo = QComboBox(self) self.statuslabels = QLabel(self) self.statuslabels.setText("Status: ") self.statuscombo = QComboBox(self) #add the startdate and end date calendars self.startcal = QCalendarWidget(self) self.startcal.setSelectedDate(date.today() - timedelta(days=30)) self.startcal.setVerticalHeaderFormat(QCalendarWidget.NoVerticalHeader) self.startcal.setGridVisible(True) self.startcal.clicked.connect(self.startdatechange) self.startlabel = QLabel(self) self.startlabel.setText("Start Date: " + self.startcal.selectedDate().toString()) self.startdroplabel = QLabel(self) self.startdroplabel.setText('Autoselect start of : ') self.startdroplabel.setObjectName('desctext') self.startcombo = QComboBox(self) self.startcombo.addItems(self.semesters.keys()) self.startcombo.currentTextChanged.connect(self.startcomboselect) self.endcal = QCalendarWidget(self) self.endcal.setSelectedDate(date.today()) self.endcal.setVerticalHeaderFormat(QCalendarWidget.NoVerticalHeader) self.endcal.setGridVisible(True) self.endcal.clicked.connect(self.enddatechange) self.endlabel = QLabel(self) self.endlabel.setText("End Date: " + self.endcal.selectedDate().toString()) self.enddroplabel = QLabel(self) self.enddroplabel.setText('Autoselect end of : ') self.enddroplabel.setObjectName('desctext') self.endcombo = QComboBox(self) self.endcombo.addItems(self.semesters.keys()) self.endcombo.currentTextChanged.connect(self.endcomboselect) #create the maxreturns things self.maxlabel = QLabel(self) self.maxlabel.setText("Max Returns: ") self.maxlabel.hide() self.maxbox = QLineEdit(self) self.maxbox.setText('10000000') self.maxbox.hide() #add close button self.closebutton = QPushButton('Close', self) self.closebutton.clicked.connect(self.close) #add submit button self.submitbutton = QPushButton('Submit', self) self.submitbutton.clicked.connect(self.subThread.start) self.tabs = QTabWidget() #everything for the data pull tab self.datapulltab = QWidget() datatypelabhbox = QHBoxLayout() datatypelabhbox.addWidget(self.datatypelabel) datatypehbox = QHBoxLayout() datatypehbox.addWidget(self.datacombo) filternamehbox = QHBoxLayout() filternamehbox.addWidget(self.filterlabel) usernamehbox = QHBoxLayout() usernamehbox.addWidget(self.usernamelabel) assignedhbox = QHBoxLayout() assignedhbox.addWidget(self.assignedlabel) locationhbox = QHBoxLayout() locationhbox.addWidget(self.locationlabel) categoryhbox = QHBoxLayout() categoryhbox.addWidget(self.categorylabel) statushbox = QHBoxLayout() statushbox.addWidget(self.statuslabels) dataselectlayout = QVBoxLayout() dataselectlayout.addLayout(datatypelabhbox) dataselectlayout.addLayout(datatypehbox) verticalSpacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) dataselectlayout.addSpacerItem(verticalSpacer) dataselectlayout.addLayout(filternamehbox) dataselectlayout.addLayout(usernamehbox) dataselectlayout.addWidget(self.usernamecombo) dataselectlayout.addLayout(assignedhbox) dataselectlayout.addWidget(self.assignedcombo) dataselectlayout.addLayout(locationhbox) dataselectlayout.addWidget(self.locationcombo) dataselectlayout.addLayout(categoryhbox) dataselectlayout.addWidget(self.categorycombo) dataselectlayout.addLayout(statushbox) dataselectlayout.addWidget(self.statuscombo) dataselectlayout.setSpacing(3) dataselectlayout.addStretch(1) startdrophlayout = QHBoxLayout() startdrophlayout.addWidget(self.startdroplabel) startdrophlayout.addWidget(self.startcombo) startdrophlayout.setSpacing(0) startdrophlayout.addStretch(0) enddropylayout = QHBoxLayout() enddropylayout.addWidget(self.enddroplabel) enddropylayout.addWidget(self.endcombo) enddropylayout.setSpacing(0) enddropylayout.addStretch(0) calendarlayout = QVBoxLayout() calendarlayout.addWidget(self.startlabel) calendarlayout.addLayout(startdrophlayout) calendarlayout.addWidget(self.startcal) calendarlayout.addSpacing(10) calendarlayout.addWidget(self.endlabel) calendarlayout.addLayout(enddropylayout) calendarlayout.addWidget(self.endcal) calendarlayout.setSpacing(3) calendarlayout.addStretch(1) datapullhlayout = QHBoxLayout() datapullhlayout.addLayout(dataselectlayout) datapullhlayout.addSpacing(10) datapullhlayout.addLayout(calendarlayout) datapullvlayout = QVBoxLayout() datapullvlayout.addSpacing(15) datapullvlayout.addLayout(datapullhlayout) self.datapulltab.setLayout(datapullvlayout) #Report things? self.reporttab = QWidget() self.startrepcal = QCalendarWidget(self) self.startrepcal.setSelectedDate(date.today() - timedelta(days=30)) self.startrepcal.setVerticalHeaderFormat( QCalendarWidget.NoVerticalHeader) self.startrepcal.setGridVisible(True) self.startrepcal.clicked.connect(self.startrepdatechange) self.startreplabel = QLabel(self) self.startreplabel.setText("Start Date: " + self.startrepcal.selectedDate().toString()) self.endrepcal = QCalendarWidget(self) self.endrepcal.setSelectedDate(date.today()) self.endrepcal.setVerticalHeaderFormat( QCalendarWidget.NoVerticalHeader) self.endrepcal.setGridVisible(True) self.endrepcal.clicked.connect(self.endrepdatechange) self.endreplabel = QLabel(self) self.endreplabel.setText("End Date: " + self.endrepcal.selectedDate().toString()) self.reporttypelabel = QLabel(self) self.reporttypelabel.setText('Report Type') self.reporttypelabel.setAlignment(Qt.AlignCenter) self.reportdrop = QComboBox(self) self.reportdrop.addItems([x.name for x in report.report_list]) self.reportdrop.currentTextChanged.connect(self.reportcombochange) self.reportactivelabel = QLabel(self) self.reportactivelabel.setText("Active") self.reportactive = QLabel(self) self.reportactive.setText("") self.reportactive.setObjectName('desctext') self.reportauthorlabel = QLabel(self) self.reportauthorlabel.setText("Author") self.reportauthor = QLabel(self) self.reportauthor.setText("") self.reportauthor.setObjectName('desctext') self.reportdesclabel = QLabel(self) self.reportdesclabel.setText("Report Description") self.descbox = QLabel(self) self.descbox.setText("") self.descbox.setWordWrap(True) self.descbox.setFixedWidth(self.usernamecombo.frameGeometry().width() + 53) self.descbox.setObjectName('desctext') self.startrepdroplabel = QLabel(self) self.startrepdroplabel.setObjectName('desctext') self.startrepdroplabel.setText('Autoselect start of : ') self.startrepcombo = QComboBox(self) self.startrepcombo.addItems(self.semesters.keys()) self.startrepcombo.currentTextChanged.connect(self.startrepcomboselect) self.enddropreplabel = QLabel(self) self.enddropreplabel.setText('Autoselect end of : ') self.enddropreplabel.setObjectName('desctext') self.endrepcombo = QComboBox(self) self.endrepcombo.addItems(self.semesters.keys()) self.endrepcombo.currentTextChanged.connect(self.endrepcomboselect) newreportlayout = QVBoxLayout() newreportlayout.addWidget(self.reporttypelabel) newreportlayout.addWidget(self.reportdrop) verticalSpacernew = QSpacerItem(10, 20, QSizePolicy.Minimum, QSizePolicy.Expanding) newreportlayout.addSpacerItem(verticalSpacernew) newreportlayout.addWidget(self.reportauthorlabel) newreportlayout.addWidget(self.reportauthor) verticalSpacernewest = QSpacerItem(10, 20, QSizePolicy.Minimum, QSizePolicy.Expanding) newreportlayout.addSpacerItem(verticalSpacernewest) newreportlayout.addWidget(self.reportactivelabel) newreportlayout.addWidget(self.reportactive) verticalSpacernewer = QSpacerItem(10, 20, QSizePolicy.Minimum, QSizePolicy.Expanding) newreportlayout.addSpacerItem(verticalSpacernewer) newreportlayout.addWidget(self.reportdesclabel) newreportlayout.addWidget(self.descbox) newreportlayout.setSpacing(3) newreportlayout.addStretch(1) startrepdrophlayout = QHBoxLayout() startrepdrophlayout.addWidget(self.startrepdroplabel) startrepdrophlayout.addWidget(self.startrepcombo) startrepdrophlayout.setSpacing(0) startrepdrophlayout.addStretch(0) endrepdropylayout = QHBoxLayout() endrepdropylayout.addWidget(self.enddropreplabel) endrepdropylayout.addWidget(self.endrepcombo) endrepdropylayout.setSpacing(0) endrepdropylayout.addStretch(0) repcallayout = QVBoxLayout() repcallayout.addWidget(self.startreplabel) repcallayout.addLayout(startrepdrophlayout) repcallayout.addWidget(self.startrepcal) repcallayout.addSpacing(10) repcallayout.addWidget(self.endreplabel) repcallayout.addLayout(endrepdropylayout) repcallayout.addWidget(self.endrepcal) repcallayout.setSpacing(3) repcallayout.addStretch(1) reportouterlayout = QHBoxLayout() reportouterlayout.addLayout(newreportlayout) reportouterlayout.addSpacing(10) reportouterlayout.addLayout(repcallayout) reportouterlayoutout = QVBoxLayout() reportouterlayoutout.addSpacing(15) reportouterlayoutout.addLayout(reportouterlayout) self.reporttab.setLayout(reportouterlayoutout) self.tabs.addTab(self.datapulltab, "Data Pull") self.tabs.addTab(self.reporttab, "Reporting") buttonlayout = QHBoxLayout() buttonlayout.addWidget(self.closebutton) buttonlayout.addWidget(self.submitbutton) self.statuslabel = QLabel(self) self.statuslabel.setText("Ready") self.statuslabel.setObjectName('statuslabel') self.statuslabel.setAlignment(Qt.AlignRight) outerlayout = QVBoxLayout() outerlayout.addWidget(self.tabs) outerlayout.addSpacing(15) outerlayout.addLayout(buttonlayout) outerlayout.addWidget(self.statuslabel) self.setLayout(outerlayout) self.current_report = False self.dframe = False self.reportcombochange() self.combochange() self.setWindowTitle('PIEthon: logged in as ' + self.username) self.setWindowIcon( QIcon(functions.resource_path('resources\\PIEcon.png'))) #style things self.setStyleSheet( open(functions.resource_path("resources\\iu_stylesheet.qss"), "r").read()) self.show() def center(self): qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def statusUpdate(self, newstat): #print('in status update') self.statuslabel.setText(newstat) QCoreApplication.processEvents() def startdatechange(self): self.startcombo.setCurrentIndex(0) self.startlabel.setText("Start Date: " + self.startcal.selectedDate().toString()) self.startreplabel.setText("Start Date: " + self.startcal.selectedDate().toString()) self.startrepcal.setSelectedDate(self.startcal.selectedDate()) def enddatechange(self): self.endcombo.setCurrentIndex(0) self.endlabel.setText("End Date: " + self.endcal.selectedDate().toString()) self.endreplabel.setText("End Date: " + self.endcal.selectedDate().toString()) self.endrepcal.setSelectedDate(self.endcal.selectedDate()) def startrepdatechange(self): self.startrepcombo.setCurrentIndex(0) self.startreplabel.setText("Start Date: " + self.startrepcal.selectedDate().toString()) self.startlabel.setText("Start Date: " + self.startrepcal.selectedDate().toString()) self.startcal.setSelectedDate(self.startrepcal.selectedDate()) def endrepdatechange(self): self.endrepcombo.setCurrentIndex(0) self.endreplabel.setText("End Date: " + self.endrepcal.selectedDate().toString()) self.endlabel.setText("End Date: " + self.endrepcal.selectedDate().toString()) self.endcal.setSelectedDate(self.endrepcal.selectedDate()) def startcomboselect(self): self.startrepcombo.setCurrentIndex(self.startcombo.currentIndex()) conv = self.semesters[self.startcombo.currentText()].getStart() if conv == '': return self.startlabel.setText("Start Date: " + conv.strftime('%a %b %d %Y')) self.startreplabel.setText("Start Date: " + conv.strftime('%a %b %d %Y')) self.startcal.setSelectedDate(conv) self.startrepcal.setSelectedDate(conv) def endcomboselect(self): self.endrepcombo.setCurrentIndex(self.endcombo.currentIndex()) conv = self.semesters[self.endcombo.currentText()].getEnd() if conv == '': return self.endlabel.setText("End Date: " + conv.strftime('%a %b %d %Y')) self.endreplabel.setText("End Date: " + conv.strftime('%a %b %d %Y')) self.endcal.setSelectedDate(conv) self.endrepcal.setSelectedDate(conv) def startrepcomboselect(self): self.startcombo.setCurrentIndex(self.startrepcombo.currentIndex()) conv = self.semesters[self.startrepcombo.currentText()].getStart() if conv == '': return self.startreplabel.setText("Start Date: " + conv.strftime('%a %b %d %Y')) self.startlabel.setText("Start Date: " + conv.strftime('%a %b %d %Y')) self.startrepcal.setSelectedDate(conv) self.startcal.setSelectedDate(conv) def endrepcomboselect(self): self.endcombo.setCurrentIndex(self.endrepcombo.currentIndex()) conv = self.semesters[self.endrepcombo.currentText()].getEnd() if conv == '': return self.endreplabel.setText("End Date: " + conv.strftime('%a %b %d %Y')) self.endlabel.setText("End Date: " + conv.strftime('%a %b %d %Y')) self.endrepcal.setSelectedDate(conv) self.endcal.setSelectedDate(conv) def reportcombochange(self): self.current_report = report.report_list[ self.reportdrop.currentIndex()] self.descbox.setText(self.current_report.description) self.reportactive.setText(str(self.current_report.active)) self.reportauthor.setText(str(self.current_report.author)) def combochange(self): datatype = self.dataoptions.get(self.datacombo.currentText()) if (datatype is None): return if (len(datatype.createdbyDict) > 1): self.usernamecombo.clear() self.usernamecombo.addItems(datatype.createdbyDict.keys()) self.usernamecombo.setEnabled(True) if datatype.createdbyPost: self.usernamelabel.setText("Created By (POST): ") else: self.usernamelabel.setText("Created By: ") else: self.usernamelabel.setText("Created By: ") self.usernamecombo.clear() self.usernamecombo.setEnabled(False) if (len(datatype.locationDict) > 1): self.locationcombo.clear() self.locationcombo.addItems(datatype.locationDict.keys()) self.locationcombo.setEnabled(True) if datatype.locationPost: self.locationlabel.setText("Location (POST): ") else: self.locationlabel.setText("Location: ") else: self.locationlabel.setText("Location: ") self.locationcombo.clear() self.locationcombo.setEnabled(False) if (len(datatype.statusDict) > 1): self.statuscombo.clear() self.statuscombo.addItems(datatype.statusDict) self.statuscombo.setEnabled(True) if datatype.statusPost: self.statuslabels.setText("Status (POST):") else: self.statuslabels.setText("Status:") else: self.statuslabels.setText("Status:") self.statuscombo.clear() self.statuscombo.setEnabled(False) if (len(datatype.categoryDict) > 1): self.categorycombo.clear() self.categorycombo.addItems(datatype.categoryDict.keys()) self.categorycombo.setEnabled(True) if datatype.categoryPost: self.categorylabel.setText("Category (POST):") else: self.categorylabel.setText("Category:") else: self.categorylabel.setText("Category:") self.categorycombo.clear() self.categorycombo.setEnabled(False) if (len(datatype.assignedToDict) > 1): self.assignedcombo.clear() self.assignedcombo.addItems(datatype.assignedToDict.keys()) self.assignedcombo.setEnabled(True) if datatype.assignedToPost: self.assignedlabel.setText("Assigned To (POST):") else: self.assignedlabel.setText("Assigned To:") else: self.assignedlabel.setText("Assigned To:") self.assignedcombo.clear() self.assignedcombo.setEnabled(False) self.endcal.setEnabled(datatype.allowDates) self.startcal.setEnabled(datatype.allowDates) self.startcombo.setEnabled(datatype.allowDates) self.endcombo.setEnabled(datatype.allowDates) def completed(self): self.statusUpdate('Ready') self.current_report.reset() if self.datecheck() or self.dframe is False: return if (self.tabs.currentIndex() == 0): self.mainwind = previewGui.preview( self.dframe, self.datacombo.currentText(), self.startcal.selectedDate().toPyDate(), self.endcal.selectedDate().toPyDate()) self.mainwind.show() self.dframe = False self.dataoptions.get(self.datacombo.currentText()).reset() self.current_report.reset() self.statusUpdate('Ready') def datecheck(self): return ((self.startcal.selectedDate().daysTo( self.endcal.selectedDate()) < 0) or (self.startrepcal.selectedDate().daysTo( self.endrepcal.selectedDate()) < 0))
class CurrencyConverter(QDialog): """ Currency Converter using PyQt5 The exchange rates are updated every days with Euro as reference """ def __init__(self): """ CurrencyConverter class initialization Set all the class variables like the labels and comboboxes that will be used in the initUI method """ super().__init__() self.rates = dict() self.currencies = list() self.getData() # Fetch the data from the csv online file # Initialization of the currencies choice dropdown boxes self.from_currency = QComboBox() self.from_currency.addItems(self.currencies) self.to_currency = QComboBox() self.to_currency.addItems(self.currencies) self.from_amount = QDoubleSpinBox() self.from_amount.setRange(0.01, 10000000.00) self.from_amount.setValue(1.00) self.to_amount = QLabel('1.00') self.from_currency_label = QLabel('From Currency:') self.to_currency_label = QLabel('To Currency:') self.from_amount_label = QLabel('Amount to convert:') self.to_amount_label = QLabel('Result of conversion based on most recent rates:') self.from_calendar = QCalendarWidget() self.to_calendar = QCalendarWidget() self.rates_plot = pg.PlotWidget() self.from_date = QDate() self.to_date = QDate() self.last_clicked = "" hint_font = QFont() hint_font.setItalic(True) self.graph_hint = QLabel('Hint: you can interact with the graph using your mouse') self.graph_hint.setFont(hint_font) self.initUI() def initUI(self): """ Positioning our differents widgets in our Layout and connect the widgets to their handler """ grid = QGridLayout() grid.addWidget(self.from_currency_label, 0, 0, Qt.AlignRight) grid.addWidget(self.from_currency, 0, 1) grid.addWidget(self.to_currency_label, 0, 2, Qt.AlignRight) grid.addWidget(self.to_currency, 0, 3) grid.addWidget(self.from_amount_label, 1, 0) grid.addWidget(self.from_amount, 1, 1) grid.addWidget(self.to_amount_label, 1, 2) grid.addWidget(self.to_amount, 1, 3) grid.addWidget(self.from_calendar, 2, 0, 1, 2) grid.addWidget(self.to_calendar, 2, 2, 1, 2) grid.addWidget(self.rates_plot, 3, 0, 1, 4) grid.addWidget(self.graph_hint, 4, 0, 1, 4) self.rates_plot.showGrid(x=True, y=True) self.rates_plot.setLabel('left', 'Rate') self.rates_plot.setLabel('bottom', 'Days') self.legend = self.rates_plot.addLegend() self.setLayout(grid) self.setWindowTitle('Currency Converter - Assignment 1 - Arnaud Bourget - 2981151') self.from_currency.currentIndexChanged.connect(self.updateUI) self.to_currency.currentIndexChanged.connect(self.updateUI) self.from_amount.valueChanged.connect(self.fromAmountHandler) self.from_calendar.selectionChanged.connect(self.fromCalendarHandler) self.to_calendar.selectionChanged.connect(self.toCalendarHandler) self.show() def fromAmountHandler(self): """ PyQt5 DoubleSpinBox Widget handler Allow to know that nothing in relationship with the graph changed """ self.last_clicked = "amount" self.updateUI() self.last_clicked = "" def fromCalendarHandler(self): """ PyQt5 Calendar Widget handler Allow to know which calendar was the last one used """ self.last_clicked = "from" self.updateUI() def toCalendarHandler(self): """ PyQt5 Calendar Widget handler Allow to know which calendar was the last one used """ self.last_clicked = "to" self.updateUI() def updateUI(self): """ PyQt5 Widgets handler This method fetches the information provided by the user and process them to get the conversion and the exchange rate graph """ try: # Getting the values selected by the user from_ = self.from_currency.currentText() to = self.to_currency.currentText() from_amt = Decimal(self.getMostRecentRelevantRate(self.rates[from_])) to_amt = Decimal(self.getMostRecentRelevantRate(self.rates[to])) amt = Decimal(self.from_amount.value()) # Calculating the new conversion value amount = (to_amt / from_amt) * amt self.to_amount.setText('%.02f' % amount) # Getting the dates selected by the user self.from_date = self.from_calendar.selectedDate().toPyDate() self.to_date = self.to_calendar.selectedDate().toPyDate() # Updating the graph only if something in relationship with it changes if self.last_clicked != 'amount': # Update the dates selected according to the user selection if the user selects a negative range if self.to_date < self.from_date: if self.last_clicked == 'from': date = self.from_calendar.selectedDate() self.to_calendar.setSelectedDate(date) self.to_date = date.toPyDate() else: date = self.to_calendar.selectedDate() self.from_calendar.setSelectedDate(date) self.from_date = date.toPyDate() # Getting and calculating the currencies rates according to the range selected by the user from_rates = self.getRatesInRange(self.rates[from_]) to_rates = self.getRatesInRange(self.rates[to]) conv_rates = self.getConvRates(from_rates, to_rates) # Getting the number of days included in the range nb_days = (self.to_date - self.from_date).days + 1 date_range = range(0, nb_days) # Clearing the graph and the legend self.rates_plot.clear() self.legend.scene().removeItem(self.legend) self.legend = self.rates_plot.addLegend() # Updating the graph with our new values self.rates_plot.setXRange(0, nb_days) self.rates_plot.setYRange(0, max(from_rates + to_rates + conv_rates)) self.rates_plot.plot(date_range, from_rates, pen='b', symbol='x', symbolPen='b', symbolBrush=0.2, name=from_) self.rates_plot.plot(date_range, to_rates, pen='r', symbol='o', symbolPen='r', symbolBrush=0.2, name=to) self.rates_plot.plot(date_range, conv_rates, pen='g', symbol='+', symbolPen='g', symbolBrush=0.2, name='conversion rate') except Exception as e: print('Failed to update UI') print(e) def getConvRates(self, from_rates, to_rates): """ Calculation of the conversion rates from from_rates to to_rates :param from_rates: (list) The rates of the currency we're conversing from :param to_rates: (list) The rates to the currency we're conversing to :return: (list) The conversion rates """ conv_rates = list() try: for i in range(len(from_rates)): conv_rates.append(to_rates[i] / from_rates[i] if from_rates[i] != 0 else 0) except Exception as e: print('Could not calculate the conversion rate') print(e) return conv_rates def getMostRecentRelevantRate(self, currency_rates, reference_date=QDate.currentDate().toPyDate()): """ Retrieve the most recent relevant rate from the rates provided and according to the reference date :param currency_rates: (dictionary) The different rates of a currency ordered by date :param reference_date: (datetime.date, optional) The reference date that defines from when we're looking for :return: (string) The first relevant rate of the rates provided """ try: for date in currency_rates: if QDate.fromString(date, "yyyy-MM-dd").toPyDate() <= reference_date and currency_rates[date] != 'N/A': return currency_rates[date] except Exception as e: print('Could not retrieve any relevant rate') print(e) def getRatesInRange(self, currency_rates): """ For each date between from_date and to_date, we retrieve the most recent rate :param currency_rates: (dictionary) The different rates of a currency ordered by date :return: (list) The list of the rates for everyday between from_date and to_date """ rates = list() try: date = self.from_date while date <= self.to_date: rates.append(float(self.getMostRecentRelevantRate(currency_rates, date))) date += timedelta(days=1) except Exception as e: print('Could not retrieve rates') print(e) rates.reverse() return rates def getData(self): """ Download the currency rates zipfile and process it into a dict """ url = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist.zip' try: file, _ = urlretrieve(url) zip_file_object = zipfile.ZipFile(file, 'r') first_file = zip_file_object.namelist()[0] file = zip_file_object.open(first_file) file_handler = [] for row in file: file_handler.append(row.decode()) # getting the currency headers into header_list header_list = [] notFound = True x = 0 while notFound: if file_handler[x].startswith('Date'): header = file_handler[x].split(',') for col in header: header_list.append(col.strip()) notFound = False x += 1 self.currencies = list(filter(None, header_list)) self.currencies.append('EUR') self.currencies = self.currencies[1:] # Removing the "Date" entry data = [] for row in file_handler[x:]: if row.startswith('`\n'): break else: data.append(list(filter(None, [x.replace('\n', '') for x in row.split(',')]))) # Removing any empty extra columns at the end of each rows # filling my self.rates with the currency in the format {CURR: {date: rate, ...}, ...} for row in data: for i in range(len(self.currencies)): try: if self.currencies[i] not in self.rates: self.rates[self.currencies[i]] = {row[0]: row[i + 1]} else: self.rates[self.currencies[i]].update({row[0]: row[i + 1]}) except IndexError: # We reached the EUR section if self.currencies[i] not in self.rates: self.rates[self.currencies[i]] = {row[0]: '1.0000'} else: self.rates[self.currencies[i]].update({row[0]: '1.0000'}) self.currencies.sort() except Exception as e: print('Failed to process the data') print(e) finally: file.close()
class OutcomeEventClaster(QDialog): def __init__(self, header, outComeEventNames, outComeCategory, units, currency, parent = None): QDialog.__init__(self, parent) self._acceptState = False self._dataContainer = {} self._header = header self._Currency = currency self._units = units self._category = outComeCategory self._EventNames = outComeEventNames self.InitUI() self.addRowWidgets() self.show() #++++++++++++++++++++++++++++++ InitUI ++++++++++++++++++++++++++++++++ def InitUI(self): self.setWindowTitle("მონაცემთა შეტანა") self.setWindowIcon(QtGui.QIcon("icon/outcome.svg")) self.setFixedSize(1300, 900) vbox = QVBoxLayout() hbox = QHBoxLayout() vbox.setContentsMargins(2, 2, 2, 2) ############################## Calendar ############################### self.calendar = QCalendarWidget() self.calendar.setGridVisible(True) self.calendar.setFirstDayOfWeek(Qt.Monday) ############################### Table ################################# self.table = QTableWidget() self.table.setRowCount(1) self.table.setColumnCount(len(self._header)) self.table.setHorizontalHeaderLabels(self._header) self.table.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents) self.table.resizeRowsToContents() self.table.setSortingEnabled(False) self.table.setWordWrap(True) self.rowNumb = self.table.rowCount()-1 ############################## add Row ################################ self.addRowButton = QPushButton('დამატება') self.addRowButton.setMaximumWidth(100) self.addRowButton.setIcon(QIcon('icon/addRow.svg')) self.addRowButton.clicked.connect(self.addRow) ############################## del Row ################################ self.delRowButton = QPushButton('წაშლა') self.delRowButton.setMaximumWidth(100) self.delRowButton.setIcon(QIcon('icon/DelRow.svg')) self.delRowButton.clicked.connect(self.delRow) ############################### test ################################## sumHboxLayout = QHBoxLayout() self.sumMoney = QLineEdit() self.equivalentSumMoney = QLineEdit() sumHboxLayout.addWidget(self.sumMoney) sumHboxLayout.addWidget(self.equivalentSumMoney) self.testButton = QPushButton('ტესტი') self.testButton.setIcon(QIcon('icon/test.png')) self.testButton.clicked.connect(self.test) ############################## Accept ################################# self.acceptButton = QPushButton('დადასტურება', self) self.acceptButton.clicked.connect(self.acceptDialog) ############################## Reject ################################# self.rejectButton = QPushButton('გაუქმება', self) self.rejectButton.clicked.connect(self.rejectDialog) ###################### Add widgets on layouts ######################### hbox.addWidget(self.addRowButton) hbox.addWidget(self.delRowButton) vbox.addWidget(self.calendar,5) vbox.addWidget(self.table,90) vbox.addLayout(hbox) vbox.addLayout(sumHboxLayout) vbox.addWidget(self.testButton,5) hboxAcceptReject = QHBoxLayout() hboxAcceptReject.addWidget(self.acceptButton) hboxAcceptReject.addWidget(self.rejectButton) vbox.addLayout(hboxAcceptReject) self.setLayout(vbox) #++++++++++++++++++++++++++++ Add Row +++++++++++++++++++++++++++++++++ def addRow(self): self.rowNumb = self.table.rowCount() self.table.insertRow(self.rowNumb) self.addRowWidgets() #++++++++++++++++++++++++ Add Row Widgets +++++++++++++++++++++++++++++ def addRowWidgets(self): ########################### emountEdit ################################ quantityEdit = QLineEdit('1') quantityEdit.setValidator(QDoubleValidator()) quantityEdit.setMaximumWidth(30) units = QComboBox() units.setToolTip("<h5>ერთეული") units.setMaximumWidth(70) units.addItems(self._units) quantityEditHlayout = QHBoxLayout() quantityEditHlayout.addWidget(quantityEdit,20) quantityEditHlayout.addWidget(units,80) quantityEditWidgets = QWidget() quantityEditWidgets.setLayout(quantityEditHlayout) ####################### Category Selector ############################# outcomeCategorySelector = QComboBox() outcomeCategorySelector.addItems(self._category) ########################## Price Editor ############################### PriceEdit = QLineEdit() PriceEdit.setValidator(QDoubleValidator()) PriceEdit.setToolTip("<h5>გადახდა") PriceEdit.setMaximumWidth(70) #################### Equivalent Price Editor ########################## equivalentPriceEdit = QLineEdit() equivalentPriceEdit.setValidator(QDoubleValidator()) equivalentPriceEdit.setText("--") equivalentPriceEdit.setToolTip("<h5>კონვერტაცია ვალუტაში") equivalentPriceEdit.setMaximumWidth(70) ####################### Currency Selector ############################# CurrencySelector = QComboBox() for idx, key in enumerate(self._Currency): CurrencySelector.addItem(key) CurrencySelector.setItemData(idx, Qt.AlignCenter, Qt.TextAlignmentRole) CurrencySelector.setItemIcon(idx, QtGui.QIcon(self._Currency[key])) ################# Equivalent Currency Selector ######################## EqviCurrencySelector = QComboBox() for idx, key in enumerate(self._Currency): EqviCurrencySelector.addItem(key) EqviCurrencySelector.setItemData(idx, Qt.AlignCenter, Qt.TextAlignmentRole) EqviCurrencySelector.setItemIcon(idx, QtGui.QIcon(self._Currency[key])) ###################### App widgets in cells ########################### priceHlayout = QHBoxLayout() priceHlayout.addWidget(PriceEdit) priceHlayout.addWidget(CurrencySelector) priceHlayout.addWidget(equivalentPriceEdit) priceHlayout.addWidget(EqviCurrencySelector) priceWidgets = QWidget() priceWidgets.setLayout(priceHlayout) PayMethodWidgets = QWidget() PayMethod = QCheckBox() PayMethod.setToolTip("<h5>ნაღდით გადახდა") PayMethodHlayout = QHBoxLayout() PayMethodHlayout.addWidget(PayMethod) PayMethodHlayout.setAlignment( Qt.AlignCenter ) PayMethodWidgets.setLayout(PayMethodHlayout) eventContent = QTableWidgetItem('') self.table.setItem(self.rowNumb, 0, eventContent) eventContent.setData(Qt.UserRole, random.sample(self._EventNames, len(self._EventNames))) self.table.setItemDelegate(TableItemCompleter(self.table)) self.table.setCellWidget(self.rowNumb, 1, quantityEditWidgets) self.table.setCellWidget(self.rowNumb, 2, outcomeCategorySelector) self.table.setCellWidget(self.rowNumb, 3, priceWidgets) self.table.setCellWidget(self.rowNumb, 4, PayMethodWidgets) ###################### Set Table Cell Widths ########################## self.table.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents) self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch) self.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeToContents) self.table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeToContents) self.table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeToContents) self.table.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeToContents) # +++++++++++++ String to float number formater +++++++++++++++++++++++ def _stingToFloatFormater(self, value): if ',' in value: value = value.replace(",", ".") return value else: return value #++++++++++++++++++++++++++ Delete Row ++++++++++++++++++++++++++++++++ def delRow(self): self.rowNumb = self.table.rowCount() if self.rowNumb > 1: selected_Row = self.table.currentRow() self.table.removeRow(selected_Row) #++++++++++++++++++++++ Set calendar date +++++++++++++++++++++++++++++ def setCalendarDate(self, date): self.calendar.setSelectedDate(QDate(date[0], date[1], date[2])) #++++++++++++++++++++++ Make data claster +++++++++++++++++++++++++++++ def makeDataClaster(self): self._dataContainer = {} dataContainerArray = [] self.rowNumb = self.table.rowCount() self.colNumb = self.table.columnCount() for row in range(self.rowNumb): dataContainerTemp = [] for column in range(self.colNumb): if column == 0: dataContainerTemp.append({'cell_0' : self.table.item(row,column).text()}) elif column == 1: dataContainerTemp.append({'cell_1.1' : self._stingToFloatFormater(self.table.cellWidget(row,column).children()[1].text()), 'cell_1.2' : self.table.cellWidget(row,column).children()[2].currentIndex()}) elif column == 2: dataContainerTemp.append({'cell_2.1' : self.table.cellWidget(row,column).currentIndex()}) elif column == 3: dataContainerTemp.append({'cell_3.1' : self._stingToFloatFormater(self.table.cellWidget(row,column).children()[1].text()), 'cell_3.2' : self.table.cellWidget(row,column).children()[2].currentIndex(), 'cell_3.3' : self._stingToFloatFormater(self.table.cellWidget(row,column).children()[3].text()), 'cell_3.4' : self.table.cellWidget(row,column).children()[4].currentIndex()}) elif column == 4: dataContainerTemp.append({'cell_4' : self.table.cellWidget(row,column).children()[1].isChecked()}) dataContainerArray.append(dataContainerTemp) self._dataContainer.update({self.calendar.selectedDate().toString("dd.MM.yyyy") : dataContainerArray}) #++++++++++++++++++++++ Edit data claster +++++++++++++++++++++++++++++ def EditDataClaster(self, DataClasterComponent, timeStamp): for _ in range(len(DataClasterComponent)-1): self.addRow() self.setCalendarDate(QDate.fromString(timeStamp, 'dd.MM.yyyy').getDate()) for row in range(len(DataClasterComponent)): self.table.item(row, 0).setText(DataClasterComponent[row][0]['cell_0']) self.table.cellWidget(row, 1).children()[1].setText(DataClasterComponent[row][1]['cell_1.1']) self.table.cellWidget(row, 1).children()[2].setCurrentIndex(DataClasterComponent[row][1]['cell_1.2']) self.table.cellWidget(row, 2).setCurrentIndex(DataClasterComponent[row][2]['cell_2.1']) self.table.cellWidget(row, 3).children()[1].setText(DataClasterComponent[row][3]['cell_3.1']) self.table.cellWidget(row, 3).children()[2].setCurrentIndex(DataClasterComponent[row][3]['cell_3.2']) self.table.cellWidget(row, 3).children()[3].setText(DataClasterComponent[row][3]['cell_3.3']) self.table.cellWidget(row, 3).children()[4].setCurrentIndex(DataClasterComponent[row][3]['cell_3.4']) self.table.cellWidget(row, 4).children()[1].setChecked(DataClasterComponent[row][4]['cell_4']) #+++++++++++++++++++++++++++ Accept +++++++++++++++++++++++++++++++++++ def acceptDialog(self): self.makeDataClaster() self._acceptState = True self.close() #+++++++++++++++++++++++++++ Reject +++++++++++++++++++++++++++++++++++ def rejectDialog(self): self._acceptState = False self.close() #++++++++++++++++++++ Get data claster part +++++++++++++++++++++++++++ def getDataClasterPart(self): return self._dataContainer, self._acceptState #++++++++++++++++++++++++++++ Test ++++++++++++++++++++++++++++++++++++ def test(self): print("Test") data = {'22.01.1993': [ [ {'cell_0': 'პური'}, {'cell_1.1': '2', 'cell_1.2': 1}, {'cell_2.1': 2}, { 'cell_3.1': '30', 'cell_3.2': 1, 'cell_3.3': '100', 'cell_3.4': 0}, {'cell_4': True}], [ {'cell_0': 'ლობიო'}, {'cell_1.1': '5', 'cell_1.2': 1}, {'cell_2.1': 3}, { 'cell_3.1': '64', 'cell_3.2': 2, 'cell_3.3': '54', 'cell_3.4': 3}, {'cell_4': True}]]} #self.EditDataClaster(data) self.makeDataClaster() self.rowNumb = self.table.rowCount() sumMoney = 0 equiSumMoney = 0 for row in range(self.rowNumb): try: sumMoney = sumMoney + round(float(self.table.cellWidget(row,3).children()[1].text()), 2) except ValueError: pass try: equiSumMoney = equiSumMoney + round(float(self.table.cellWidget(row,3).children()[3].text()), 2) except ValueError: pass self.sumMoney.setText(str(sumMoney)) self.equivalentSumMoney.setText(str(equiSumMoney))
class IncomeEventClaster(QDialog): def __init__(self, header, IncomeSourceCategory, currency, parent = None): QDialog.__init__(self, parent) self._acceptState = False self._dataContainer = {} self._header = header self._IncomeSourceCategory = IncomeSourceCategory self._Currency = currency self.date = [1993,1,22] self.InitUI() self.addRowWidgets() self.show() #+++++++++++++++++++++++++++ InitUI +++++++++++++++++++++++++++++++++++ def InitUI(self): self.setWindowTitle("მონაცემთა შეტანა") self.setWindowIcon(QtGui.QIcon("icon/income.svg")) self.setFixedSize(750, 900) vbox = QVBoxLayout() hbox = QHBoxLayout() vbox.setContentsMargins(2, 2, 2, 2) ########################### Calendar ################################## self.calendar = QCalendarWidget() self.calendar.setGridVisible(True) self.calendar.setFirstDayOfWeek(Qt.Monday) ############################ Table #################################### self.table = QTableWidget() self.table.setRowCount(1) self.table.setColumnCount(len(self._header)) self.table.setHorizontalHeaderLabels(self._header) self.table.setSortingEnabled(False) self.table.setWordWrap(True) self.rowNumb = self.table.rowCount()-1 ########################### add Row ################################### self.addRowButton = QPushButton('დამატება') self.addRowButton.setMaximumWidth(100) self.addRowButton.setIcon(QIcon('icon/addRow.svg')) self.addRowButton.clicked.connect(self.addRow) ########################### del Row ################################### self.delRowButton = QPushButton('წაშლა') self.delRowButton.setMaximumWidth(100) self.delRowButton.setIcon(QIcon('icon/DelRow.svg')) self.delRowButton.clicked.connect(self.delRow) ############################# test #################################### self.testButton = QPushButton('ტესტი') self.testButton.setIcon(QIcon('icon/test.png')) self.testButton.clicked.connect(self.test) ############################ Accept ################################### self.acceptButton = QPushButton('დადასტურება', self) self.acceptButton.clicked.connect(self.acceptDialog) ############################ Reject ################################### self.rejectButton = QPushButton('გაუქმება', self) self.rejectButton.clicked.connect(self.rejectDialog) #################### Add widgets on layouts ########################### hbox.addWidget(self.addRowButton) hbox.addWidget(self.delRowButton) vbox.addWidget(self.calendar,5) vbox.addWidget(self.table,90) vbox.addLayout(hbox) vbox.addWidget(self.testButton,5) hboxAcceptReject = QHBoxLayout() hboxAcceptReject.addWidget(self.acceptButton) hboxAcceptReject.addWidget(self.rejectButton) vbox.addLayout(hboxAcceptReject) self.setLayout(vbox) #++++++++++++++++++++++++++ Add Row +++++++++++++++++++++++++++++++++++ def addRow(self): self.rowNumb = self.table.rowCount() self.table.insertRow(self.rowNumb) self.addRowWidgets() #++++++++++++++++++++++ Add Row Widgets +++++++++++++++++++++++++++++++ def addRowWidgets(self): ########################## emountEdit ################################# quantityEdit = QLineEdit('') quantityEdit.setValidator(QDoubleValidator()) ###################### Currency Selector ############################## CurrencySelector = QComboBox() for idx, key in enumerate(self._Currency): CurrencySelector.addItem(key) CurrencySelector.setItemData(idx, Qt.AlignCenter, Qt.TextAlignmentRole) CurrencySelector.setItemIcon(idx, QtGui.QIcon(self._Currency[key])) quantityEditHlayout = QHBoxLayout() quantityEditHlayout.addWidget(quantityEdit,50) quantityEditHlayout.addWidget(CurrencySelector,50) quantityEditWidgets = QWidget() quantityEditWidgets.setLayout(quantityEditHlayout) ################## Income Category Selector ########################### incomeCategorySelector = QComboBox() incomeCategorySelector.addItems(self._IncomeSourceCategory) self.table.setCellWidget(self.rowNumb, 0, incomeCategorySelector) self.table.setCellWidget(self.rowNumb, 1, quantityEditWidgets) self.table.cellWidget(self.rowNumb,0).activated.connect(self.incomeCategoryFormater) ################### Set Table Cell Widths ############################# self.table.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents) self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch) self.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch) # +++++++++++++ String to float number formater +++++++++++++++++++++++ def _stingToFloatFormater(self, value): if ',' in value: value = value.replace(",", ".") return value else: return value #++++++++++++++++++++++++ Delete Row ++++++++++++++++++++++++++++++++++ def delRow(self): self.rowNumb = self.table.rowCount() if self.rowNumb > 1: selected_Row = self.table.currentRow() self.table.removeRow(selected_Row) self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch) self.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch) #+++++++++++++++++++++ Set calendar date ++++++++++++++++++++++++++++++ def setCalendarDate(self, date): self.calendar.setSelectedDate(QDate(date[0], date[1], date[2])) #+++++++++++++++++++++ Make data claster ++++++++++++++++++++++++++++++ def makeDataClaster(self): self._dataContainer = {} dataContainerArray = [] self.rowNumb = self.table.rowCount() self.colNumb = self.table.columnCount() for row in range(self.rowNumb): dataContainerTemp = [] for column in range(self.colNumb): if column == 0: dataContainerTemp.append({'cell_0' : self.table.cellWidget(row,column).currentIndex()}) elif column == 1: if len(self.table.cellWidget(row, 1).children()[0]) == 2: dataContainerTemp.append({'cell_1.1' : self.table.cellWidget(row,column).children()[1].text(), 'cell_1.2' : self.table.cellWidget(row,column).children()[2].currentIndex()}) elif len(self.table.cellWidget(row, 1).children()[0]) == 4: dataContainerTemp.append({'cell_1.1' : self._stingToFloatFormater(self.table.cellWidget(row,column).children()[1].text()), 'cell_1.2' : self.table.cellWidget(row,column).children()[2].currentIndex(), 'cell_1.3' : self._stingToFloatFormater(self.table.cellWidget(row,column).children()[3].text()), 'cell_1.4' : self.table.cellWidget(row,column).children()[4].currentIndex()}) dataContainerArray.append(dataContainerTemp) self._dataContainer.update({self.calendar.selectedDate().toString("dd.MM.yyyy") : dataContainerArray}) #+++++++++++++++++++++ Edit data claster ++++++++++++++++++++++++++++++ def EditDataClaster(self, DataClasterComponent, timeStamp): for _ in range(len(DataClasterComponent)-1): self.addRow() self.setCalendarDate(QDate.fromString(timeStamp, 'dd.MM.yyyy').getDate()) for row, rowData in enumerate(DataClasterComponent): self.table.cellWidget(row, 0).setCurrentIndex(rowData[0]['cell_0']) self.table.cellWidget(row, 1).children()[1].setText(rowData[1]['cell_1.1']) self.table.cellWidget(row, 1).children()[2].setCurrentIndex(rowData[1]['cell_1.2']) if len(rowData[1]) == 4: quantityEdit = QLineEdit('') quantityEdit.setValidator(QDoubleValidator()) CurrencySelector = QComboBox() for idx, key in enumerate(self._Currency): CurrencySelector.addItem(key) CurrencySelector.setItemData(idx, Qt.AlignCenter, Qt.TextAlignmentRole) CurrencySelector.setItemIcon(idx, QtGui.QIcon(self._Currency[key])) self.table.cellWidget(row, 1).children()[0].addWidget(quantityEdit,50) self.table.cellWidget(row, 1).children()[0].addWidget(CurrencySelector,50) self.table.cellWidget(row, 1).children()[3].setText(rowData[1]['cell_1.3']) self.table.cellWidget(row, 1).children()[4].setCurrentIndex(rowData[1]['cell_1.4']) self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch) self.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch) #++++++++++++++++++++++++++ Accept ++++++++++++++++++++++++++++++++++++ def acceptDialog(self): self.makeDataClaster() self._acceptState = True self.close() #++++++++++++++++++++++++++ Reject ++++++++++++++++++++++++++++++++++++ def rejectDialog(self): self._acceptState = False self.close() #++++++++++++++++++ Get data claster part +++++++++++++++++++++++++++++ def getDataClasterPart(self): return self._dataContainer, self._acceptState #++++++++++++++++++ incomeCategoryFormater ++++++++++++++++++++++++++++ def incomeCategoryFormater(self): changedSelectrorIndex = self.sender() self.rowNumb = self.table.rowCount() for row in range (self.rowNumb): if self.table.cellWidget(row,0) == changedSelectrorIndex: if self.table.cellWidget(row,0).currentIndex() == 7: if len(self.table.cellWidget(row, 1).children()[0]) == 2: quantityEdit = QLineEdit('') quantityEdit.setValidator(QDoubleValidator()) CurrencySelector = QComboBox() for idx, key in enumerate(self._Currency): CurrencySelector.addItem(key) CurrencySelector.setItemData(idx, Qt.AlignCenter, Qt.TextAlignmentRole) CurrencySelector.setItemIcon(idx, QtGui.QIcon(self._Currency[key])) self.table.cellWidget(row, 1).children()[0].addWidget(quantityEdit,50) self.table.cellWidget(row, 1).children()[0].addWidget(CurrencySelector,50) else: try: self.table.cellWidget(row, 1).children()[0].itemAt(2).widget().deleteLater() self.table.cellWidget(row, 1).children()[0].itemAt(3).widget().deleteLater() except AttributeError: pass self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch) self.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch) def read(self): return self._dataContainer #+++++++++++++++++++++++++++ Test +++++++++++++++++++++++++++++++++++++ def test(self): print("Test") self.makeDataClaster()
class SideBar(QWidget): data_filtered_signal = pyqtSignal(pd.DataFrame) new_indicator_created_signal = pyqtSignal() def __init__(self, config): super().__init__() self.config = config self.cleaned_data = None self.filtered_data = None self.min_value = None self.max_value = None self.min_value_is_valid = True self.max_value_is_valid = True self.is_data_loaded = False self.filter_values = None self.cleaned_data = None self.min_date_selector = QCalendarWidget(self) self.max_date_selector = QCalendarWidget(self) self.target_line = QLineEdit(self) self.account_number_line = QLineEdit(self) self.message_line = QLineEdit(self) self.event_line = QLineEdit(self) self.category_line = QLineEdit(self) self.min_value_line = FloatLineEdit(self) self.max_value_line = FloatLineEdit(self) self.load_button = QPushButton('Load data') self.create_indicator_button = QPushButton('Create indicator from existing filters') self.create_category_button = QPushButton('Create category from existing filters') self._set_layout() self._set_connections() def _set_layout(self): self.layout = QVBoxLayout() self.layout.addWidget(QLabel('Min date')) self.layout.addWidget(self.min_date_selector) self.layout.addWidget(QLabel('Max date')) self.layout.addWidget(self.max_date_selector) layout = QHBoxLayout() layout.addWidget(QLabel('Min value')) layout.addWidget(self.min_value_line) layout.addWidget(QLabel('Max value')) layout.addWidget(self.max_value_line) self.layout.addLayout(layout) self.layout.addWidget(QLabel('Target contains (regexp pattern)')) self.layout.addWidget(self.target_line) self.layout.addWidget(QLabel('Account number contains (regexp pattern)')) self.layout.addWidget(self.account_number_line) self.layout.addWidget(QLabel('Message contains (regexp pattern)')) self.layout.addWidget(self.message_line) self.layout.addWidget(QLabel('Event contains (regexp pattern)')) self.layout.addWidget(self.event_line) self.layout.addWidget(QLabel('Category contains (regexp pattern)')) self.layout.addWidget(self.category_line) self.layout.addWidget(self.load_button) self.layout.addWidget(self.create_indicator_button) self.layout.addWidget(self.create_category_button) def _set_connections(self): self.load_button.clicked.connect(self._handle_load_button_clicked) self.create_indicator_button.clicked.connect(self._handle_create_new_indicator) self.create_category_button.clicked.connect(self._handle_create_new_category) self.min_value_line.textChanged.connect(self._handle_min_value_changed) self.max_value_line.textChanged.connect(self._handle_max_value_changed) self.min_date_selector.selectionChanged.connect(self._handle_filter_data) self.max_date_selector.selectionChanged.connect(self._handle_filter_data) self.min_value_line.returnPressed.connect(self._handle_filter_data) self.max_value_line.returnPressed.connect(self._handle_filter_data) self.target_line.returnPressed.connect(self._handle_filter_data) self.account_number_line.returnPressed.connect(self._handle_filter_data) self.message_line.returnPressed.connect(self._handle_filter_data) self.event_line.returnPressed.connect(self._handle_filter_data) self.category_line.returnPressed.connect(self._handle_filter_data) def _handle_load_button_clicked(self): self.file_paths = self._get_file_paths() if not self.file_paths: return None self.load_data() def load_data(self): bank = get_bank(self.config["bank"]) self.cleaned_data = prepare_data(file_paths=self.file_paths, data_loader=bank.loader, data_transformer=bank.transformer, drop_data=self.config["drop_data"], categories=self.config["categories"]) self._set_dates_based_on_data() self.is_data_loaded = True self._handle_filter_data() def _set_dates_based_on_data(self): datetime_min = self.cleaned_data.time.min() datetime_max = self.cleaned_data.time.max() self.min_date_selector.setSelectedDate(QtCore.QDate(datetime_min.year, datetime_min.month, datetime_min.day)) self.max_date_selector.setSelectedDate(QtCore.QDate(datetime_max.year, datetime_max.month, datetime_max.day)) def _update_filtering_values(self): self.filter_values = dict( min_date=self._get_min_date(), max_date=self._get_max_date(), target=self._get_target(), account_number=self._get_account_number(), message=self._get_message(), event=self._get_event(), min_value=self.min_value, max_value=self.max_value, category=self._get_category() ) def _handle_filter_data(self): self._update_filtering_values() if self.cleaned_data is not None: self.filtered_data = filter_data(self.cleaned_data, **self.filter_values) if self.filtered_data.empty: show_warning("Warning", "No data to analyze") else: self.data_filtered_signal.emit(self.filtered_data) def _update_categories(self): self.cleaned_data["categories"] = categorize(self.cleaned_data, self.config["categories"]) self._handle_filter_data() def _handle_create_new_indicator(self): name, ok = QInputDialog.getText(self, 'New indicator', 'Type the name of new indicator') if not ok: return try: new_indicators = self._write_filtering_values_to_file(self.config["paths"]["indicators"], name) self.config["indicators"] = new_indicators self.new_indicator_created_signal.emit() except Exception as e: print(e) show_warning("Indicator creation failure", "Something went wrong") def _handle_create_new_category(self): name, ok = QInputDialog.getText(self, 'New category', 'Type the name of new category') if not ok: return try: new_categories = self._write_filtering_values_to_file(self.config["paths"]["categories"], name) self.config["categories"] = new_categories self._update_categories() except Exception as e: print(e) show_warning("Category creation failure", "Something went wrong") def _write_filtering_values_to_file(self, file_path, name): self._update_filtering_values() filter_values = {k: v for k, v in self.filter_values.items() if v != "" and pd.notnull(v)} filter_values.pop("min_date", None) filter_values.pop("max_date", None) values = load_json(file_path) values[name] = filter_values save_json(file_path, values) return values def _get_file_paths(self) -> List[str]: file_paths, _ = QFileDialog.getOpenFileNames(caption='Choose files for analysis', directory=self.config["default_data_dir"]) return file_paths def _get_min_date(self) -> datetime: return self.min_date_selector.selectedDate().toPyDate() def _get_max_date(self) -> datetime: return self.max_date_selector.selectedDate().toPyDate() def _get_target(self) -> str: return self.target_line.text() def _get_account_number(self) -> str: return self.account_number_line.text() def _get_message(self) -> str: return self.message_line.text() def _get_event(self) -> str: return self.event_line.text() def _get_category(self) -> str: return self.category_line.text() def _handle_min_value_changed(self): self.min_value, self.min_value_is_valid = self.min_value_line.get_value() def _handle_max_value_changed(self): self.max_value, self.max_value_is_valid = self.max_value_line.get_value()
class CalendarDemo(QWidget): current_day = datetime.now().day current_month = datetime.now().month current_year = datetime.now().year start_date = date(year=current_year, month=current_month, day=current_day) end_date = date(year=current_year, month=current_month, day=current_day) def __init__(self): super().__init__() self.setWindowTitle('K Powerball') self.setGeometry(500, 500, 600, 300) self.initUI() def initUI(self): self.calendar = QCalendarWidget(self) self.calendar.move(20, 20) self.calendar.setGridVisible(True) self.calendar.setMinimumDate( QDate(self.current_year, self.current_month - 1, 1)) self.calendar.setMaximumDate( QDate( self.current_year, self.current_month + 1, calendar.monthrange(self.current_year, self.current_month)[1])) self.calendar.setSelectedDate( QDate(self.current_year, self.current_month, 1)) self.calendar.clicked.connect(self.set_start_date) self.calendar_2 = QCalendarWidget(self) self.calendar_2.move(300, 20) self.calendar_2.setGridVisible(True) self.calendar_2.setMinimumDate( QDate(self.current_year, self.current_month - 1, 1)) self.calendar_2.setMaximumDate( QDate( self.current_year, self.current_month + 1, calendar.monthrange(self.current_year, self.current_month)[1])) self.calendar_2.setSelectedDate( QDate(self.current_year, self.current_month, 1)) self.calendar_2.clicked.connect(self.set_end_date) self.btn2 = QPushButton(self) self.btn2.move(20, 200) self.btn2.setText('다운로드') self.btn2.clicked.connect(self.download_excel) def set_start_date(self, qDate): self.start_date = date(year=qDate.year(), month=qDate.month(), day=qDate.day()) def set_end_date(self, qDate): self.end_date = date(year=qDate.year(), month=qDate.month(), day=qDate.day()) def download_excel(self): print(f'{self.start_date} ~ {self.end_date}') try: # powerball_download(self.start_date, self.end_date) powerball_download(date(2018, 1, 1), date(2020, 5, 6)) QMessageBox.about(self, "Info", "다운로드 완료") except: QMessageBox.about(self, "Info", "다운로드 실패")
class MyWidget(QWidget): def __init__(self, parent=None): super().__init__(parent) horizontalLayout = QHBoxLayout() self.dayView = QTableView() self.dayView.setFrameShape(QFrame.Box) self.dayView.horizontalHeader().setStretchLastSection(True) self.dayView.verticalHeader().setVisible(False) horizontalLayout.addWidget(self.dayView) verticalLayout = QVBoxLayout() self.calendarWidget = QCalendarWidget() self.calendarWidget.setMinimumSize(QSize(250, 200)) self.calendarWidget.setMaximumSize(QSize(250, 200)) self.calendarWidget.setMinimumDate(QDate(2017, 1, 1)) self.calendarWidget.setMaximumDate(QDate(2030, 1, 1)) self.calendarWidget.selectionChanged.connect(self.dataChange) self.calendarWidget.setSelectedDate(QDate.currentDate()) verticalLayout.addWidget(self.calendarWidget) titleFV = QLabel('Food View') verticalLayout.addWidget(titleFV) self.filterLine = QLineEdit() self.filterLine.setMaximumSize(QSize(200, 25)) self.filterLine.textChanged.connect(self.filterChange) buttonAdd = QPushButton(QIcon("images/add.png"), '', None) buttonAdd.setMaximumSize(QSize(20, 30)) buttonAdd.clicked.connect(self.addFood) buttonDell = QPushButton(QIcon("images/del.png"), '', None) buttonDell.setMaximumSize(QSize(20, 30)) buttonDell.clicked.connect(self.delFood) lineEditLayout = QHBoxLayout() lineEditLayout.addWidget(self.filterLine) lineEditLayout.addWidget(buttonAdd) lineEditLayout.addWidget(buttonDell) verticalLayout.addLayout(lineEditLayout) self.foodView = QTableView() self.foodView.setMinimumSize(QSize(0, 0)) self.foodView.setMaximumSize(QSize(250, 1000)) self.foodView.verticalHeader().setVisible(False) self.foodView.horizontalHeader().setStretchLastSection(True) verticalLayout.addWidget(self.foodView) horizontalLayout.addLayout(verticalLayout) self.setLayout(horizontalLayout) model_in = QSqlRelationalTableModel() model_in.setEditStrategy(QSqlTableModel.OnFieldChange) model_in.setTable("intake_food") id_food = model_in.fieldIndex("id_food") date = model_in.fieldIndex("food_date") mass = model_in.fieldIndex("mass") # Set model, hide ID column model_in.setRelation(id_food, QSqlRelation("food", "id", "name")) model_in.setHeaderData(id_food, Qt.Horizontal, "Food") model_in.setHeaderData(date, Qt.Horizontal, "Date") model_in.setHeaderData(mass, Qt.Horizontal, "Mass") if not model_in.select(): self.showError(model_in.lastError()) return self.proxyModel_in = QSortFilterProxyModel() self.proxyModel_in.setSourceModel(model_in) self.proxyModel_in.setFilterKeyColumn(2) self.dayView.setItemDelegate(FlipProxyDelegate()) self.dayView.setModel(self.proxyModel_in) self.dayView.setColumnHidden(0, True) self.dayView.setColumnHidden(2, True) self.dayView.setSelectionMode(QAbstractItemView.SingleSelection) self.dayView.setContextMenuPolicy(Qt.CustomContextMenu) self.dayView.customContextMenuRequested.connect(self.ShowContextMenu) # filter day food by calendar widget self.dataChange() self.model_f = QSqlRelationalTableModel() self.model_f.setEditStrategy(QSqlTableModel.OnFieldChange) self.model_f.setTable("food") self.model_f.setHeaderData(1, Qt.Horizontal, "Food") self.model_f.setHeaderData(2, Qt.Horizontal, "Rate") if not self.model_f.select(): self.showError(self.model_f.lastError()) return self.proxyModel_f = QSortFilterProxyModel() self.proxyModel_f.setSourceModel(self.model_f) self.proxyModel_f.setFilterKeyColumn(1) self.foodView.setModel(self.proxyModel_f) self.foodView.setColumnHidden(0, True) self.foodView.setSelectionMode(QAbstractItemView.SingleSelection) self.foodView.setColumnWidth(1, 150) self.foodView.setColumnWidth(2, 90) def showError(self, err): QMessageBox.critical(self, "Unable to initialize Database", "Error initializing database: " + err.text()) def filterChange(self): regExp = QRegExp(self.filterLine.text(), Qt.CaseInsensitive, QRegExp.FixedString) self.proxyModel_f.setFilterRegExp(regExp) def dataChange(self): date = self.calendarWidget.selectedDate().toString('dd.MM.yyyy') regExp = QRegExp(date, Qt.CaseInsensitive, QRegExp.FixedString) self.proxyModel_in.setFilterRegExp(regExp) def addFood(self): self.model_f.insertRow(self.model_f.rowCount()) def delFood(self): self.model_f.removeRow(self.foodView.currentIndex().row()) self.model_f.select() def resizeEvent(self, event): self.dayView.setColumnWidth(1, self.dayView.width() * 0.7) self.dayView.setColumnWidth(3, self.dayView.width() * 0.2) QWidget.resizeEvent(self, event) def ShowContextMenu(self, pos): contextMenu = QMenu("Context menu", self) action1 = QAction("Add food eaten", self) contextMenu.addAction(action1) contextMenu.exec(self.mapToGlobal(pos))
class MainWindow(QMainWindow): mySignal = pyqtSignal(dict) acquireDataSignal = pyqtSignal(str) acquireMostCommonEmojis = pyqtSignal() loadNewFileSignal = pyqtSignal(str) setMinDateSignal = pyqtSignal(object) setMaxDateSignal = pyqtSignal(object) def makeConnections(self, otherObject): self.mySignal.connect(otherObject.onJob) def __init__(self, parent=None): super(MainWindow, self).__init__(parent) QMainWindow.__init__(self) self.currentData = {} self.indx = 0 self.indxPlotTable = { 0: 'Emojis', 1: 'Words', 2: 'Messages by user', 3: 'Media messages by user' } self.currentFile = "" self.title = 'Whatsapp Statisic Application' self.mindataToDisplay = date(1900, 1, 1) self.currentMinData = date(1900, 1, 1) self.maxdataToDisplay = date(2100, 12, 31) self.currentMaxData = date(2100, 12, 31) self.setWindowTitle(self.title) self.setGeometry(30, 30, 1280, 1024) self.statusBar().showMessage('Ready') self.initMenubar() self.initToolBar() self.plotWidget = WidgetPlot(self) widget = QWidget(self) self.setCentralWidget(widget) vlay = QVBoxLayout(widget) self.nameLabel = QLabel('Min Date', self) self.nameLabel2 = QLabel('Max Date', self) self.nameLabel.setFont(QFont('Arial', 20)) self.nameLabel2.setFont(QFont('Arial', 20)) self.pyCal = QCalendarWidget() self.pyCal.setGridVisible(True) self.pyCal.clicked[QDate].connect(self.sendMinDate) self.pyCal2 = QCalendarWidget() self.pyCal2.setGridVisible(True) self.pyCal2.clicked[QDate].connect(self.sendMaxDate) grid = QGridLayout() grid.addWidget(self.nameLabel, 0, 0, Qt.AlignCenter) grid.addWidget(self.nameLabel2, 0, 1, Qt.AlignCenter) grid.addWidget(self.pyCal, 1, 0) grid.addWidget(self.pyCal2, 1, 1) vlay.addLayout(grid) vlay.addWidget(self.plotWidget) def sendMinDate(self, date): self.currentMinData = date.toPyDate() self.setMinDateSignal.emit(self.currentMinData) def sendMaxDate(self, date): self.currentMaxData = date.toPyDate() self.setMaxDateSignal.emit(self.currentMaxData) def initMenubar(self): mainMenu = self.menuBar() mainMenu.setNativeMenuBar(False) fileMenu = mainMenu.addMenu('File') helpMenu = mainMenu.addMenu('Help') loadButton = QAction(QIcon('load24.png'), 'Load', self) loadButton.setShortcut('Ctrl+O') loadButton.setStatusTip('Load File') loadButton.triggered.connect(self.loadFile) fileMenu.addAction(loadButton) exitButton = QAction(QIcon('exit24.png'), 'Exit', self) exitButton.setShortcut('Ctrl+Q') exitButton.setStatusTip('Exit application') exitButton.triggered.connect(self.close) fileMenu.addAction(exitButton) def initToolBar(self): self.toolbar = self.addToolBar('Open') open_action = QAction( QIcon('resources\Icons\Icon_New_File_256x256.png'), '&Save', self) open_action.setShortcut('Ctrl+O') open_action.setStatusTip('Open File') open_action.triggered.connect(self.loadFile) self.toolbar.addAction(open_action) prevPlot_action = QAction( QIcon('resources\Icons\iconfinder_arrow-left_227602.png'), '&Save', self) prevPlot_action.setShortcut('Left') prevPlot_action.setStatusTip('Previous Plot') prevPlot_action.triggered.connect(self.prevPlot) self.toolbar.addAction(prevPlot_action) nextPlot_action = QAction( QIcon('resources\Icons\iconfinder_arrow-right_227601.png'), '&Save', self) nextPlot_action.setShortcut('Right') nextPlot_action.setStatusTip('Next Plot') nextPlot_action.triggered.connect(self.nextPlot) self.toolbar.addAction(nextPlot_action) def loadFile(self): fname = QFileDialog.getOpenFileName(self, 'Open file', 'c:\\', "Text files (*.txt)") if fname[0]: self.currentFile = fname[0] self.plotWidget.canvas.clearPlot() self.loadNewFileSignal.emit(self.currentFile) def clickMethod(self): print('Clicked Pyqt button.') print('Emit signal') self.mySignal.emit(dict()) if self.line.text() == '': self.statusBar().showMessage('Not a Number') else: print('Number: {}'.format(float(self.line.text()) * 2)) self.statusBar().showMessage('Introduction of a number') self.nameLabel2.setText(str(float(self.line.text()) * 2)) def nextPlot(self): self.plotWidget.canvas.clearPlot() if self.currentFile != "": if self.indx + 1 >= len(self.indxPlotTable): self.indx = 0 else: self.indx = self.indx + 1 self.acquireDataSignal.emit(self.indxPlotTable[self.indx]) def prevPlot(self): self.plotWidget.canvas.clearPlot() if self.currentFile != "": if self.indx - 1 < 0: self.indx = len(self.indxPlotTable) - 1 else: self.indx = self.indx - 1 self.acquireDataSignal.emit(self.indxPlotTable[self.indx]) def clearPlot(self): self.plotWidget.canvas.clearPlot() @pyqtSlot(dict) def onData(self, data): self.currentData = data self.plotWidget.canvas.clearPlot() title = self.indxPlotTable[ self.indx] + " between " + self.currentMinData.strftime( "%d.%m.%Y") + " and " + self.currentMaxData.strftime( "%d.%m.%Y") self.plotWidget.canvas.plot(self.currentData, title) @pyqtSlot(object) def setMinDateInCalendar(self, minData): self.mindataToDisplay = minData self.currentMinData = minData self.pyCal.setMinimumDate( QDate(minData.year, minData.month, minData.day)) self.pyCal2.setMinimumDate( QDate(minData.year, minData.month, minData.day)) self.pyCal.setSelectedDate( QDate(minData.year, minData.month, minData.day)) @pyqtSlot(object) def setMaxDateInCalendar(self, maxData): self.maxdataToDisplay = maxData self.currentMaxData = maxData self.pyCal.setMaximumDate( QDate(maxData.year, maxData.month, maxData.day)) self.pyCal2.setMaximumDate( QDate(maxData.year, maxData.month, maxData.day)) self.pyCal2.setSelectedDate( QDate(maxData.year, maxData.month, maxData.day))
class ToDoWindow(QWidget): def __init__(self, db_accessor): super().__init__() self.db_accessor = db_accessor # database delegate self.init_ui() def init_ui(self): self.hBox = QHBoxLayout() self.hBox2 = QHBoxLayout() self.vBox = QVBoxLayout() self.removeBtn = QPushButton() self.removeBtn.setText("Remove Selected Tasks") self.removeBtn.clicked[bool].connect(self.remove_task) self.createBtn = QPushButton() self.createBtn.setText("Create Task") self.createBtn.setFixedSize(200, 50) self.createBtn.clicked[bool].connect(self.create_task) self.nameBox = QLineEdit() self.nameBox.setPlaceholderText("Task Name") self.nameBox.setMaxLength(50) self.nameBox.setFixedSize(1185, 50) self.descBox = QTextEdit() self.descBox.setPlaceholderText("Task Description") self.descBox.setFixedSize(600, 500) self.calendar = QCalendarWidget() self.calendar.setFixedSize(775, 500) self.table = QTableView() self.table.setFixedSize(1400, 400) # stretch columns to fill table's width and load data from database into table self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) self.update_task_view(self.db_accessor.get_tasks()) # add widgets to appropriate horizontal layouts self.hBox.addWidget(self.createBtn) self.hBox.addWidget(self.nameBox) self.hBox2.addWidget(self.descBox) self.hBox2.addWidget(self.calendar) # add horizontal layouts to vertical layout # add remove button and table to vertical layout self.vBox.addLayout(self.hBox) self.vBox.addLayout(self.hBox2) self.vBox.addWidget(self.removeBtn) self.vBox.addWidget(self.table) # Create and display window self.setLayout(self.vBox) self.setWindowTitle('To-Do') self.show() # insert a new task into the database and refresh table to reflect insertion def create_task(self): name = self.nameBox.text().replace("'", "\\'") description = self.descBox.toPlainText().replace("'", "\\'") date = self.calendar.selectedDate().toString("yyyy-MM-dd") self.db_accessor.insert_new_task(name, description, date) self.update_task_view(self.db_accessor.get_tasks()) # refresh table def update_task_view(self, result_set): model = QStandardItemModel() list_of_entries = [list(map(str, elem)) for elem in result_set] model.setHorizontalHeaderLabels(self.db_accessor.get_column_names()) res_rows = list_of_entries for row in res_rows: model.appendRow(self.get_items_row(row)) self.table.setModel(model) self.table.resizeRowsToContents() self.nameBox.setText("") self.descBox.setText("") self.calendar.setSelectedDate(QDate.currentDate()) # set the values from the result set into a new row in the model format def get_items_row(self, result_row): item_row = [] for val in result_row: item = QStandardItem(val) item.setEditable(False) item_row.append(item) return item_row def remove_task(self): model = self.table.model() # get the indeces of the currently selected rows indices = [ elem.row() for elem in self.table.selectionModel().selectedRows() ] # remove the tasks from the database and refresh table to reflect deletion for index in indices: name = model.data(model.index(index, 0)).replace("'", "\\'") description = model.data(model.index(index, 1)).replace("'", "\\'") date = model.data(model.index(index, 2)) self.db_accessor.delete_task(name, description, date) self.update_task_view(self.db_accessor.get_tasks())
class VistaListaPrenotazioni(QWidget): global currentYear, currentMonth currentMonth = datetime.now().month currentYear = datetime.now().year def __init__(self): super(VistaListaPrenotazioni, self).__init__() grid_layout = QGridLayout() self.controller = ControlloreListaPrenotazioni() self.list_view = QListView() self.calendar = QCalendarWidget(self) self.calendar.move(20, 20) self.calendar.setGridVisible(True) self.calendar.setMinimumDate(QDate(currentYear, currentMonth - 1, 1)) self.calendar.setMaximumDate( QDate(currentYear, currentMonth + 1, calendar.monthrange(currentYear, currentMonth)[1])) self.calendar.setSelectedDate(QDate(currentYear, currentMonth, 1)) self.calendar.clicked.connect(self.printInfo) buttons_layout = QVBoxLayout() add_button = QPushButton("Aggiungi prenotazione") add_button.clicked.connect(self.aggiungi_prenotazione) buttons_layout.addWidget(add_button) delete_button = QPushButton("Elimina prenotazione") delete_button.clicked.connect(self.elimina_prenotazione) buttons_layout.addWidget(delete_button) grid_layout.addWidget(self.calendar, 0, 0) grid_layout.addLayout(buttons_layout, 0, 1) grid_layout.addWidget(self.list_view, 1, 0) self.resize(600, 400) self.setWindowTitle('Lista Prenotazioni') self.setLayout(grid_layout) def printInfo(self, qDate): self.listview_model = QStandardItemModel(self.list_view) item = QStandardItem() fontstd = QFont("DejaVu Sans Mono", 10) fontstd.setFamily('Monospace') fontstd.setFixedPitch(True) item.setFont(fontstd) item.setText("{0:<15}{1:<12}{2:<10}{3}".format("Nome: ", "Telefono:", "Persone:", "Orario:")) item.setEditable(False) font = item.font() font.setPointSize(12) item.setFont(font) self.listview_model.appendRow(item) for prenotazione in self.controller.get_prenotazioni_by_data( datetime(qDate.year(), qDate.month(), qDate.day())): item = QStandardItem() fontstd = QFont("DejaVu Sans Mono", 10) fontstd.setFamily('Monospace') fontstd.setFixedPitch(True) item.setFont(fontstd) item.setText("{0:<15}{1:<12}{2:<10}{3}".format( prenotazione.nome, prenotazione.telefono, prenotazione.num_persone, prenotazione.data.hour)) item.setEditable(False) font = item.font() font.setPointSize(12) item.setFont(font) self.listview_model.appendRow(item) self.list_view.setModel(self.listview_model) def aggiungi_prenotazione(self): self.vista_aggiungi_prenotazione = VistaPrenotazione(self.controller) self.vista_aggiungi_prenotazione.show() def elimina_prenotazione(self): pass
class DateInputW(QFrame): def __init__(self, parent): super(DateInputW, self).__init__() self.layout = QGridLayout() self.parent = parent self.title1 = QLabel(u'Начало:', self) self.title1.move(5, 5) self.cal1 = QCalendarWidget() self.cal1.setGridVisible(True) self.cal1.setDateEditEnabled(True) self.cal1.clicked.connect(self.setDateStart) self.cal1.setFixedSize(200, 160) ymd1 = [parent.day_start.year, parent.day_start.month, parent.day_start.day] qdate1 = QDate() qdate1.setDate(ymd1[0], ymd1[1], ymd1[2]) self.cal1.setSelectedDate(qdate1) self.lbl1 = QLabel(self) self.lbl1.setText(parent.day_start.strftime('%d/%m/%Y')) self.lbl1.move(5, 25) self.title2 = QLabel(u'Конец:', self) self.title2.move(325, 5) self.cal2 = QCalendarWidget() self.cal2.setGridVisible(True) self.cal2.setDateEditEnabled(True) self.cal2.clicked.connect(self.setDateEnd) self.cal2.setFixedSize(200, 160) ymd2 = [parent.day_end.year, parent.day_end.month, parent.day_end.day] qdate2 = QDate() qdate2.setDate(ymd2[0], ymd2[1], ymd2[2]) self.cal2.setSelectedDate(qdate2) self.lbl2 = QLabel(self) self.lbl2.setText(parent.day_end.strftime('%d/%m/%Y')) self.lbl2.move(325, 25) self.layout.addWidget(self.cal1, 1, 0) self.layout.addWidget(self.cal2, 1, 1) self.setAutoFillBackground(True) palette = self.palette() palette.setColor(self.backgroundRole(), QColor('white')) self.setPalette(palette) self.setFrameShape(_frameShape) self.setFrameShadow(_frameShadow) self.setLineWidth(_lineWidth) self.setMidLineWidth(_midLineWidth) #change NavBar background color child = self.cal1.children()[3] palette = child.palette() palette.setColor(child.backgroundRole(), QColor('silver')) child.setPalette(palette) child = self.cal2.children()[3] palette = child.palette() palette.setColor(child.backgroundRole(), QColor('silver')) child.setPalette(palette) # change cell color brush = self.cal1.paintCell #self.cal1.setWeekdayTextFormat(headerForm) #parent.layout.addLayout(self.layout, 1, 0, 1, 2) def setDateStart(self): date = self.cal1.selectedDate() date = date.toPyDate() self.parent.day_start = datetime.datetime(date.year, date.month, date.day) self.lbl1.setText(self.parent.day_start.strftime('%d/%m/%Y')) minDate_dt = self.parent.day_start + datetime.timedelta(days=1) minDate = QDate() minDate.setDate(minDate_dt.year, minDate_dt.month, minDate_dt.day) self.cal2.setMinimumDate(minDate) def setDateEnd(self): date = self.cal2.selectedDate() date = date.toPyDate() self.parent.day_end = datetime.datetime(date.year, date.month, date.day) self.lbl2.setText(self.parent.day_end.strftime('%d/%m/%Y')) maxDate_dt = self.parent.day_end - datetime.timedelta(days=1) maxDate = QDate() maxDate.setDate(maxDate_dt.year, maxDate_dt.month, maxDate_dt.day) self.cal1.setMaximumDate(maxDate)