def add_date_field(self, f_title, top, left, f_date, widthchange=0, need_calendar=True, default_value=QDate(1980, 1, 1), readonly=False, label_margin=2, label_font_size=LABEL_FONT_SIZE, field_size=4): label = QLabel(self.parent) label.setText(f_title) font = QFont() font.setPointSize(label_font_size) label.setFont(font) geo_label = QRect(left * self.width_step, top, label_margin * self.width_step, 30) label.setGeometry(geo_label) field = QDateEdit(self.parent) field.setCalendarPopup(need_calendar) geo_field = QRect((left + label_margin) * self.width_step, top, field_size * self.width_step, 30) field.setGeometry(geo_field) if f_date: Defdate = QDate(int(f_date.split('.')[2]), int(f_date.split('.')[1]), int(f_date.split('.')[0])) else: Defdate = default_value field.setDate(Defdate) field.setReadOnly(readonly) return field
class TableWidget(QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.resize(700, 72) self.setMinimumWidth(700) # Widgets self.lesson = QLineEdit(self) self.lesson.setReadOnly(True) self.lesson.setToolTip('Описание предмета') self.deadline = QDateEdit(self) self.deadline.setToolTip('Дата окончания') self.deadline.setReadOnly(True) self.deadline.setDate(date.today()) self.deadline.setMinimumDate(date(2017, 9, 1)) self.save_button = QPushButton('Сохранить', self) self.delete_button = QPushButton('Удалить', self) self.result = QDoubleSpinBox(self) self.result.setSingleStep(0.01) self.result.setToolTip('Результат') self.done = QCheckBox(self) self.done.setToolTip('Задача выполнена') # Layouts grid_layout = QGridLayout(self) grid_layout.addWidget(self.lesson, 0, 1) grid_layout.addWidget(self.deadline, 0, 3) buttons_layout = QVBoxLayout() buttons_layout.addWidget(self.save_button) buttons_layout.addWidget(self.delete_button) grid_layout.addLayout(buttons_layout, 0, 5) grid_layout.addWidget(self.result, 0, 4) grid_layout.addWidget(self.done, 0, 0) # Tab order self.setTabOrder(self.done, self.lesson) self.setTabOrder(self.lesson, self.deadline) self.setTabOrder(self.deadline, self.result) self.setTabOrder(self.result, self.save_button) self.setTabOrder(self.save_button, self.delete_button)
class Window(QWidget): def __init__(self): super().__init__() self.db = run() self.setWindowTitle("To-Do") self.setWindowIcon(QIcon('web.png')) self.setGeometry(100, 50, 1920, 1080) self.layout = QVBoxLayout(self) self.prelayout = QHBoxLayout(self) self.row = 0 #=================== #widget part #------------------- self.label = QLabel('To-Do!', self) self.plus = QPushButton("+", self) self.plus.resize(700, 100) self.plus.clicked.connect(self.createTask) self.today = QPushButton("Tasks on today") self.today.resize(500, 30) self.today.clicked.connect(self.day_notifications) ## self.grid.addWidget(self.plus, 0, 2, 3, 2) self.layout.addWidget(self.label) self.layout.addWidget(self.plus) self.layout.addWidget(self.today) self.all = QPushButton("All") self.active = QPushButton("Active") self.done = QPushButton("Done") self.all.clicked.connect(self.all_tasks) self.active.clicked.connect(self.active_tasks) self.done.clicked.connect(self.done_tasks) self.prelayout.addWidget(self.all) self.prelayout.addWidget(self.active) self.prelayout.addWidget(self.done) self.layout.addLayout(self.prelayout) self.scrollArea = QScrollArea(self) self.scrollArea.setWidgetResizable(True) self.scrollAreaWidgetContents = QWidget() self.tasks = QGridLayout(self.scrollAreaWidgetContents) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.layout.addWidget(self.scrollArea) self.tasks.setSpacing(10) self.layout.addLayout(self.tasks) self.createTaskWithStuff #=================== #CSS part #-------------------- self.label.setStyleSheet("""font-size: 14.5pt; font-family: MS Gothic 2; """) self.all.setStyleSheet("""QPushButton{ margin-top: 40px; margin-right: 0px; margin-left: 0px; border: 1px solid gray; } QPushButton:hover{ background-color: lightgray; } """) self.active.setStyleSheet("""QPushButton{ margin-top: 40px; margin-right: 0px; margin-left: 0px; border: 1px solid gray; } QPushButton:hover{ background-color: lightgray; } """) self.done.setStyleSheet("""QPushButton{ margin-top: 40px; margin-right: 0px; margin-left: 0px; border: 1px solid gray; } QPushButton:hover{ background-color: lightgray; } """) #==================== self.layouts = {} self.layouts1 = {} self.layouts2 = {} self.layouts3 = {} self.layouts4 = {} self.done_layouts = {} self.str_louts = {} self.x_pos = 0 self.y_pos = 0 for task in self.db.read_all(): if task[1] != 'notnamed': self.createTaskWithStuff(id=task[0], name=task[1], date_exec=task[2], text=task[3], date_until=task[4], status=task[5]) else: self.db.delete_the_task(task[0]) self.show() def save(self): self.widget = self.sender() self.key_list = list(self.layouts2.keys()) self.val_list = list(self.layouts2.values()) self.position = self.val_list.index(self.widget) self.item = self.key_list[self.position] self.cur_id = int(self.layouts[self.item][0].text()) self.date = self.layouts[self.item][2].date().toString('yyyy-MM-dd') self.text = str(self.layouts[self.item][4].toPlainText()) self.date1 = self.layouts[self.item][3].date().toString('yyyy-MM-dd') self.name = str(self.layouts[self.item][1].text()) print(self.date) print(self.text) print(self.date1) print(self.name) self.db.update(self.date, self.text, self.date1, self.cur_id, self.name if self.name else None) self.layouts[self.item][1].setReadOnly(True) self.layouts[self.item][2].setReadOnly(True) self.layouts[self.item][3].setReadOnly(True) self.layouts[self.item][4].setReadOnly(True) self.layouts[self.item][5].setEnabled(True) self.layouts[self.item][6].setEnabled(False) self.layouts[self.item][7].setEnabled(True) def edit(self): self.widget = self.sender() self.key_list = list(self.layouts3.keys()) self.val_list = list(self.layouts3.values()) self.position = self.val_list.index(self.widget) self.item = self.key_list[self.position] self.layouts[self.item][1].setReadOnly(False) self.layouts[self.item][2].setReadOnly(False) self.layouts[self.item][3].setReadOnly(False) self.layouts[self.item][4].setReadOnly(False) self.layouts[self.item][6].setEnabled(True) self.layouts[self.item][7].setEnabled(False) def delete(self): self.widget = self.sender() self.key_list = list(self.layouts1.keys()) self.val_list = list(self.layouts1.values()) self.position = self.val_list.index(self.widget) self.item = self.key_list[self.position] self.db.delete_the_task(int(self.layouts[self.item][0].text())) for i in self.layouts[self.item]: i.deleteLater() if self.layouts[self.item] == None: break del self.layouts[self.item] self.y_pos -= 1 def createTask(self): self.y_pos = self.y_pos + 1 self.elem = [] self.task = QGridLayout() self.label = QLabel(f"{self.y_pos}") self.line = QLineEdit() self.date = QDateTimeEdit() self.date.setDisplayFormat("yyyy-MM-dd") self.date.setDate(date.today()) self.date1 = QDateTimeEdit() self.date1.setDisplayFormat("yyyy-MM-dd") self.date1.setDate(date.today()) self.text = QTextEdit() self.button = QPushButton(f"Delete") self.button1 = QPushButton(f"Save") self.button2 = QPushButton(f"Edit") self.button3 = QPushButton(f"Done") self.elem.append(self.label) self.elem.append(self.line) self.elem.append(self.date) self.elem.append(self.date1) self.elem.append(self.text) self.elem.append(self.button) self.elem.append(self.button1) self.elem.append(self.button2) self.elem.append(self.button3) self.task.addWidget(self.label, self.y_pos, 0) self.task.addWidget(self.line, self.y_pos, 1) self.task.addWidget(self.date, self.y_pos, 2) self.task.addWidget(self.date1, self.y_pos, 3) self.task.addWidget(self.text, self.y_pos, 4) self.task.addWidget(self.button2, self.y_pos, 5) self.task.addWidget(self.button1, self.y_pos, 6) self.task.addWidget(self.button, self.y_pos, 7) self.task.addWidget(self.button3, self.y_pos, 8) self.button.clicked.connect(self.delete) self.button2.clicked.connect(self.edit) self.button1.clicked.connect(self.save) self.button3.clicked.connect(self.doneTask) self.layouts[self.task] = self.elem self.layouts1[self.task] = self.button self.layouts2[self.task] = self.button1 self.layouts3[self.task] = self.button2 self.layouts4[self.task] = self.button3 self.str_louts[str(self.task)] = self.task self.button2.setEnabled(False) self.tasks.addLayout(self.task, self.y_pos, 0) self.db.create_a_task(None, None, None, "Active", self.task, None, self.y_pos) def doneTask(self): self.widget = self.sender() self.widget.setEnabled(False) self.key_list = list(self.layouts4.keys()) self.val_list = list(self.layouts4.values()) self.position = self.val_list.index(self.widget) self.item = self.key_list[self.position] self.db.done(int(self.layouts[self.item][0].text())) def createTaskWithStuff(self, id, name, date_exec, date_until, text, status): self.y_pos += 1 self.elem = [] self.task = QGridLayout() self.label = QLabel(f"{id}") self.line = QLineEdit() self.line.setText(name) self.line.setReadOnly(True) self.date = QDateEdit() self.date.setDate(QDate.fromString(date_exec, "yyyy-MM-dd")) self.date.setDisplayFormat("yyyy-MM-dd") self.date.setReadOnly(True) self.date1 = QDateEdit() self.date1.setDate(QDate.fromString(date_until, "yyyy-MM-dd")) self.date1.setDisplayFormat("yyyy-MM-dd") self.date1.setReadOnly(True) self.text = QTextEdit() self.text.setText(text) self.text.setReadOnly(True) self.button = QPushButton(f"Delete") self.button1 = QPushButton(f"Save") self.button2 = QPushButton(f"Edit") self.button3 = QPushButton(f"Done") self.button1.setEnabled(False) if status == "Done": self.button3.setEnabled(False) self.elem.append(self.label) self.elem.append(self.line) self.elem.append(self.date) self.elem.append(self.date1) self.elem.append(self.text) self.elem.append(self.button) self.elem.append(self.button1) self.elem.append(self.button2) self.elem.append(self.button3) self.task.addWidget(self.label, id, 0) self.task.addWidget(self.line, id, 1) self.task.addWidget(self.date, id, 2) self.task.addWidget(self.date1, id, 3) self.task.addWidget(self.text, id, 4) self.task.addWidget(self.button2, id, 5) self.task.addWidget(self.button1, id, 6) self.task.addWidget(self.button, id, 7) self.task.addWidget(self.button3, id, 8) self.button.clicked.connect(self.delete) self.button2.clicked.connect(self.edit) self.button1.clicked.connect(self.save) self.button3.clicked.connect(self.doneTask) self.layouts[self.task] = self.elem self.layouts1[self.task] = self.button self.layouts2[self.task] = self.button1 self.layouts3[self.task] = self.button2 self.layouts4[self.task] = self.button3 self.str_louts[str(self.task)] = self.task self.db.grid(int(self.layouts[self.task][0].text()), str(self.task)) self.tasks.addLayout(self.task, id, 0) def all_tasks(self): self.y_pos = 0 for task in self.db.read_all(): self.createTaskWithStuff(id=task[0], name=task[1], date_exec=task[2], text=task[3], date_until=task[4], status=task[5]) def active_tasks(self): for task in self.db.read_all(): if task[5] == "Active": self.createTaskWithStuff(id=task[0], name=task[1], date_exec=task[2], text=task[3], date_until=task[4], status=task[5]) else: for i in self.layouts: for p in self.layouts[i]: p.deleteLater() del self.layouts[i][0] self.y_pos -= 1 def done_tasks(self): for task in self.db.read_all(): if task[5] == "Done": self.createTaskWithStuff(id=task[0], name=task[1], date_exec=task[2], text=task[3], date_until=task[4], status=task[5]) else: for i in self.layouts[self.str_louts[task[6]]]: i.deleteLater() del self.layouts[self.str_louts[task[6]]] self.y_pos -= 1 def day_notifications(self): self.str_of_tasks = "Today, you need to do these tasks - " self.tasks_num = 0 for task in self.db.read_all(): if task[4] == str(date.today()) or task[2] == str(date.today()): self.str_of_tasks = self.str_of_tasks + str(task[1]) + ", " self.tasks_num += 1 if self.tasks_num == 0: self.str_of_tasks = "You're relaxing today! You don't need to do anything today." elif self.tasks_num > 0: self.str_of_tasks = self.str_of_tasks[:-2] self.str_of_tasks = self.str_of_tasks + "." QMessageBox.about(self, 'Tasks', self.str_of_tasks)
class PatientDialog(QDialog): ADD_PATIENT = 1 EDIT_PATIENT = 2 UPDATE_ID = 3 DELETE_PATIENT = 4 SYSTOLIC_DEFAULT = 135 DIASTOLIC_DEFAULT = 90 def __init__(self, kind, patient_ids): QDialog.__init__(self) assert kind >= self.ADD_PATIENT and kind <= self.DELETE_PATIENT self.kind = kind self.patient_ids = patient_ids if kind == self.ADD_PATIENT: self.id = QLineEdit(self) self.id.setMaxLength(20) else: self.id = QComboBox(self) for ident in self.patient_ids: self.id.addItem(ident) self.id.currentIndexChanged.connect(self.selection_change) self.name = QLineEdit() self.name.setReadOnly(kind == self.DELETE_PATIENT) self.birthday = QDateEdit() self.birthday.displayFormat = bpm_db.BIRTHDAY_FMT self.birthday.setReadOnly(kind == self.DELETE_PATIENT) self.gender = QComboBox(self) for choice in ["Female", "Male", "Non-binary"]: self.gender.addItem(choice) self.sys_limit = QLineEdit(str(self.SYSTOLIC_DEFAULT)) self.sys_limit.setValidator(QIntValidator(100, 180)) self.sys_limit.setReadOnly(kind == self.DELETE_PATIENT) self.dia_limit = QLineEdit(str(self.DIASTOLIC_DEFAULT)) self.dia_limit.setValidator(QIntValidator(60, 120)) self.dia_limit.setReadOnly(kind == self.DELETE_PATIENT) if kind != self.ADD_PATIENT: self.selection_change(0) self.flo = QFormLayout() self.flo.addRow("Id", self.id) self.flo.addRow("Full Name", self.name) self.flo.addRow("Birthday", self.birthday) self.flo.addRow("Gender", self.gender) self.flo.addRow("Systolic limit", self.sys_limit) self.flo.addRow("Diastolic limit", self.dia_limit) self.buttonBox = QDialogButtonBox(( QDialogButtonBox. Ok if kind >= self.UPDATE_ID else QDialogButtonBox.Save) | QDialogButtonBox.Cancel) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) self.layout = QVBoxLayout() self.layout.addLayout(self.flo) self.layout.addWidget(self.buttonBox) self.setLayout(self.layout) self.setWindowTitle( "Add Patient" if kind == self.ADD_PATIENT else "Delete Patient" if kind == self.DELETE_PATIENT else "Edit Patient" if kind == self.EDIT_PATIENT else "Update ID in Blood Pressure Monitor") self.setWindowModality(Qt.ApplicationModal) def selection_change(self, i): info = self.patient_ids[self.id.currentText()] self.name.setText(info['name'] if 'name' in info else "") self.birthday.setDate( QDate.fromString(info['birthday'], bpm_db.BIRTHDAY_FMT ) if 'birthday' in info else QDate.fromString("1/1/2000", bpm_db.BIRTHDAY_FMT)) self.gender.setCurrentText(info['gender'] if 'gender' in info else "Non-binary") self.sys_limit.setText( str(info['systolic_limit']) if 'systolic_limit' in info else str(self.SYSTOLIC_DEFAULT)) self.dia_limit.setText( str(info['diastolic_limit']) if 'diastolic_lim' 'it' in info else str(self.DIASTOLIC_DEFAULT)) def run(self): if self.exec_(): bd = self.birthday.date().toString(bpm_db.BIRTHDAY_FMT) return { 'id': self.id.text() if self.kind == self.ADD_PATIENT else self.id.currentText(), 'name': self.name.text(), 'birthday': bd, 'age': bpm_db.age_from_birthday(bd), 'gender': self.gender.currentText(), 'systolic_limit': int(self.sys_limit.text()), 'diastolic_limit': int(self.dia_limit.text()) } else: return None
class BookLog(QWidget): NavigationMode, AddingMode, EditingMode = range(3) def __init__(self, parent=None): super(BookLog, self).__init__(parent) self.contacts = SortedDict() self.oldTitle = '' self.oldMemo = '' self.oldShoziflag = False self.oldIsbn = '' self.oldDokuryodate = QDate() self.currentMode = self.NavigationMode #ラベル titleLabel = QLabel("書名:") self.titleLine = QLineEdit() self.titleLine.setReadOnly(True) dokuryoLabel = QLabel("読了日:") self.dokuryodate = QDateEdit() self.dokuryodate.setReadOnly(True) memoLabel = QLabel("メモ:") self.memoText = QTextEdit() self.memoText.setReadOnly(True) isbnLabel = QLabel("ISBN:") self.isbnLine = QLineEdit() self.isbnLine.setReadOnly(True) shoziflag = QLabel("所持:") self.shoziflag = QCheckBox() self.addButton = QPushButton("&追加") self.addButton.show() self.editButton = QPushButton("&編集") self.editButton.setEnabled(False) self.removeButton = QPushButton("&削除") self.removeButton.setEnabled(False) self.findButton = QPushButton("&検索") self.findButton.setEnabled(False) self.submitButton = QPushButton("&挿入") self.submitButton.hide() self.cancelButton = QPushButton("&キャンセル") self.cancelButton.hide() self.nextButton = QPushButton("&次") self.nextButton.setEnabled(False) self.previousButton = QPushButton("&前") self.previousButton.setEnabled(False) self.loadButton = QPushButton("&Load...") self.loadButton.setToolTip("Load contacts from a file") self.saveButton = QPushButton("Sa&ve...") self.saveButton.setToolTip("Save contacts to a file") self.saveButton.setEnabled(False) self.exportButton = QPushButton("Ex&port") self.exportButton.setToolTip("Export as vCard") self.exportButton.setEnabled(False) self.dialog = FindDialog() self.addButton.clicked.connect(self.addContact) self.submitButton.clicked.connect(self.submitContact) self.editButton.clicked.connect(self.editContact) self.removeButton.clicked.connect(self.removeContact) #self.findButton.clicked.connect(self.findContact) self.cancelButton.clicked.connect(self.cancel) self.nextButton.clicked.connect(self.next) self.previousButton.clicked.connect(self.previous) self.loadButton.clicked.connect(self.loadFromFile) self.saveButton.clicked.connect(self.saveToFile) self.exportButton.clicked.connect(self.exportAsVCard) #self.createMenus() #topFiller = QWidget() #topFiller.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) buttonLayout1 = QVBoxLayout() buttonLayout1.addWidget(self.addButton) buttonLayout1.addWidget(self.editButton) buttonLayout1.addWidget(self.removeButton) buttonLayout1.addWidget(self.findButton) buttonLayout1.addWidget(self.submitButton) buttonLayout1.addWidget(self.cancelButton) buttonLayout1.addWidget(self.loadButton) buttonLayout1.addWidget(self.saveButton) buttonLayout1.addWidget(self.exportButton) buttonLayout1.addStretch() buttonLayout2 = QHBoxLayout() buttonLayout2.addWidget(self.previousButton) buttonLayout2.addWidget(self.nextButton) mainLayout = QGridLayout() mainLayout.addWidget(titleLabel, 0, 0) mainLayout.addWidget(self.titleLine, 0, 1) mainLayout.addWidget(memoLabel, 3, 0, Qt.AlignTop) mainLayout.addWidget(self.memoText, 3, 1) mainLayout.addWidget(dokuryoLabel, 2, 0) mainLayout.addWidget(self.dokuryodate, 2, 1) mainLayout.addWidget(isbnLabel, 1, 0) mainLayout.addWidget(self.isbnLine, 1, 1) mainLayout.addWidget(shoziflag, 4, 0) mainLayout.addWidget(self.shoziflag, 4, 1) mainLayout.addLayout(buttonLayout1, 6, 2) mainLayout.addLayout(buttonLayout2, 5, 1) #テーブル self.table = QTableWidget( 100, 5, ) self.table.setHorizontalHeaderLabels(["書名", "ISBN", "読了日", "メモ", "所持"]) self.table.verticalHeader().setVisible(False) #for i, (title, memo) in enumerate(tableData): i = 0 for title, obj in self.contacts.items(): titleItem = QTableWidgetItem(title) memoItem = QTableWidgetItem() memoItem.setData(Qt.DisplayRole, memo) if obj['shoziflag'] == True: maru = '○' else: maru = '' self.table.setItem(i, 0, titleItem) self.table.setItem(i, 1, QTableWidgetItem(obj['isbn'])) self.table.setItem(i, 2, QTableWidgetItem(obj['dokuryodate'])) self.table.setItem(i, 3, QTableWidgetItem(obj['memo'])) self.table.setItem(i, 4, QTableWidgetItem(maru)) i += 1 #table.resize(150, 50) #self.table.resizeColumnToContents(0) self.table.horizontalHeader().setStretchLastSection(True) self.table.doubleClicked.connect(self.tableclick) mainLayout.addWidget(self.table, 6, 1) #mainLayout.addWidget(topFiller) self.setLayout(mainLayout) self.setWindowTitle("Simple Book Log") #self.csvImport() self.loadFromFile('./a.bl') def createUI(self): self.setWindowTitle('Equipment Manager 0.3') #Menu Bar fileMenuBar = QMenuBar(self) menuFile = QMenu(fileMenuBar) actionChangePath = QAction(tr("Change Path"), self) fileMenuBar.addMenu(menuFile) menuFile.addAction(actionChangePath) def addContact(self): self.oldTitle = self.titleLine.text() self.oldMemo = self.memoText.toPlainText() self.oldIsbn = self.isbnLine.text() self.titleLine.clear() self.memoText.clear() self.isbnLine.clear() self.updateInterface(self.AddingMode) def editContact(self): self.oldTitle = self.titleLine.text() self.oldMemo = self.memoText.toPlainText() self.oldDokuryodate = self.dokuryodate.text() self.oldIsbn = self.isbnLine.text() self.oldShoziflag = self.shoziflag.isChecked() self.updateInterface(self.EditingMode) def submitContact(self): title = self.titleLine.text() memo = self.memoText.toPlainText() isbn = self.isbnLine.text() dokuryodate = self.dokuryodate.text() shoziflag = self.shoziflag.isChecked() if title == "" or memo == "": QMessageBox.information(self, "Empty Field", "Please enter a title and memo.") return if self.currentMode == self.AddingMode: if title not in self.contacts: self.contacts[title] = { 'memo': memo, 'dokuryodate': dokuryodate, 'isbn': isbn, 'shoziflag': shoziflag } QMessageBox.information(self, "追加しました", "\"%s\" は追加されました。" % title) else: QMessageBox.information(self, "追加できませんでした", "\"%s\" はすでに存在しています。" % title) return elif self.currentMode == self.EditingMode: if self.oldTitle != title: if title not in self.contacts: QMessageBox.information(self, "編集しました", "\"%s\" は編集されました。" % self.oldTitle) del self.contacts[self.oldTitle] self.contacts[title] = memo else: QMessageBox.information(self, "編集できませんでした。", "\"%s\"はすでに存在しています。" % title) return elif self.oldMemo != memo: QMessageBox.information(self, "編集しました", "\"%s\"は編集されました。" % title) self.contacts[title] = { memo: memo, dokuryodate: dokuryodate, shoziflag: shoziflag, isbn: isbn } self.updateInterface(self.NavigationMode) # ボタンの処理 def cancel(self): self.titleLine.setText(self.oldTitle) self.memoText.setText(self.oldMemo) self.dokuryodate.setDate(self.oldDokuryodate) self.shoziflag.setChecked(self.oldShoziflag) self.isbnLine.setText(self.oldIsbn) self.updateInterface(self.NavigationMode) def removeContact(self): title = self.titleLine.text() memo = self.memoText.toPlainText() if title in self.contacts: button = QMessageBox.question( self, "Confirm Remove", "Are you sure you want to remove \"%s\"?" % title, QMessageBox.Yes | QMessageBox.No) if button == QMessageBox.Yes: self.previous() del self.contacts[title] QMessageBox.information( self, "Remove Successful", "\"%s\" has been removed from your memo book." % title) self.updateInterface(self.NavigationMode) def next(self): title = self.titleLine.text() it = iter(self.contacts) try: while True: this_title, _ = it.next() if this_title == title: next_title, next_memo, next_date = it.next() break except StopIteration: next_title, next_memo = iter(self.contacts).next() self.titleLine.setText(next_title) self.memoText.setText(next_memo) def previous(self): title = self.titleLine.text() prev_title = prev_memo = None for this_title, this_memo in self.contacts: if this_title == title: break prev_title = this_title prev_memo = this_memo else: self.titleLine.clear() self.memoText.clear() return if prev_title is None: for prev_title, prev_memo in self.contacts: pass self.titleLine.setText(prev_title) self.memoText.setText(prev_memo) def Contact(self): self.dialog.show() if self.dialog.exec_() == QDialog.Accepted: contactTitle = self.dialog.getFindText() found = False for this_title, this_memo in self.contacts: # if contactTitle in this_title: if re.search(contactTitle, this_title): found = True break if found: self.titleLine.setText(this_title) self.memoText.setText(self.contacts[this_title]) self.isbnLine.setText(self.contacts[this_title]) self.dokuryodate.setDate(self.contacts[this_title]) self.shoziflag.setChecked(self.contacts[this_title]) else: QMessageBox.information( self, "Contact Not Found", "Sorry, \"%s\" is not in your address book." % contactTitle) return self.updateInterface(self.NavigationMode) # ボタンを押せるか押せないかの処理 def updateInterface(self, mode): self.currentMode = mode if self.currentMode in (self.AddingMode, self.EditingMode): self.titleLine.setReadOnly(False) self.titleLine.setFocus(Qt.OtherFocusReason) self.isbnLine.setReadOnly(False) self.dokuryodate.setReadOnly(False) self.memoText.setReadOnly(False) self.addButton.setEnabled(False) self.editButton.setEnabled(False) self.removeButton.setEnabled(False) self.nextButton.setEnabled(False) self.previousButton.setEnabled(False) self.submitButton.show() self.cancelButton.show() self.loadButton.setEnabled(False) self.saveButton.setEnabled(False) self.exportButton.setEnabled(False) elif self.currentMode == self.NavigationMode: if not self.contacts: self.titleLine.clear() self.memoText.clear() self.dokuryodate.clear() self.isbnLine.clear() self.titleLine.setReadOnly(True) self.memoText.setReadOnly(True) self.dokuryodate.setReadOnly(True) self.shoziflag self.isbnLine.setReadOnly(True) self.addButton.setEnabled(True) number = len(self.contacts) self.editButton.setEnabled(number >= 1) self.removeButton.setEnabled(number >= 1) self.findButton.setEnabled(number > 2) self.nextButton.setEnabled(number > 1) self.previousButton.setEnabled(number > 1) self.submitButton.hide() self.cancelButton.hide() self.exportButton.setEnabled(number >= 1) self.loadButton.setEnabled(True) self.saveButton.setEnabled(number >= 1) #テーブルの更新 i = 0 for title, obj in self.contacts.items(): titleItem = QTableWidgetItem(title) memoItem = QTableWidgetItem() memoItem.setData(Qt.DisplayRole, obj['memo']) if obj['shoziflag'] == True: maru = '○' else: maru = '' self.table.setItem(i, 0, titleItem) self.table.setItem(i, 1, QTableWidgetItem(obj['isbn'])) self.table.setItem(i, 2, QTableWidgetItem(obj['dokuryodate'])) self.table.setItem(i, 3, QTableWidgetItem(obj['memo'])) self.table.setItem(i, 4, QTableWidgetItem(maru)) i += 1 def saveToFile(self): fileTitle, _ = QFileDialog.getSaveFileName( self, "Save book log", '', "Book Log (*.bl);;All Files (*)") if not fileTitle: return try: out_file = open(str(fileTitle), 'wb') except IOError: QMessageBox.information( self, "Unable to open file", "There was an error opening \"%s\"" % fileTitle) return pickle.dump(self.contacts, out_file) out_file.close() def loadFromFile(self, fileName=None): if not fileName: fileName, _ = QFileDialog.getOpenFileName( self, "Open Address Book", '', "Address Book (*.bl);;All Files (*)") try: in_file = open(str(fileName), 'rb') except IOError: QMessageBox.information( self, "Unable to open file", "There was an error opening \"%s\"" % fileName) return self.contacts = pickle.load(in_file) in_file.close() if len(self.contacts) == 0: QMessageBox.information( self, "No contacts in file", "The file you are attempting to open contains no " "contacts.") else: for title, obj in self.contacts: date = QDate.fromString(obj['dokuryodate']) self.titleLine.setText(title) self.memoText.setText(obj['memo']) self.shoziflag.setChecked(obj['shoziflag']) self.isbnLine.setText(obj['isbn']) self.dokuryodate.setDate(date) self.updateInterface(self.NavigationMode) def exportAsVCard(self): title = str(self.titleLine.text()) memo = self.memoText.toPlainText() titleList = title.split() if len(titleList) > 1: firstName = nameList[0] lastName = nameList[-1] else: firstName = name lastName = '' fileName, _ = QFileDialog.getSaveFileName( self, "Export Contact", '', "vCard Files (*.vcf);;All Files (*)") if not fileName: return out_file = QFile(fileName) if not out_file.open(QIODevice.WriteOnly): QMessageBox.information(self, "Unable to open file", out_file.errorString()) return out_s = QTextStream(out_file) out_s << 'BEGIN:VCARD' << '\n' out_s << 'VERSION:2.1' << '\n' out_s << 'N:' << lastName << ';' << firstName << '\n' out_s << 'FN:' << ' '.join(nameList) << '\n' address.replace(';', '\\;') address.replace('\n', ';') address.replace(',', ' ') out_s << 'ADR;HOME:;' << address << '\n' out_s << 'END:VCARD' << '\n' QMessageBox.information(self, "Export Successful", "\"%s\" has been exported as a vCard." % name) def csvImport(self): with open('MediaMarkerExport.csv', newline='', encoding='utf-8') as f: reader = csv.reader(f) for r in reader: if r[2] == 1: flag = True else: flag = False self.contacts[r[0]] = { 'isbn': r[1], 'dokuryodate': r[3].replace('-', '/'), 'shoziflag': flag, 'memo': '' } aa = 0 def createMenus(self): self.fileMenu = self.menuBar().addMenu("&File") #self.fileMenu.addAction(self.newAct) #self.fileMenu.addAction(self.openAct) #self.fileMenu.addAction(self.saveAct) #self.fileMenu.addAction(self.printAct) #self.fileMenu.addSeparator() #self.fileMenu.addAction(self.exitAct) self.editMenu = self.menuBar().addMenu("&Edit") self.editMenu.addAction(self.undoAct) self.editMenu.addAction(self.redoAct) self.editMenu.addSeparator() self.editMenu.addAction(self.cutAct) self.editMenu.addAction(self.copyAct) self.editMenu.addAction(self.pasteAct) self.editMenu.addSeparator() self.helpMenu = self.menuBar().addMenu("&Help") self.helpMenu.addAction(self.aboutAct) self.helpMenu.addAction(self.aboutQtAct) self.formatMenu = self.editMenu.addMenu("&Format") self.formatMenu.addAction(self.boldAct) self.formatMenu.addAction(self.italicAct) self.formatMenu.addSeparator().setText("Alignment") self.formatMenu.addAction(self.leftAlignAct) self.formatMenu.addAction(self.rightAlignAct) self.formatMenu.addAction(self.justifyAct) self.formatMenu.addAction(self.centerAct) self.formatMenu.addSeparator() self.formatMenu.addAction(self.setLineSpacingAct) self.formatMenu.addAction(self.setParagraphSpacingAct) def tableclick(self, mi): row = mi.row() column = mi.column() #QMessageBox.information(self, "Export Successful", # "%d x %d" % (row, column)) title = self.titleLine.text() it = iter(self.contacts) try: n = 0 while True: next_title, next_obj = it.next() if row == n: break n += 1 except StopIteration: next_title, next_obj = iter(self.contacts).next() self.titleLine.setText(next_title) self.memoText.setText(next_obj['memo']) self.isbnLine.setText(next_obj['isbn']) self.dokuryodate.setDate(next_obj['dokuryodate']) self.shoziflag.setChecked(next_obj['shoziflag'])
class WidgetNote(QWidget): def __init__(self, parent=None): super(WidgetNote, self).__init__(parent) self.parent = parent # Состояние компонентов (Можно редактировать или нет) self.condition_edit = True # Создание интерфейса self.__init_ui() # id товара self.product_id = 0 # Включение Read Only self.read_only_on_off() # Подключение кнопок self.button_edit.clicked.connect(self.__button_edit_input) self.button_remove.clicked.connect(self.parent.remove_product_list) def __init_ui(self): hbox = QHBoxLayout() self.name_product = QLineEdit() self.name_product.setPlaceholderText('Введите название товара') self.price_product = QLineEdit() self.price_product.setValidator(QDoubleValidator()) self.price_product.setPlaceholderText('Введите цену товара') current_date = QDate() self.date_purchase = QDateEdit() self.date_purchase.setDate(current_date.currentDate()) self.button_edit = QPushButton('Редактировать') self.button_remove = QPushButton('Удалить') hbox.addWidget(self.name_product) hbox.addWidget(QVLine()) hbox.addWidget(self.price_product) hbox.addWidget(QVLine()) hbox.addWidget(self.date_purchase) hbox.addWidget(QVLine()) hbox.addWidget(self.button_edit) hbox.addWidget(QVLine()) hbox.addWidget(self.button_remove) self.setLayout(hbox) # Включение/выключение 'read only' def read_only_on_off(self) -> None: self.condition_edit = not self.condition_edit if self.condition_edit: self.button_edit.setText('Редактировать') else: self.button_edit.setText('Сохранить') self.name_product.setReadOnly(self.condition_edit) self.price_product.setReadOnly(self.condition_edit) self.date_purchase.setReadOnly(self.condition_edit) def __button_edit_input(self): self.read_only_on_off() if self.name_product.text() == '': self.name_product.setText('Product Name') if self.condition_edit: self.parent.edit_product(product_id=self.product_id, name_product=self.name_product.text(), price_product=self.convert_price(), date_purchase=self.convert_date()) def select_name_product(self, text) -> None: self.name_product.setText(text) def select_price_product(self, text) -> None: self.price_product.setText(text) def select_id_product(self, id): self.product_id = id def select_date_purchase(self, date): qt_date = QDate() qt_date.setDate(date.year, date.month, date.day) self.date_purchase.setDate(qt_date) # Преобразовать дату def convert_date(self): day, month, year = self.date_purchase.text().split('.') return datetime.datetime(int(year), int(month), int(day)) # Преобразовать цену def convert_price(self): price = self.price_product.text() if price != '': if ',' in price: return float(price.replace(',', '.')) return float(price) self.price_product.setText('0.0') return 0.0
class BookLog(QWidget): NavigationMode, AddingMode, EditingMode = range(3) def __init__(self, parent=None): super(BookLog, self).__init__(parent) self.contacts = SortedDict() self.oldTitle = '' self.oldMemo = '' self.oldShoziflag = False self.oldIsbn = '' self.oldDokuryodate = QDate() self.currentMode = self.NavigationMode #ラベル titleLabel = QLabel("書名:") self.titleLine = QLineEdit() self.titleLine.setReadOnly(True) dokuryoLabel = QLabel("読了日:") self.dokuryodate = QDateEdit() self.dokuryodate.setReadOnly(True) memoLabel = QLabel("メモ:") self.memoText = QTextEdit() self.memoText.setReadOnly(True) isbnLabel = QLabel("ISBN:") self.isbnLine = QLineEdit() self.isbnLine.setReadOnly(True) shoziflag = QLabel("所持:") self.shoziflag = QCheckBox() self.addButton = QPushButton("&追加") self.addButton.show() self.editButton = QPushButton("&編集") self.editButton.setEnabled(False) self.removeButton = QPushButton("&削除") self.removeButton.setEnabled(False) self.findButton = QPushButton("&検索") self.findButton.setEnabled(False) self.submitButton = QPushButton("&挿入") self.submitButton.hide() self.cancelButton = QPushButton("&キャンセル") self.cancelButton.hide() self.nextButton = QPushButton("&次") self.nextButton.setEnabled(False) self.previousButton = QPushButton("&前") self.previousButton.setEnabled(False) self.loadButton = QPushButton("&Load...") self.loadButton.setToolTip("Load contacts from a file") self.saveButton = QPushButton("Sa&ve...") self.saveButton.setToolTip("Save contacts to a file") self.saveButton.setEnabled(False) self.exportButton = QPushButton("Ex&port") self.exportButton.setToolTip("Export as vCard") self.exportButton.setEnabled(False) self.dialog = FindDialog() self.addButton.clicked.connect(self.addContact) self.submitButton.clicked.connect(self.submitContact) self.editButton.clicked.connect(self.editContact) self.removeButton.clicked.connect(self.removeContact) #self.findButton.clicked.connect(self.findContact) self.cancelButton.clicked.connect(self.cancel) self.nextButton.clicked.connect(self.next) self.previousButton.clicked.connect(self.previous) self.loadButton.clicked.connect(self.loadFromFile) self.saveButton.clicked.connect(self.saveToFile) self.exportButton.clicked.connect(self.exportAsVCard) #self.createMenus() #topFiller = QWidget() #topFiller.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) buttonLayout1 = QVBoxLayout() buttonLayout1.addWidget(self.addButton) buttonLayout1.addWidget(self.editButton) buttonLayout1.addWidget(self.removeButton) buttonLayout1.addWidget(self.findButton) buttonLayout1.addWidget(self.submitButton) buttonLayout1.addWidget(self.cancelButton) buttonLayout1.addWidget(self.loadButton) buttonLayout1.addWidget(self.saveButton) buttonLayout1.addWidget(self.exportButton) buttonLayout1.addStretch() buttonLayout2 = QHBoxLayout() buttonLayout2.addWidget(self.previousButton) buttonLayout2.addWidget(self.nextButton) mainLayout = QGridLayout() mainLayout.addWidget(titleLabel, 0, 0) mainLayout.addWidget(self.titleLine, 0, 1) mainLayout.addWidget(memoLabel, 3, 0, Qt.AlignTop) mainLayout.addWidget(self.memoText, 3, 1) mainLayout.addWidget(dokuryoLabel, 2, 0) mainLayout.addWidget(self.dokuryodate, 2, 1) mainLayout.addWidget(isbnLabel, 1, 0) mainLayout.addWidget(self.isbnLine, 1, 1) mainLayout.addWidget(shoziflag, 4, 0) mainLayout.addWidget(self.shoziflag, 4, 1) mainLayout.addLayout(buttonLayout1, 6, 2) mainLayout.addLayout(buttonLayout2, 5, 1) #テーブル self.table = QTableWidget(100, 5,) self.table.setHorizontalHeaderLabels(["書名", "ISBN", "読了日", "メモ", "所持"]) self.table.verticalHeader().setVisible(False) #for i, (title, memo) in enumerate(tableData): i = 0 for title, obj in self.contacts.items(): titleItem = QTableWidgetItem(title) memoItem = QTableWidgetItem() memoItem.setData(Qt.DisplayRole, memo) if obj['shoziflag'] == True: maru = '○' else: maru = '' self.table.setItem(i, 0, titleItem) self.table.setItem(i, 1, QTableWidgetItem(obj['isbn'])) self.table.setItem(i, 2, QTableWidgetItem(obj['dokuryodate'])) self.table.setItem(i, 3, QTableWidgetItem(obj['memo'])) self.table.setItem(i, 4, QTableWidgetItem(maru)) i += 1 #table.resize(150, 50) #self.table.resizeColumnToContents(0) self.table.horizontalHeader().setStretchLastSection(True) self.table.doubleClicked.connect(self.tableclick) mainLayout.addWidget(self.table, 6, 1) #mainLayout.addWidget(topFiller) self.setLayout(mainLayout) self.setWindowTitle("Simple Book Log") #self.csvImport() self.loadFromFile('./a.bl') def createUI(self): self.setWindowTitle('Equipment Manager 0.3') #Menu Bar fileMenuBar = QMenuBar(self) menuFile = QMenu(fileMenuBar) actionChangePath = QAction(tr("Change Path"), self) fileMenuBar.addMenu(menuFile) menuFile.addAction(actionChangePath) def addContact(self): self.oldTitle = self.titleLine.text() self.oldMemo = self.memoText.toPlainText() self.oldIsbn = self.isbnLine.text() self.titleLine.clear() self.memoText.clear() self.isbnLine.clear() self.updateInterface(self.AddingMode) def editContact(self): self.oldTitle = self.titleLine.text() self.oldMemo = self.memoText.toPlainText() self.oldDokuryodate = self.dokuryodate.text() self.oldIsbn = self.isbnLine.text() self.oldShoziflag = self.shoziflag.isChecked() self.updateInterface(self.EditingMode) def submitContact(self): title = self.titleLine.text() memo = self.memoText.toPlainText() isbn = self.isbnLine.text() dokuryodate = self.dokuryodate.text() shoziflag = self.shoziflag.isChecked() if title == "" or memo == "": QMessageBox.information(self, "Empty Field", "Please enter a title and memo.") return if self.currentMode == self.AddingMode: if title not in self.contacts: self.contacts[title] = {'memo':memo, 'dokuryodate':dokuryodate, 'isbn':isbn, 'shoziflag':shoziflag} QMessageBox.information(self, "追加しました", "\"%s\" は追加されました。" % title) else: QMessageBox.information(self, "追加できませんでした", "\"%s\" はすでに存在しています。" % title) return elif self.currentMode == self.EditingMode: if self.oldTitle != title: if title not in self.contacts: QMessageBox.information(self, "編集しました", "\"%s\" は編集されました。" % self.oldTitle) del self.contacts[self.oldTitle] self.contacts[title] = memo else: QMessageBox.information(self, "編集できませんでした。", "\"%s\"はすでに存在しています。" % title) return elif self.oldMemo != memo: QMessageBox.information(self, "編集しました", "\"%s\"は編集されました。" % title) self.contacts[title] = {memo:memo, dokuryodate:dokuryodate, shoziflag:shoziflag, isbn:isbn } self.updateInterface(self.NavigationMode) # ボタンの処理 def cancel(self): self.titleLine.setText(self.oldTitle) self.memoText.setText(self.oldMemo) self.dokuryodate.setDate(self.oldDokuryodate) self.shoziflag.setChecked(self.oldShoziflag) self.isbnLine.setText(self.oldIsbn) self.updateInterface(self.NavigationMode) def removeContact(self): title = self.titleLine.text() memo = self.memoText.toPlainText() if title in self.contacts: button = QMessageBox.question(self, "Confirm Remove", "Are you sure you want to remove \"%s\"?" % title, QMessageBox.Yes | QMessageBox.No) if button == QMessageBox.Yes: self.previous() del self.contacts[title] QMessageBox.information(self, "Remove Successful", "\"%s\" has been removed from your memo book." % title) self.updateInterface(self.NavigationMode) def next(self): title = self.titleLine.text() it = iter(self.contacts) try: while True: this_title, _ = it.next() if this_title == title: next_title, next_memo, next_date = it.next() break except StopIteration: next_title, next_memo = iter(self.contacts).next() self.titleLine.setText(next_title) self.memoText.setText(next_memo) def previous(self): title = self.titleLine.text() prev_title = prev_memo = None for this_title, this_memo in self.contacts: if this_title == title: break prev_title = this_title prev_memo = this_memo else: self.titleLine.clear() self.memoText.clear() return if prev_title is None: for prev_title, prev_memo in self.contacts: pass self.titleLine.setText(prev_title) self.memoText.setText(prev_memo) def Contact(self): self.dialog.show() if self.dialog.exec_() == QDialog.Accepted: contactTitle = self.dialog.getFindText() found = False for this_title, this_memo in self.contacts: # if contactTitle in this_title: if re.search(contactTitle, this_title): found = True break if found: self.titleLine.setText(this_title) self.memoText.setText(self.contacts[this_title]) self.isbnLine.setText(self.contacts[this_title]) self.dokuryodate.setDate(self.contacts[this_title]) self.shoziflag.setChecked(self.contacts[this_title]) else: QMessageBox.information(self, "Contact Not Found", "Sorry, \"%s\" is not in your address book." % contactTitle) return self.updateInterface(self.NavigationMode) # ボタンを押せるか押せないかの処理 def updateInterface(self, mode): self.currentMode = mode if self.currentMode in (self.AddingMode, self.EditingMode): self.titleLine.setReadOnly(False) self.titleLine.setFocus(Qt.OtherFocusReason) self.isbnLine.setReadOnly(False) self.dokuryodate.setReadOnly(False) self.memoText.setReadOnly(False) self.addButton.setEnabled(False) self.editButton.setEnabled(False) self.removeButton.setEnabled(False) self.nextButton.setEnabled(False) self.previousButton.setEnabled(False) self.submitButton.show() self.cancelButton.show() self.loadButton.setEnabled(False) self.saveButton.setEnabled(False) self.exportButton.setEnabled(False) elif self.currentMode == self.NavigationMode: if not self.contacts: self.titleLine.clear() self.memoText.clear() self.dokuryodate.clear() self.isbnLine.clear() self.titleLine.setReadOnly(True) self.memoText.setReadOnly(True) self.dokuryodate.setReadOnly(True) self.shoziflag self.isbnLine.setReadOnly(True) self.addButton.setEnabled(True) number = len(self.contacts) self.editButton.setEnabled(number >= 1) self.removeButton.setEnabled(number >= 1) self.findButton.setEnabled(number > 2) self.nextButton.setEnabled(number > 1) self.previousButton.setEnabled(number >1 ) self.submitButton.hide() self.cancelButton.hide() self.exportButton.setEnabled(number >= 1) self.loadButton.setEnabled(True) self.saveButton.setEnabled(number >= 1) #テーブルの更新 i = 0 for title, obj in self.contacts.items(): titleItem = QTableWidgetItem(title) memoItem = QTableWidgetItem() memoItem.setData(Qt.DisplayRole, obj['memo']) if obj['shoziflag'] == True: maru = '○' else: maru = '' self.table.setItem(i, 0, titleItem) self.table.setItem(i, 1, QTableWidgetItem(obj['isbn'])) self.table.setItem(i, 2, QTableWidgetItem(obj['dokuryodate'])) self.table.setItem(i, 3, QTableWidgetItem(obj['memo'])) self.table.setItem(i, 4, QTableWidgetItem(maru)) i += 1 def saveToFile(self): fileTitle, _ = QFileDialog.getSaveFileName(self, "Save book log", '', "Book Log (*.bl);;All Files (*)") if not fileTitle: return try: out_file = open(str(fileTitle), 'wb') except IOError: QMessageBox.information(self, "Unable to open file", "There was an error opening \"%s\"" % fileTitle) return pickle.dump(self.contacts, out_file) out_file.close() def loadFromFile(self, fileName= None): if not fileName: fileName, _ = QFileDialog.getOpenFileName(self, "Open Address Book", '', "Address Book (*.bl);;All Files (*)") try: in_file = open(str(fileName), 'rb') except IOError: QMessageBox.information(self, "Unable to open file", "There was an error opening \"%s\"" % fileName) return self.contacts = pickle.load(in_file) in_file.close() if len(self.contacts) == 0: QMessageBox.information(self, "No contacts in file", "The file you are attempting to open contains no " "contacts.") else: for title, obj in self.contacts: date = QDate.fromString(obj['dokuryodate']) self.titleLine.setText(title) self.memoText.setText(obj['memo']) self.shoziflag.setChecked(obj['shoziflag']) self.isbnLine.setText(obj['isbn']) self.dokuryodate.setDate(date) self.updateInterface(self.NavigationMode) def exportAsVCard(self): title = str(self.titleLine.text()) memo = self.memoText.toPlainText() titleList = title.split() if len(titleList) > 1: firstName = nameList[0] lastName = nameList[-1] else: firstName = name lastName = '' fileName, _ = QFileDialog.getSaveFileName(self, "Export Contact", '', "vCard Files (*.vcf);;All Files (*)") if not fileName: return out_file = QFile(fileName) if not out_file.open(QIODevice.WriteOnly): QMessageBox.information(self, "Unable to open file", out_file.errorString()) return out_s = QTextStream(out_file) out_s << 'BEGIN:VCARD' << '\n' out_s << 'VERSION:2.1' << '\n' out_s << 'N:' << lastName << ';' << firstName << '\n' out_s << 'FN:' << ' '.join(nameList) << '\n' address.replace(';', '\\;') address.replace('\n', ';') address.replace(',', ' ') out_s << 'ADR;HOME:;' << address << '\n' out_s << 'END:VCARD' << '\n' QMessageBox.information(self, "Export Successful", "\"%s\" has been exported as a vCard." % name) def csvImport(self): with open('MediaMarkerExport.csv', newline='', encoding='utf-8') as f: reader = csv.reader(f) for r in reader: if r[2] == 1: flag = True else: flag = False self.contacts[r[0]] = {'isbn':r[1], 'dokuryodate':r[3].replace('-', '/'), 'shoziflag':flag, 'memo':''} aa = 0 def createMenus(self): self.fileMenu = self.menuBar().addMenu("&File") #self.fileMenu.addAction(self.newAct) #self.fileMenu.addAction(self.openAct) #self.fileMenu.addAction(self.saveAct) #self.fileMenu.addAction(self.printAct) #self.fileMenu.addSeparator() #self.fileMenu.addAction(self.exitAct) self.editMenu = self.menuBar().addMenu("&Edit") self.editMenu.addAction(self.undoAct) self.editMenu.addAction(self.redoAct) self.editMenu.addSeparator() self.editMenu.addAction(self.cutAct) self.editMenu.addAction(self.copyAct) self.editMenu.addAction(self.pasteAct) self.editMenu.addSeparator() self.helpMenu = self.menuBar().addMenu("&Help") self.helpMenu.addAction(self.aboutAct) self.helpMenu.addAction(self.aboutQtAct) self.formatMenu = self.editMenu.addMenu("&Format") self.formatMenu.addAction(self.boldAct) self.formatMenu.addAction(self.italicAct) self.formatMenu.addSeparator().setText("Alignment") self.formatMenu.addAction(self.leftAlignAct) self.formatMenu.addAction(self.rightAlignAct) self.formatMenu.addAction(self.justifyAct) self.formatMenu.addAction(self.centerAct) self.formatMenu.addSeparator() self.formatMenu.addAction(self.setLineSpacingAct) self.formatMenu.addAction(self.setParagraphSpacingAct) def tableclick(self, mi): row = mi.row() column = mi.column() #QMessageBox.information(self, "Export Successful", # "%d x %d" % (row, column)) title = self.titleLine.text() it = iter(self.contacts) try: n = 0 while True: next_title, next_obj = it.next() if row == n: break n += 1 except StopIteration: next_title, next_obj = iter(self.contacts).next() self.titleLine.setText(next_title) self.memoText.setText(next_obj['memo']) self.isbnLine.setText(next_obj['isbn']) self.dokuryodate.setDate(next_obj['dokuryodate']) self.shoziflag.setChecked(next_obj['shoziflag'])
class WidgetGallery(QDialog): def __init__(self, parent=None): super(WidgetGallery, self).__init__(parent) self.localization = de self.srcFileString = "" self.targetFileString = "" self.truePath = None self.firstRun = True styleComboBox = QComboBox() styleComboBox.addItems(QStyleFactory.keys()) self.createStartSection() self.createFileSelection() self.createDateSelection() self.createCheckboxArea() self.createInfoOutputSection() mainLayout = QGridLayout() mainLayout.addWidget(self.fileSelectionGroup, 1, 0) mainLayout.addWidget(self.dateSelectionGroupBox, 2, 0) mainLayout.addWidget(self.checkboxGroup, 3, 0) mainLayout.addWidget(self.startSection, 4, 0) mainLayout.addWidget(self.infoOutputSection, 5, 0) self.setLayout(mainLayout) self.setWindowTitle(self.localization.window_title) def createStartSection(self): '''Generate Aread containing the start button''' self.startSection = QGroupBox(self.localization.start_section) self.buttonGo = QPushButton(self.localization.button_go) self.buttonGo.setDisabled(True) self.buttonGo.clicked.connect(self.run) layout = QVBoxLayout() layout.addWidget(self.buttonGo) self.startSection.setLayout(layout) def createInfoOutputSection(self): '''Generate Aread containing progress, error and warning outputs''' self.infoOutputSection = QGroupBox(self.localization.infoOutput) self.infoTextBox = QTextBrowser() layout = QVBoxLayout() layout.addWidget(self.infoTextBox) self.infoOutputSection.setLayout(layout) def createFileSelection(self): '''Generate the area containing the file selectors and go button''' self.fileSelectionGroup = QGroupBox(self.localization.file_selection) # basic object # self.buttonSrcFile = QPushButton(self.localization.button_set_src_file) self.srcFileName = QLabel(self.localization.output_file) self.buttonTargetFile = QPushButton( self.localization.output_file_placeholder) self.boxUseSrcDir = QCheckBox(self.localization.button_use_src_dir) # connectors # self.buttonSrcFile.clicked.connect(self.selectSrcFile) self.buttonTargetFile.clicked.connect(self.selectTargetFile) self.boxUseSrcDir.stateChanged.connect(self.useSrcDir) self.boxUseSrcDir.setChecked(True) # layout # layout = QVBoxLayout() layout.addWidget(self.buttonSrcFile) layout.addWidget(self.srcFileName) layout.addWidget(self.buttonTargetFile) layout.addWidget(self.boxUseSrcDir) layout.addStretch(1) self.fileSelectionGroup.setLayout(layout) def createDateSelection(self): '''Generate the area containing the date selectors''' self.dateSelectionGroupBox = QGroupBox( self.localization.date_selection) layout = QGridLayout() self.startDateEdit = QDateEdit(calendarPopup=True) self.startDateEdit.setDisplayFormat("dd.MM.yyyy") self.startDateEdit.setReadOnly(True) self.startDateEdit.lineEdit().setDisabled(True) self.endDateEdit = QDateEdit(calendarPopup=True) self.endDateEdit.setDisplayFormat("dd.MM.yyyy") self.endDateEdit.setReadOnly(True) self.endDateEdit.lineEdit().setDisabled(True) self.startTimeEdit = QLineEdit("00:00") self.endTimeEdit = QLineEdit("23:59") self.startTimeEdit.setDisabled(True) self.endTimeEdit.setDisabled(True) layout.addWidget(self.startDateEdit, 0, 0) layout.addWidget(self.startTimeEdit, 0, 1) layout.addWidget(self.endDateEdit, 1, 0) layout.addWidget(self.endTimeEdit, 1, 1) layout.setColumnStretch(0, 1) layout.setColumnStretch(1, 1) self.dateSelectionGroupBox.setLayout(layout) def createCheckboxArea(self): '''Generate area with configuration options''' self.checkboxGroup = QGroupBox(self.localization.options) self.boxOTemp = QCheckBox(self.localization.button_otemp) self.boxOHumidity = QCheckBox(self.localization.button_ohumidity) layout = QVBoxLayout() layout.addWidget(self.boxOTemp) layout.addWidget(self.boxOHumidity) layout.addStretch(1) self.checkboxGroup.setLayout(layout) def run(self): '''Run generation with selected file and options''' # set save target if nessesary # self.infoTextBox.clear() self.buttonGo.setText(self.localization.button_go_wait) self.buttonGo.setDisabled(True) self.repaint() if self.boxUseSrcDir.isChecked(): target = self.srcFileString forcePath = False else: target = self.targetFileString forcePath = True # workaround for checkboxes changed # outsideDataNeeded = self.boxOTemp.isChecked( ) or self.boxOHumidity.isChecked() self.datapoints = input_backend.read_in_file( self.srcFileString, outsideData=outsideDataNeeded, plotOutsideTemp=self.boxOTemp.isChecked(), plotOutsideHum=self.boxOHumidity.isChecked(), qtTextBrowser=self.infoTextBox) # build dates # try: startTimeHelper = dt.datetime.strptime(self.startTimeEdit.text(), "%H:%M") endTimeHelper = dt.datetime.strptime(self.endTimeEdit.text(), "%H:%M") except ValueError as e: errorBox = QMessageBox(self) errorBox.setAttribute(PyQt5.QtCore.Qt.WA_DeleteOnClose) errorBox.setText(self.localization.bad_time) errorBox.setDetailedText(str(e)) errorBox.show() self.buttonGo.setText(self.localization.button_go) self.buttonGo.setDisabled(False) return startTimeOffset = dt.timedelta(hours=startTimeHelper.hour, minutes=startTimeHelper.minute) endTimeOffset = dt.timedelta(hours=endTimeHelper.hour, minutes=endTimeHelper.minute) zeroTime = dt.time(0, 0) startDateTime = dt.datetime.combine( self.startDateEdit.date().toPyDate(), zeroTime) startDateTime += startTimeOffset endDateTime = dt.datetime.combine(self.endDateEdit.date().toPyDate(), zeroTime) endDateTime += endTimeOffset try: self.truePath = plot.plot(self.datapoints, path=target, date1=startDateTime, date2=endDateTime, forcePath=forcePath, qtTextBrowser=self.infoTextBox) except ValueError as e: self.infoTextBox.append("ERROR: " + str(e)) self.buttonGo.setText(self.localization.button_go) return self.buttonGo.setText(self.localization.button_go) self.buttonGo.setDisabled(False) self.infoTextBox.append(self.localization.success) doneDialog = QMessageBox(self) doneDialog.setAttribute(PyQt5.QtCore.Qt.WA_DeleteOnClose) doneDialog.setText(self.localization.done_text) doneDialog.addButton(self.localization.open_pic, QMessageBox.YesRole) doneDialog.addButton(self.localization.close, QMessageBox.NoRole) doneDialog.buttonClicked.connect(self.openFile) doneDialog.show() def selectSrcFile(self): '''Function to select a src-file''' if not self.firstRun: targetDir = "" # meaning the last one opened else: targetDir = cp.CFG("default_source_dir") self.srcFileString = QFileDialog.getOpenFileName( self, self.localization.src_file_dialog, targetDir, "Data-Files (*.txt *.csv *.dbf *.xls)")[0] self.srcFileName.setText(self.srcFileString) if not self.srcFileString: return self.infoTextBox.append(self.localization.testing_input) self.firstRun = False try: self.datapoints = input_backend.read_in_file( self.srcFileString, outsideData=False, plotOutsideTemp=False, plotOutsideHum=False, qtTextBrowser=self.infoTextBox) except Exception as e: errorBox = QMessageBox(self) errorBox.setStyleSheet("QLabel{min-width: 700px;}") errorBox.setAttribute(PyQt5.QtCore.Qt.WA_DeleteOnClose) errorBox.setText(self.localization.error_read_in) errorBox.setDetailedText(traceback.format_exc()) errorBox.show() return start = self.datapoints[cp.CFG("plot_temperatur_key")].getFirstTime() self.startDateEdit.setDateTime(start) end = self.datapoints[cp.CFG("plot_temperatur_key")].getLastTime() self.endDateEdit.setDateTime(end) self.buttonGo.setDisabled(False) self.endDateEdit.setReadOnly(False) self.startDateEdit.setReadOnly(False) self.startDateEdit.lineEdit().setDisabled(False) self.endDateEdit.lineEdit().setDisabled(False) self.startTimeEdit.setDisabled(False) self.endTimeEdit.setDisabled(False) self.buttonGo.setFocus(PyQt5.QtCore.Qt.OtherFocusReason) self.infoTextBox.append(self.localization.testing_input_suc) def selectTargetFile(self): '''Function to select a target-file''' self.targetFileString = QFileDialog.getSaveFileName( self, self.localization.save_file_dialog)[0] if not self.targetFileString: return self.buttonTargetFile.setText(self.targetFileString) self.buttonGo.setDisabled(False) self.buttonGo.setFocus(PyQt5.QtCore.Qt.OtherFocusReason) def useSrcDir(self): '''Function to handle use src dir checkbox''' if self.boxUseSrcDir.isChecked(): self.buttonTargetFile.setDisabled(True) if self.srcFileString: self.buttonGo.setDisabled(False) self.srcFileName.setText(self.srcFileString) else: self.buttonTargetFile.setDisabled(False) if self.targetFileString: self.buttonTargetFile.setText(self.targetFileString) else: self.buttonGo.setDisabled(True) def openFile(self, button): if button.text() == self.localization.open_pic and self.truePath: PyQt5.QtGui.QDesktopServices.openUrl( QUrl.fromLocalFile(self.truePath)) else: pass