class Window(QWidget): def __init__(self): super().__init__() # Make widgets ################# self.edit1 = QDateEdit() self.edit2 = QDateEdit() self.edit3 = QDateEdit() self.edit1.setMinimumDate(datetime.date(year=2017, month=9, day=1)) self.edit2.setMinimumDate(datetime.date(year=2017, month=9, day=1)) self.edit3.setMinimumDate(datetime.date(year=2017, month=9, day=1)) self.edit1.setMaximumDate(datetime.date(year=2020, month=9, day=1)) self.edit2.setMaximumDate(datetime.date(year=2020, month=9, day=1)) self.edit3.setMaximumDate(datetime.date(year=2020, month=9, day=1)) self.edit1.setDate(datetime.datetime.now().date()) self.edit2.setDate(datetime.datetime.now().date()) self.edit3.setDate(datetime.datetime.now().date()) self.edit1.setCalendarPopup(True) self.edit2.setCalendarPopup(True) self.edit3.setCalendarPopup(True) # Format: see http://doc.qt.io/qt-5/qdatetime.html#toString-2 self.edit1.setDisplayFormat("yyyy-MM-dd") self.edit2.setDisplayFormat("dd/MM/yyyy") self.edit3.setDisplayFormat("dddd d MMMM yyyy") self.btn = QPushButton("Print") # Set button slot ############## self.btn.clicked.connect(self.printText) # Set the layout ############### vbox = QVBoxLayout() vbox.addWidget(self.edit1) vbox.addWidget(self.edit2) vbox.addWidget(self.edit3) vbox.addWidget(self.btn) self.setLayout(vbox) def printText(self): print(self.edit1.text()) print(self.edit2.text()) print(self.edit3.text())
class StudentTable(QTableWidget): def __init__(self, *args): self.rows = [] super(StudentTable, self).__init__(*args) self.gender = ['MALE', 'FEMALE'] self.medium = ['TAMIL', 'ENGLISH', 'MALAYALAM', 'TELUGU', 'HINDI'] self.gender_combo = None self.medium_combo = None self.dob_edit = None def add(self, student): self.add_row() print(self.rowCount()) self.setItem(self.rowCount() - 1, 0, QTableWidgetItem(student.name)) self.cellWidget(self.rowCount() - 1, 1).setCurrentText(student.gender) self.cellWidget(self.rowCount() - 1, 2).setDate(student.date_of_birth) self.cellWidget(self.rowCount() - 1, 3).setCurrentText(student.medium) def add_row(self): self.gender_combo = QComboBox() self.medium_combo = QComboBox() self.gender_combo.addItems(self.gender) self.medium_combo.addItems(self.medium) self.dob_edit = QDateEdit() self.dob_edit.setDisplayFormat('dd/MM/yyyy') self.dob_edit.setCalendarPopup(True) self.dob_edit.setDate(QDate.currentDate()) self.insertRow(self.rowCount()) self.setCellWidget(self.rowCount() - 1, 1, self.gender_combo) self.setCellWidget(self.rowCount() - 1, 2, self.dob_edit) self.setCellWidget(self.rowCount() - 1, 3, self.medium_combo)
def createHorizontalLayout(self): self.horizontalQWidget = QWidget() layout1 = QHBoxLayout() # Label Date label_date = QLabel('Date', self) layout1.addWidget(label_date) # QDateEdit: Edit Date DateEdit = QDateEdit(self) DateEdit.setDisplayFormat("dd-MMMM-yyyy") DateEdit.setLocale(QLocale(QLocale.English, QLocale.UnitedStates)) DateEdit.setCalendarPopup(True) layout1.addWidget(DateEdit) today = QDateTime.currentDateTime().date() DateEdit.setDate(QDate(today)) DateEdit.dateChanged[QDate].connect(self.on_ShowDate) self.date = DateEdit.date() self.date = self.date.toPyDate() self.year, self.month, self.day = self.date.year, '{:02d}'.format( self.date.month), '{:02d}'.format(self.date.day) # Edit path to Narrowband Data label_PathNarrow = QLabel('Path to Narrowband Data', self) layout1.addWidget(label_PathNarrow) self.PathText = QLineEdit("C:/NarrowbandData/", self) self.PathText.textChanged[str].connect(self.update_PathFileNames) layout1.addWidget(self.PathText) # Select directory button BtnSelectDir = QPushButton('...', self) BtnSelectDir.clicked.connect(self.on_SelectDir) layout1.addWidget(BtnSelectDir) self.horizontalQWidget.setLayout(layout1)
class ReceiptParserUI(QWidget): """ 仓单数据解析界面 """ def __init__(self, *args, **kwargs): super(ReceiptParserUI, self).__init__(*args, **kwargs) main_layout = QVBoxLayout() opt_layout = QHBoxLayout() self.current_date = QDateEdit(self) self.current_date.setDate(QDate.currentDate()) self.current_date.setCalendarPopup(True) self.current_date.setDisplayFormat("yyyy-MM-dd") opt_layout.addWidget(self.current_date) self.parser_button = QPushButton("提取数据", self) opt_layout.addWidget(self.parser_button) self.message_label = QLabel("请在【后台管理】-【行业数据】-【交易所数据】获取仓单源文件后再提取", self) opt_layout.addWidget(self.message_label) opt_layout.addStretch() main_layout.addLayout(opt_layout) self.preview_table = QTableWidget(self) self.preview_table.setColumnCount(7) self.preview_table.setHorizontalHeaderLabels( ["仓库编号", "简称", "品种", "交易代码", "日期", "仓单", "增减"]) main_layout.addWidget(self.preview_table) self.commit_button = QPushButton("提交保存", self) main_layout.addWidget(self.commit_button, alignment=Qt.AlignRight) self.setLayout(main_layout)
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
def createEditor(self, parent: QWidget, option: QStyleOptionViewItem, index: QModelIndex) -> QWidget: wdgt = QDateEdit(parent) wdgt.setDisplayFormat("yyyy-MM-dd") wdgt.setDate(datetime.date.today()) wdgt.setCalendarPopup(True) return wdgt
def select_reports(self): path_list, _ = QFileDialog.getOpenFileNames(self, '打开文件', '', "PDF files(*.pdf)") # 遍历报告文件填充预览表格与设置状态 self.review_table.setRowCount(len(path_list)) self.review_table.setColumnCount(4) self.review_table.setHorizontalHeaderLabels( ['序号', '报告名', '报告日期', '状态']) self.review_table.horizontalHeader().setSectionResizeMode( QHeaderView.Stretch) self.review_table.horizontalHeader().setSectionResizeMode( 0, QHeaderView.ResizeToContents) for row, file_path in enumerate(path_list): item_1 = QTableWidgetItem(str(row + 1)) item_1.file_path = file_path item_1.setTextAlignment(Qt.AlignCenter) self.review_table.setItem(row, 0, item_1) file_name = file_path.rsplit('/', 1)[1] item_2 = QTableWidgetItem(file_name) item_2.setTextAlignment(Qt.AlignCenter) self.review_table.setItem(row, 1, item_2) # 日期控件 date_edit = QDateEdit(QDate.currentDate()) date_edit.setCalendarPopup(True) date_edit.setDisplayFormat('yyyy-MM-dd') self.review_table.setCellWidget(row, 2, date_edit) # 装态 item_4 = QTableWidgetItem('等待上传') item_4.setTextAlignment(Qt.AlignCenter) self.review_table.setItem(row, 3, item_4)
def mainUI(self): layout = QHBoxLayout() scrollArea = QScrollArea() layout_sc = QHBoxLayout(scrollArea) row, col = self.df.shape self.tableWidge.setRowCount(row) self.tableWidge.setColumnCount(col) self.tableWidge.setHorizontalHeaderLabels(self.df.columns.tolist()) for i in range(row): for j in range(2): self.tableWidge.setItem(i, j, QTableWidgetItem(self.df.iloc[i, j])) for i in range(row): for j in range(2, 5): date = self.df.iloc[i, j] qdate = QDate(date.year, date.month, date.day) datedit = QDateEdit(qdate) datedit.setDisplayFormat('yyyy-MM-dd') datedit.setCalendarPopup(True) self.tableWidge.setCellWidget(i, j, datedit) layout_sc.addWidget(self.tableWidge) layout_sc.addWidget(self.btn_savecsv) layout.addWidget(scrollArea) self.setLayout(layout)
class inputBarang(QWidget): def __init__(self): super().__init__() self.createFormGroupBox() title = "Koperasi ITK" left = 0 right = 0 width = 400 height = 600 iconName = "assets/img/icon.png" mainLayout = QVBoxLayout() mainLayout.addWidget(self.formGroupBox) submitBtn = QPushButton("Submit") self.report = LaporanBarang() laporanBtn = QPushButton("Lihat Laporan") laporanBtn.clicked.connect(self.Lihat) mainLayout.addWidget(submitBtn) mainLayout.addWidget(laporanBtn) self.setWindowTitle(title) self.setWindowIcon(QtGui.QIcon(iconName)) self.setGeometry(left, right, height, width) self.setLayout(mainLayout) self.show() def createFormGroupBox(self): self.formGroupBox = QGroupBox("Input Barang") self.formGroupBox.setAlignment(QtCore.Qt.AlignCenter) self.layout = QFormLayout() self.nama = QLineEdit(self) self.nama.setPlaceholderText("Masukkan Nama Barang ") self.layout.addRow("Nama Barang :", self.nama) self.lokasi = QLineEdit(self) self.lokasi.setPlaceholderText("Masukkan Lokasi Barang ") self.layout.addRow("Lokasi :", self.lokasi) self.tanggal = QDateEdit() self.tanggal.setCalendarPopup(True) self.layout.addRow(QLabel("Tanggal Masuk :"), self.tanggal) self.harga = QLineEdit(self) self.harga.setPlaceholderText("Masukkan Harga ") self.layout.addRow("Harga :", self.harga) self.jumlah = QSpinBox(self) self.layout.addRow("Jumlah :", self.jumlah) self.formGroupBox.setLayout(self.layout) def Lihat(self): self.report.show()
def createEditor(self, parent, option, index): dateedit = QDateEdit(parent) #dateedit=QDateTimeEdit(parent) dateedit.setDateRange(self.minimum, self.maximum) dateedit.setAlignment(Qt.AlignRight | Qt.AlignVCenter) dateedit.setDisplayFormat(self.format) dateedit.setCalendarPopup(True) return dateedit
class EditSMSLink(QDialog): def __init__(self, sms_data, *args, **kwargs): super(EditSMSLink, self).__init__(*args, **kwargs) layout = QVBoxLayout(margin=0) print(sms_data) self.sms_id = sms_data['id'] # 时间布局 date_time_layout = QHBoxLayout() self.date_edit = QDateEdit(QDate.fromString(sms_data['date'], 'yyyy-MM-dd')) self.date_edit.setCalendarPopup(True) self.date_edit.setDisplayFormat('yyyy-MM-dd') date_time_layout.addWidget(QLabel('日期:')) date_time_layout.addWidget(self.date_edit) date_time_layout.addWidget(QLabel('时间:')) self.time_edit = QTimeEdit(QTime.fromString(sms_data['time'], 'HH:mm:ss')) self.time_edit.setDisplayFormat('HH:mm:ss') date_time_layout.addWidget(self.time_edit) date_time_layout.addStretch() layout.addLayout(date_time_layout) self.show_tips = QLabel() self.text_edit = QTextEdit(textChanged=self.set_show_tips_null) self.text_edit.setPlainText(sms_data['content']) layout.addWidget(self.text_edit) layout.addWidget(self.show_tips) layout.addWidget(QPushButton('确定', clicked=self.commit_sms_edited), alignment=Qt.AlignRight) self.setLayout(layout) self.resize(420, 240) self.setWindowTitle('编辑短信通') def set_show_tips_null(self): self.show_tips.setText('') # 确定提交修改 def commit_sms_edited(self): text = self.text_edit.toPlainText().strip(' ') if not text: self.show_tips.setText('请输入内容。') return # 提交 try: r = requests.put( url=settings.SERVER_ADDR + 'info/sms/' + str(self.sms_id) + '/?mc=' + settings.app_dawn.value('machine'), headers={'AUTHORIZATION': settings.app_dawn.value('AUTHORIZATION')}, data=json.dumps({ 'date': self.date_edit.text(), 'time': self.time_edit.text(), 'content': text }) ) response = json.loads(r.content.decode('utf-8')) if r.status_code != 201: raise ValueError(response['message']) except Exception as e: QMessageBox.information(self, '错误', str(e)) else: QMessageBox.information(self,'成功', '修改成功!') self.close()
def createEditor(self, parent, option, index): if index.column() == self.col: editor = QDateEdit(parent) editor.setDisplayFormat('dd.MM.yyyy') editor.date().toString('dd.MM.yyyy') editor.setCalendarPopup(True) return editor else: return QStyledItemDelegate.createEditor(self, parent, option, index)
def createEditor(self): editor = QDateEdit() editor.setMinimumDate(self.minimumDate) # editor.setSpecialValueText(self.placeholderText) editor.setCalendarPopup(True) style = self.style() editor.setStyleSheet(style) # setup connections editor.dateChanged[QDate].connect(self.onActivated) return editor
class CreateNewTradePolicyPopup(QDialog): def __init__(self, *args, **kwargs): super(CreateNewTradePolicyPopup, self).__init__(*args, **kwargs) layout = QVBoxLayout(margin=0) # 时间布局 date_time_layout = QHBoxLayout() self.date_edit = QDateEdit(QDate.currentDate()) self.date_edit.setCalendarPopup(True) self.date_edit.setDisplayFormat('yyyy-MM-dd') date_time_layout.addWidget(QLabel('日期:')) date_time_layout.addWidget(self.date_edit) date_time_layout.addWidget(QLabel('时间:')) self.time_edit = QTimeEdit(QTime.currentTime()) self.time_edit.setDisplayFormat('HH:mm:ss') date_time_layout.addWidget(self.time_edit) date_time_layout.addStretch() layout.addLayout(date_time_layout) self.text_edit = QTextEdit(textChanged=self.set_show_tips_null) layout.addWidget(self.text_edit) self.show_tips = QLabel() layout.addWidget(self.show_tips) layout.addWidget(QPushButton('确定', clicked=self.commit_trade_policy), alignment=Qt.AlignRight) self.setLayout(layout) self.resize(400, 200) self.setWindowTitle('新建短信通') def set_show_tips_null(self): self.show_tips.setText('') # 确定增加 def commit_trade_policy(self): text = self.text_edit.toPlainText().strip(' ') if not text: self.show_tips.setText('请输入内容。') return # 提交 try: r = requests.post( url=settings.SERVER_ADDR + 'info/trade-policy/?mc=' + settings.app_dawn.value('machine'), headers={'AUTHORIZATION': settings.app_dawn.value('AUTHORIZATION')}, data=json.dumps({ 'date': self.date_edit.text(), 'time': self.time_edit.text(), 'content': text }) ) response = json.loads(r.content.decode('utf-8')) if r.status_code != 201: raise ValueError(response['message']) except Exception as e: self.show_tips.setText(str(e)) else: self.show_tips.setText(response['message'])
class DateFrame(BaseFrame): def __init__(self, recovered, parent=None): super().__init__(parent) self.label.setText("Date:") self.date_edit = QDateEdit(QDate.currentDate()) self.date_edit.setCalendarPopup(True) self.date_edit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) if recovered: self.date_edit.setEnabled(False) self.layout.addWidget(self.label) self.layout.addWidget(self.date_edit) self.setLayout(self.layout)
def createEditor(self, parent, option, index): editor = QDateEdit(parent=parent) editor.setMinimumDate(datetime.datetime(year=2017, month=9, day=1)) editor.setMaximumDate(datetime.datetime(year=2020, month=9, day=1)) editor.setDisplayFormat("yyyy-MM-dd") editor.setCalendarPopup(True) # setFrame(): tell whether the line edit draws itself with a frame. # If enabled (the default) the line edit draws itself inside a frame, otherwise the line edit draws itself without any frame. editor.setFrame(False) return editor
class CreateNewSMSLink(QDialog): def __init__(self, *args, **kwargs): super(CreateNewSMSLink, self).__init__(*args, **kwargs) self.setAttribute(Qt.WA_DeleteOnClose) layout = QVBoxLayout() # 时间布局 date_time_layout = QHBoxLayout() self.date_edit = QDateEdit(QDate.currentDate()) self.date_edit.setCalendarPopup(True) self.date_edit.setDisplayFormat('yyyy-MM-dd') date_time_layout.addWidget(QLabel('日期:')) date_time_layout.addWidget(self.date_edit) date_time_layout.addWidget(QLabel('时间:')) self.time_edit = QTimeEdit(QTime.currentTime()) self.time_edit.setDisplayFormat('HH:mm:ss') date_time_layout.addWidget(self.time_edit) date_time_layout.addStretch() layout.addLayout(date_time_layout) self.text_edit = QTextEdit() layout.addWidget(self.text_edit) layout.addWidget(QPushButton('确定', clicked=self.commit_sms), alignment=Qt.AlignRight) self.setLayout(layout) self.setFixedSize(400, 200) self.setWindowTitle('新建短信通') # 确定增加 def commit_sms(self): text = self.text_edit.toPlainText().strip() if not text: QMessageBox.information(self,'错误', '请输入内容。') return # 提交 try: r = requests.post( url=settings.SERVER_ADDR + 'advise/shortmessage/', headers={'Content-Type': 'application/json;charset=utf8'}, data=json.dumps({ 'utoken':settings.app_dawn.value('AUTHORIZATION'), 'custom_time': self.date_edit.text() + ' ' + self.time_edit.text(), 'content': text }) ) response = json.loads(r.content.decode('utf-8')) if r.status_code != 201: raise ValueError(response['message']) except Exception as e: QMessageBox.information(self,'错误', str(e)) else: QMessageBox.information(self,'成功', "新增成功") self.close()
def _handleDate(self, name, parameterType, tooltip, defaultVal, minVal=None, maxVal=None): if (minVal is not None): minDate = QDate.fromString(minVal, 'yyyy-MM-dd') if (maxVal is not None): maxDate = QDate.fromString(maxVal, 'yyyy-MM-dd') defaultDate = QDate.fromString(defaultVal.strftime('%Y-%m-%d'), 'yyyy-MM-dd') widget = QDateEdit(self.parameterTable) widget.setDate(defaultDate) widget.setToolTip(tooltip) widget.setCalendarPopup(True) self.parameters[name] = [parameterType, widget] if (minVal is not None and maxVal is not None): self.parameters[name][1].setDateRange(minDate, maxDate)
def createEditor(self, parent, option, index): if (index.column() == ACTIONID and index.model().data( index, Qt.DisplayRole) == ACQUIRED): # Acquired is read-only return if index.column() == DATE: editor = QDateEdit(parent) editor.setMaximumDate(QDate.currentDate()) editor.setDisplayFormat("yyyy-MM-dd") if PYQT_VERSION_STR >= "4.1.0": editor.setCalendarPopup(True) editor.setAlignment(Qt.AlignRight | Qt.AlignVCenter) return editor else: return QSqlRelationalDelegate.createEditor(self, parent, option, index)
class FinanceCalendarPage(QWidget): def __init__(self, *args, **kwargs): super(FinanceCalendarPage, self).__init__(*args, **kwargs) layout = QVBoxLayout(margin=0, spacing=2) # 日期选择、信息展示与新增按钮 message_button_layout = QHBoxLayout() self.date_edit = QDateEdit(QDate.currentDate(), dateChanged=self.getCurrentFinanceCalendar) self.date_edit.setDisplayFormat('yyyy-MM-dd') self.date_edit.setCalendarPopup(True) message_button_layout.addWidget(QLabel('日期:')) message_button_layout.addWidget(self.date_edit) self.network_message_label = QLabel() message_button_layout.addWidget(self.network_message_label) message_button_layout.addStretch() # 伸缩 message_button_layout.addWidget(QPushButton('新增', clicked=self.create_finance_calendar), alignment=Qt.AlignRight) layout.addLayout(message_button_layout) # 当前数据显示表格 self.finance_table = FinanceCalendarTable() self.finance_table.network_result.connect(self.network_message_label.setText) layout.addWidget(self.finance_table) self.setLayout(layout) # 获取当前日期财经日历 def getCurrentFinanceCalendar(self): current_date = self.date_edit.text() current_page = 1 try: user_id = pickle.loads(settings.app_dawn.value("UKEY")) r = requests.get( url=settings.SERVER_ADDR + 'user/' + str(user_id) + '/fecalendar/?page=' +str(current_page)+'&page_size=50&date=' + current_date, ) response = json.loads(r.content.decode('utf-8')) if r.status_code != 200: raise ValueError(response['message']) except Exception as e: self.network_message_label.setText(str(e)) else: self.finance_table.showRowContents(response['fecalendar']) self.network_message_label.setText(response['message']) # 新增财经日历数据 def create_finance_calendar(self): popup = CreateNewFinanceCalendarPopup(parent=self) popup.exec_()
def setUI(self): self.cleanChoixVilleBool = False labelVille = QLabel("Ville / Code postal : ") labelJour = QLabel("Jour : ") textEditVille = QLineEdit() calendarJour = QDateEdit() calendarJour.setCalendarPopup(True) calendarJour.setDate(QDate.currentDate()) buttonValiderParam = QPushButton("Valider") splitterRes = QSplitter() splitterRes.setOrientation(Qt.Horizontal) hboxParam = QHBoxLayout() hboxChoixVille = QVBoxLayout() hboxResultats = QHBoxLayout() vboxGlobal = QVBoxLayout() hboxParam.addWidget(labelVille) hboxParam.addWidget(textEditVille) hboxParam.addWidget(labelJour) hboxParam.addWidget(calendarJour) hboxParam.addWidget(buttonValiderParam) hboxResultats.addWidget(splitterRes) vboxGlobal.addLayout(hboxParam) vboxGlobal.addLayout(hboxChoixVille) vboxGlobal.addLayout(hboxResultats) self.setLayout(vboxGlobal) buttonValiderParam.clicked.connect( lambda: self.choixVille(textEditVille.text(), calendarJour.date())) textEditVille.returnPressed.connect( lambda: self.choixVille(textEditVille.text(), calendarJour.date())) self.setWindowTitle('Super Cinemon 2000 ExtraPlus') self.show()
class MyApp(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): lbl = QLabel('QDateEdit') self.dateEditWidget = QDateEdit() # theDate = QDate() # self.dateEditWidget.setDate(theDate.currentDate()) # 현재 날짜 # theDate.setDate() # self.dateEditWidget.setDate(QDate.currentDate()) # 현재 날짜 self.dateEditWidget.setMinimumDate(QDate(2000, 1, 1)) self.dateEditWidget.setMaximumDate(QDate(2100, 12, 31)) self.dateEditWidget.setDisplayFormat('yyyy.MM.dd') self.dateEditWidget.setCalendarPopup(True) self.dateEditWidget.setDate(QDate(2020, 5, 1)) # 지정한 날짜 # self.dateEditWidget.setDate(QDate.currentDate()) self.dateEditWidget.dateChanged.connect(self.__dateChanged) vbox = QVBoxLayout() vbox.addWidget(lbl) vbox.addWidget(self.dateEditWidget) vbox.addStretch() self.setLayout(vbox) self.setWindowTitle('QDateEdit') self.setGeometry(300, 300, 300, 200) def __dateChanged(self): varQDate = self.dateEditWidget.date() # QDate print(varQDate) print(varQDate.toString('yyyy-MM-dd')) print(f'Year:{varQDate.year()} Month:{varQDate.month()} Day:{varQDate.day()}') print('5 Years later:\t', varQDate.addYears(5).toString('yyyy-MM-dd')) print('5 Months later:\t', varQDate.addMonths(5).toString('yyyy-MM-dd')) print('5 Days later:\t', varQDate.addDays(5).toString('yyyy-MM-dd'))
class NotesForm: note_id = None def __init__(self, note=None): self.form_layout = QFormLayout() self.date = QDateEdit() self.notes = QTextEdit() self.notes.setMinimumHeight(420) if note is not None and note['id'] is not None: self.note_id = note['id'] self.date.setCalendarPopup(True) self.date.setDisplayFormat('dd MMMM yyyy') if note is not None and note['date'] is not None: self.date.setDate(QDate.fromString(note['date'], "d.M.yyyy")) if note is not None and note['notes'] is not None: self.notes.setText(note['notes']) date_label = QLabel('Дата:') notes_label = QLabel('Примечание:') self.form_layout.addRow(date_label, self.date) self.form_layout.addRow(notes_label, self.notes) def get_layout(self): return self.form_layout def get_date(self): tmp_date = self.date.date() tmp_date = tmp_date.toPyDate() return '{0:%d.%m.%Y}'.format(tmp_date) def get_notes(self): return self.notes.toPlainText() def get_note_id(self): return self.note_id def validate_form(self): errors = list() # errors.append(self.first_name.validator())
def initUI(self): """ cal = QCalendarWidget(self) cal.setGridVisible(True) cal.move(20, 20) cal.clicked[QDate].connect(self.showDate) """ cal = QCalendarWidget(self) dtEdit = QDateEdit(QDate.currentDate(), self) dtEdit.setCalendarPopup(True) dtEdit.setCalendarWidget(cal) dtEdit.setDate(cal.selectedDate()) dtEdit.dateChanged.connect(self.showDate) self.lbl = QLabel(self) date = cal.selectedDate() self.lbl.setText(date.toString()) self.lbl.move(130, 260) self.setGeometry(300, 300, 350, 300) self.setWindowTitle('Calendar') self.show()
class WindowClass(QWidget): def __init__(self, parent=None): super(WindowClass, self).__init__(parent) self.btn = QPushButton(self) #self参数则让该按钮显示当前窗体中 self.btn.setText("点击获取日期信息") self.btn.clicked.connect(self.showdate) self.dateEdit = QDateEdit(self) self.timeEdit = QTimeEdit(self) self.dateTimeEdit = QDateTimeEdit(self) self.dateEdit.setCalendarPopup(True) #self.timeEdit.setCalendarPopup(True)#弹出界面是失效的注意; #self.dateTimeEdit.setCalendarPopup(True)#时间是无法选择的 self.dateEdit.move(10, 200) self.timeEdit.move(10, 100) self.dateTimeEdit.move(10, 300) self.dateEdit.setDisplayFormat("yyyy-MM-dd") self.timeEdit.setDisplayFormat("HH:mm:ss") self.dateTimeEdit.setDisplayFormat("yyyy-MM-dd HH:mm:ss") self.setWindowTitle("QDateEdit和QDateTimeEdit控件使用") def showdate(self): print(self.dateEdit.text())
class Inputbarang(QWidget): def __init__(self): super().__init__() Label = QLabel("Input Barang") Label.setAlignment(QtCore.Qt.AlignCenter) submitbtn = QPushButton("Submit") laporanbtn = QPushButton("Lihat Laporan") title = "Koperasi ITK" left = 0 right = 0 width = 400 height = 600 iconName = "assets/img/icon.png" self.setWindowTitle(title) self.setWindowIcon(QtGui.QIcon(iconName)) self.setGeometry(left, right, height, width) self.inputBarang() self.show() def inputBarang(self): self.form = QFormLayout(self) self.barang = QLineEdit(self) self.barang.setPlaceholderText("Nama Barang") self.form.addRow("Nama Barang", self.barang) self.lokasi = QLineEdit(self) self.lokasi.setPlaceholderText("Lokasi") self.form.addRow("Lokasi", self.lokasi) self.tglMasuk = QDateEdit(self) self.tglMasuk.setCalendarPopup(True) self.form.addRow("Tanggal Masuk", self.tglMasuk) self.harga = QLineEdit(self) self.harga.setPlaceholderText("Harga") self.form.addRow("Harga", self.harga) self.jumlah = QSpinBox(self) self.form.addRow("Masukkan Jumlah", self.jumlah) self.submit = QPushButton(self) self.submit.setText("Tambah") self.submit.clicked.connect(self.submit_btn) self.laporan = QPushButton(self) self.laporan.setText("Laporan") self.form.addRow(self.submit,self.laporan) def submit_btn(self): print("Nama Barang : {}\nLokasi : {}\nTanggal Masuk : {}\nHarga : {}\nJumlah : {}". format(self.nama.text(), self.noTel.text(), self.alamat.toPlainText(), self.jk.currentText(), self.Nik.text(), self.tglLahir.text()))
class AddTransactionsForm(QVBoxLayout): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Title self.title = QLabel(self.tr("Add Transaction")) self.title.setFont(TitleFont()) self.title.setAlignment(Qt.AlignCenter) # First line: Date self.label1 = QLabel(self.tr("Date")) # self.label1.setMinimumWidth(120) self.label1.setMaximumWidth(120) self.date_edit = QDateEdit(datetime.now()) self.date_edit.setDisplayFormat("dd/MM/yyyy") self.date_edit.setCalendarPopup(True) self.label1_checkbox = QPushButton(self.tr("Today")) self.label1_checkbox.setMaximumWidth(50) self.label1_checkbox.clicked.connect(self.setToday) self.line1 = QHBoxLayout() self.line1.addWidget(self.label1) self.line1.addWidget(self.date_edit) self.line1.addWidget(self.label1_checkbox) # Second Line: Account self.label2 = QLabel(self.tr("Sender Account")) self.label2.setMinimumWidth(120) self.label2.setMaximumWidth(120) self.senderaccount_select = QComboBox() self.senderaccount_select.setEditable(True) self.senderaccount_select.setDuplicatesEnabled(False) currentaccounts = [a[0] for a in balances.get_all_accounts()] self.senderaccount_select.addItems(currentaccounts) self.line2 = QHBoxLayout() self.line2.addWidget(self.label2) self.line2.addWidget(self.senderaccount_select, Qt.AlignLeft) # Third Line: Receiver Account self.label3 = QLabel(self.tr("Receiver Account")) self.label3.setMinimumWidth(120) self.label3.setMaximumWidth(120) self.receiveraccount_select = QComboBox() self.receiveraccount_select.setEditable(True) self.receiveraccount_select.setDuplicatesEnabled(False) currentaccounts = [a[0] for a in balances.get_all_accounts()] self.receiveraccount_select.addItems(currentaccounts) self.receiveraccount_select.setCurrentIndex(1) self.line3 = QHBoxLayout() self.line3.addWidget(self.label3) self.line3.addWidget(self.receiveraccount_select, Qt.AlignLeft) # Fourth Line: Amount self.label4 = QLabel(self.tr("Amount")) self.label4.setMinimumWidth(120) self.label4.setMaximumWidth(120) self.amount_select = QSpinBox() self.amount_select.setSuffix(" €") self.amount_select.setMinimum(0) self.amount_select.setMaximum(999999999) self.amount_select.setAccelerated(True) self.line4 = QHBoxLayout() self.line4.addWidget(self.label4) self.line4.addWidget(self.amount_select, Qt.AlignLeft) # Fifth Line: Deposit or Withdrawal self.group = QButtonGroup(self) self.deposit_checkbox = QCheckBox('Deposit') self.deposit_checkbox.stateChanged.connect(self.handlechecks) self.withdrawal_checkbox = QCheckBox('Withdrawal') self.withdrawal_checkbox.stateChanged.connect(self.handlechecks) self.transfer_checkbox = QCheckBox('Transfer') self.transfer_checkbox.stateChanged.connect(self.handlechecks) self.line5 = QHBoxLayout() self.line5.addWidget(self.deposit_checkbox) self.line5.addWidget(self.withdrawal_checkbox) self.line5.addWidget(self.transfer_checkbox) # Sixth Line: Description self.label6 = QLabel(self.tr("Description")) self.label6.setFixedWidth(120) self.description_edit = QLineEdit() self.line6 = QHBoxLayout() self.line6.addWidget(self.label6) self.line6.addWidget(self.description_edit) # Buttons self.button_layout = QHBoxLayout() self.insert_button = QPushButton(self.tr("Insert")) self.insert_button.setMaximumWidth(50) self.button_layout.setAlignment(Qt.AlignHCenter | Qt.AlignTop) # Centering it self.button_layout.setContentsMargins(QMargins( 10, 10, 10, 10)) # A little bit of margin self.insert_button.clicked.connect(self.insertTransaction) self.button_layout.addWidget(self.insert_button, Qt.AlignVCenter) self.addWidget(self.title) self.addLayout(self.line1) self.addLayout(self.line2) self.addLayout(self.line3) self.addLayout(self.line4) self.addLayout(self.line5) self.addLayout(self.line6) self.addLayout(self.button_layout) # Signal handle self.receiveraccount_select.currentTextChanged.connect( self.handleselections) self.senderaccount_select.currentTextChanged.connect( self.handleselections) def setToday(self): self.date_edit.setDate(datetime.now()) def insertTransaction(self): # Current data self.current_date = datetime(self.date_edit.date().year(), self.date_edit.date().month(), self.date_edit.date().day()).timestamp() self.current_senderaccount = self.senderaccount_select.currentText() self.current_receiveraccount = self.receiveraccount_select.currentText( ) self.current_amount = int(float(self.amount_select.text()[:-2])) # Deposit/Withdrawal/Transfer if self.deposit_checkbox.isChecked(): self.currenttype = 1 elif self.withdrawal_checkbox.isChecked(): self.currenttype = -1 else: # No checked defaults to transfer self.currenttype = 0 # If there is a new account involved, it should be created first all_accounts = [i[0] for i in balances.get_all_accounts()] if self.current_senderaccount not in all_accounts: balances.add_account(self.current_senderaccount, 0) if self.current_receiveraccount not in all_accounts: balances.add_account(self.current_receiveraccount, 0) # Adding the transaction on db transactions.add_transaction(self.current_date, self.current_senderaccount, self.current_amount, self.current_receiveraccount, self.currenttype, description=self.description_edit.text()) def handlechecks(self, state): """ Proper checkbox behavour """ # Checking if state is checked if state == Qt.Checked: if self.sender() == self.deposit_checkbox: # making others unchecked self.withdrawal_checkbox.setChecked(False) self.transfer_checkbox.setChecked(False) elif self.sender() == self.withdrawal_checkbox: # making others unchecked self.deposit_checkbox.setChecked(False) self.transfer_checkbox.setChecked(False) elif self.sender() == self.transfer_checkbox: # making others unchecked self.deposit_checkbox.setChecked(False) self.withdrawal_checkbox.setChecked(False) # Now that only one checkbox is checked, we change the form according to the transfer type if self.deposit_checkbox.isChecked(): self.senderaccount_select.setCurrentText("Cash") if self.withdrawal_checkbox.isChecked(): self.receiveraccount_select.setCurrentText("Cash") else: pass def handleselections(self): """ Establishing certain retrictions """ if self.receiveraccount_select.currentText( ) == self.senderaccount_select.currentText(): # We move the currentIndex, so that both accounts can't be the same self.senderaccount_select.setStyleSheet("color: red") self.receiveraccount_select.setStyleSheet("color:red") self.insert_button.hide() else: self.senderaccount_select.setStyleSheet("") self.receiveraccount_select.setStyleSheet("") self.insert_button.show() # 'Cash' special cases if self.senderaccount_select.currentText() != 'Cash' and \ self.receiveraccount_select.currentText() != 'Cash': self.transfer_checkbox.setChecked(True)
class DataWidget(QWidget): def __init__(self): super(DataWidget, self).__init__(None) self.read_data_file(config.HISTORIC_DATA) self.start_date = date(2016, 10, 1) self.end_date = date(2016, 11, 1) self.graph = GraphCanvas(self.data_frame) with open(config.LOGFILE, 'w', newline='') as logfile: logwriter = csv.writer(logfile) logwriter.writerow(config.headers) # options group box self.optionsGroupBox = QGroupBox("Options") options_layout = QVBoxLayout() date_range_layout = QFormLayout() start_date_label = QLabel("Start Date:") self.start_date_box = QDateEdit(self.start_date) self.start_date_box.setCalendarPopup(True) self.start_date_box.setDisplayFormat(config.DATE_DISPLAY_FORMAT) self.start_date_box.dateChanged.connect(self.plot) end_date_label = QLabel("End Date:") self.end_date_box = QDateEdit(self.end_date) self.end_date_box.setCalendarPopup(True) self.end_date_box.setDisplayFormat(config.DATE_DISPLAY_FORMAT) self.end_date_box.dateChanged.connect(self.plot) date_range_layout.addRow(start_date_label, self.start_date_box) date_range_layout.addRow(end_date_label, self.end_date_box) # days of week self.sundayCheckBox = QCheckBox("Sunday") self.mondayCheckBox = QCheckBox("Monday") self.tuesdayCheckBox = QCheckBox("Tuesday") self.wednesdayCheckBox = QCheckBox("Wednesday") self.thursdayCheckBox = QCheckBox("Thursday") self.fridayCheckBox = QCheckBox("Friday") self.saturdayCheckBox = QCheckBox("Saturday") self.sundayCheckBox.toggled.connect(self.plot) self.mondayCheckBox.toggled.connect(self.plot) self.tuesdayCheckBox.toggled.connect(self.plot) self.wednesdayCheckBox.toggled.connect(self.plot) self.thursdayCheckBox.toggled.connect(self.plot) self.fridayCheckBox.toggled.connect(self.plot) self.saturdayCheckBox.toggled.connect(self.plot) options_layout.addLayout(date_range_layout) options_layout.addWidget(self.sundayCheckBox) options_layout.addWidget(self.mondayCheckBox) options_layout.addWidget(self.tuesdayCheckBox) options_layout.addWidget(self.wednesdayCheckBox) options_layout.addWidget(self.thursdayCheckBox) options_layout.addWidget(self.fridayCheckBox) options_layout.addWidget(self.saturdayCheckBox) options_layout.addWidget(QPushButton("Button")) self.optionsGroupBox.setLayout(options_layout) # graph group box self.graphGroupBox = QGroupBox("Graph") graphLayout = QVBoxLayout() graphLayout.addWidget(self.graph) self.graphGroupBox.setLayout(graphLayout) # choice group box self.choiceGroupBox = QGroupBox("Choice") choice_layout = QVBoxLayout() choice_layout_1 = QHBoxLayout() choice_layout_1.addWidget(QLabel("A")) choice_layout_1.addWidget(QLabel("B")) choice_layout_1.addWidget(QLabel("C")) choice_layout_1.addWidget(QLabel("D")) choice_layout_2 = QHBoxLayout() self.decision_value_1 = QSpinBox() self.decision_value_2 = QSpinBox() self.decision_value_3 = QSpinBox() self.decision_value_4 = QSpinBox() choice_layout_2.addWidget(self.decision_value_1) choice_layout_2.addWidget(self.decision_value_2) choice_layout_2.addWidget(self.decision_value_3) choice_layout_2.addWidget(self.decision_value_4) choice_layout.addLayout(choice_layout_1) choice_layout.addLayout(choice_layout_2) self.decision_value_1.setValue(42) self.choiceGroupBox.setLayout(choice_layout) # count-down timer self.timerGroupBox = QGroupBox("Timer") timer_layout = QVBoxLayout() self.timerGroupBox.setLayout(timer_layout) self.count_down_timer = CountDownTimer() timer_layout.addWidget(self.count_down_timer.lcd) # central widget frame = QFrame(self) self.grid = QGridLayout(frame) self.grid.setSpacing(16) self.grid.setContentsMargins(16, 16, 16, 16) self.grid.addWidget(self.optionsGroupBox, 0, 0, 2, 1) self.grid.addWidget(self.graphGroupBox, 0, 1, 2, 1) self.grid.addWidget(self.timerGroupBox, 0, 2) self.grid.addWidget(self.choiceGroupBox, 2, 1) self.grid.setColumnStretch(0, 2) self.grid.setColumnStretch(1, 6) self.grid.setColumnStretch(2, 1) self.grid.setRowStretch(0, 1) self.grid.setRowStretch(1, 2) self.grid.setRowStretch(2, 2) self.setLayout(self.grid) def read_data_file(self, data_file): """read data_file and import it's content as pandas dataframe""" dateparse = lambda x: pd.datetime.strptime(x, '%Y-%m-%d') self.data_frame = pd.read_csv(data_file, index_col=0, parse_dates=True) def plot(self): """ Method to update start / end dates upon selection. Fetch the start / end dates, convert the QTime datatype to DateTime.Date datatype, and plot the graph. """ self.start_date = self.start_date_box.date().toPyDate() self.end_date = self.end_date_box.date().toPyDate() self.graph.plot(self.data_frame.loc[self.start_date : self.end_date]) def add_log_row(self): """ Write data in the log file :return: """ new_row = [config.id, config.age, config.male, config.field, 'test_condition', datetime.now()] with open(config.LOGFILE, 'a', newline='') as logfile: logwriter = csv.writer(logfile) logwriter.writerow(new_row)
class Qt_Frame(QMainWindow): def __init__(self, *args, **kw): super(Qt_Frame, self).__init__(*args, **kw) self.secret_f = SecretFile() #self.secret_f._save_file("456") thread = MyThread(target=self.secret_f._save_tmpfile, args=("456",)) thread.start() self._initUI() def _initUI(self): self.resize(400,250) self.setWindowTitle("查询系统 v1.01") self.main_widget = QWidget() self.main_layout = QGridLayout() self.main_widget.setLayout(self.main_layout) self.left_widget = QWidget() self.left_widget.setObjectName("left_widget") self.left_layout = QGridLayout() self.left_widget.setLayout(self.left_layout) self.center_widget = QWidget() self.center_widget.setObjectName("center_widget") self.center_layout = QGridLayout() self.center_widget.setLayout(self.center_layout) self.right_widget = QWidget() self.right_widget.setObjectName("right_widget") self.right_layout = QGridLayout() self.right_widget.setLayout(self.right_layout) self.main_layout.addWidget(self.left_widget, 0, 0, 10, 1) self.main_layout.addWidget(self.center_widget, 0, 1, 10, 4) self.main_layout.addWidget(self.right_widget, 0, 5, 10, 1) self._leftUI() self._centerUI() #self._rightUI() self.left_layout.setAlignment(Qt.AlignBottom) self.center_layout.setAlignment(Qt.AlignCenter) self.right_layout.setAlignment(Qt.AlignTop) self.setCentralWidget(self.main_widget) def _leftUI(self): self.left_soft = QPushButton(qtawesome.icon('fa.folder-open', color='green'), "") self.left_soft.clicked.connect(self._leadialog) self.left_layout.addWidget(self.left_soft, 0, 1, 2, 1) def _centerUI(self): self.query_name = QLineEdit() self.query_name.setPlaceholderText("请输入要查询的名字") self.query_secret = QLineEdit() self.query_secret.setPlaceholderText("请输入密码") self.query_secret.setEchoMode(QLineEdit.Password) self.date1 = QDateEdit(QDate.currentDate()) self.date1.setCalendarPopup(True) self.date2 = QDateEdit(QDate.currentDate()) self.date2.setCalendarPopup(True) self.job_combox = QComboBox(minimumWidth=100) self.job_combox.addItems(["业务员", "操作员"]) self.button = QPushButton("运行") self.button.clicked.connect(self._opendialog) self.center_layout.addWidget(QLabel("姓名:"), 0, 0, 2, 1) self.center_layout.addWidget(self.query_name, 0, 1, 2, 3) self.center_layout.addWidget(QLabel("密码:"), 3, 0, 2, 1) self.center_layout.addWidget(self.query_secret, 3, 1, 2, 3) self.center_layout.addWidget(QLabel("类型:"), 6, 0, 2, 1) self.center_layout.addWidget(self.job_combox, 6, 1, 2, 3) self.center_layout.addWidget(self.button, 9, 1, 1, 3) def _rightUI(self): self.right_mini = QPushButton("") # 最小化 self.right_visit = QPushButton("") # 空白按钮 self.right_close = QPushButton("") # 关闭 self.right_layout.addWidget(self.right_mini, 0, 0, 1, 1) self.right_layout.addWidget(self.right_visit, 0, 1, 1, 1) self.right_layout.addWidget(self.right_close, 0, 2, 1, 1) def _opendialog(self): name = self.query_name.text() pwd = self.query_secret.text() job = self.job_combox.currentText() my = New_Dialog(self) if name and pwd: if my._name_and_pwd(name, pwd): QMessageBox.warning(self, "消息框标题", "请确帐号或密码不正确", QMessageBox.Ok) return else: my._creat_table_show(name, job) my.exec_() else: QMessageBox.warning(self, "消息框标题", "请确定帐号或密码是否输入正确", QMessageBox.Ok) def _leadialog(self): my = Lead_Data() my.exec_() def __del__(self): self.secret_f._del_file()
class Window(QWidget): def __init__(self): super(Window, self).__init__() self.proxyModel = MySortFilterProxyModel(self) self.proxyModel.setDynamicSortFilter(True) self.sourceView = QTreeView() self.sourceView.setRootIsDecorated(False) self.sourceView.setAlternatingRowColors(True) sourceLayout = QHBoxLayout() sourceLayout.addWidget(self.sourceView) sourceGroupBox = QGroupBox("Original Model") sourceGroupBox.setLayout(sourceLayout) self.filterCaseSensitivityCheckBox = QCheckBox("Case sensitive filter") self.filterCaseSensitivityCheckBox.setChecked(True) self.filterPatternLineEdit = QLineEdit() self.filterPatternLineEdit.setText("Grace|Sports") filterPatternLabel = QLabel("&Filter pattern:") filterPatternLabel.setBuddy(self.filterPatternLineEdit) self.filterSyntaxComboBox = QComboBox() self.filterSyntaxComboBox.addItem("Regular expression", QRegExp.RegExp) self.filterSyntaxComboBox.addItem("Wildcard", QRegExp.Wildcard) self.filterSyntaxComboBox.addItem("Fixed string", QRegExp.FixedString) self.fromDateEdit = QDateEdit() self.fromDateEdit.setDate(QDate(2006, 12, 22)) self.fromDateEdit.setCalendarPopup(True) fromLabel = QLabel("F&rom:") fromLabel.setBuddy(self.fromDateEdit) self.toDateEdit = QDateEdit() self.toDateEdit.setDate(QDate(2007, 1, 5)) self.toDateEdit.setCalendarPopup(True) toLabel = QLabel("&To:") toLabel.setBuddy(self.toDateEdit) self.filterPatternLineEdit.textChanged.connect(self.textFilterChanged) self.filterSyntaxComboBox.currentIndexChanged.connect(self.textFilterChanged) self.filterCaseSensitivityCheckBox.toggled.connect(self.textFilterChanged) self.fromDateEdit.dateChanged.connect(self.dateFilterChanged) self.toDateEdit.dateChanged.connect(self.dateFilterChanged) self.proxyView = QTreeView() self.proxyView.setRootIsDecorated(False) self.proxyView.setAlternatingRowColors(True) self.proxyView.setModel(self.proxyModel) self.proxyView.setSortingEnabled(True) self.proxyView.sortByColumn(1, Qt.AscendingOrder) self.textFilterChanged() self.dateFilterChanged() proxyLayout = QGridLayout() proxyLayout.addWidget(self.proxyView, 0, 0, 1, 3) proxyLayout.addWidget(filterPatternLabel, 1, 0) proxyLayout.addWidget(self.filterPatternLineEdit, 1, 1) proxyLayout.addWidget(self.filterSyntaxComboBox, 1, 2) proxyLayout.addWidget(self.filterCaseSensitivityCheckBox, 2, 0, 1, 3) proxyLayout.addWidget(fromLabel, 3, 0) proxyLayout.addWidget(self.fromDateEdit, 3, 1, 1, 2) proxyLayout.addWidget(toLabel, 4, 0) proxyLayout.addWidget(self.toDateEdit, 4, 1, 1, 2) proxyGroupBox = QGroupBox("Sorted/Filtered Model") proxyGroupBox.setLayout(proxyLayout) mainLayout = QVBoxLayout() mainLayout.addWidget(sourceGroupBox) mainLayout.addWidget(proxyGroupBox) self.setLayout(mainLayout) self.setWindowTitle("Custom Sort/Filter Model") self.resize(500, 450) def setSourceModel(self, model): self.proxyModel.setSourceModel(model) self.sourceView.setModel(model) def textFilterChanged(self): syntax = QRegExp.PatternSyntax( self.filterSyntaxComboBox.itemData( self.filterSyntaxComboBox.currentIndex())) caseSensitivity = ( self.filterCaseSensitivityCheckBox.isChecked() and Qt.CaseSensitive or Qt.CaseInsensitive) regExp = QRegExp(self.filterPatternLineEdit.text(), caseSensitivity, syntax) self.proxyModel.setFilterRegExp(regExp) def dateFilterChanged(self): self.proxyModel.setFilterMinimumDate(self.fromDateEdit.date()) self.proxyModel.setFilterMaximumDate(self.toDateEdit.date())
class GalleryDialog(QWidget): """ A window for adding/modifying gallery. Pass a list of QModelIndexes to edit their data or pass a path to preset path """ gallery_queue = queue.Queue() SERIES = pyqtSignal(list) SERIES_EDIT = pyqtSignal(list, int) #gallery_list = [] # might want to extend this to allow mass gallery adding def __init__(self, parent=None, arg=None): super().__init__(parent, Qt.Dialog) self.setAttribute(Qt.WA_DeleteOnClose) self.parent_widget = parent log_d('Triggered Gallery Edit/Add Dialog') m_l = QVBoxLayout() self.main_layout = QVBoxLayout() dummy = QWidget(self) scroll_area = QScrollArea(self) scroll_area.setWidgetResizable(True) scroll_area.setFrameStyle(scroll_area.StyledPanel) dummy.setLayout(self.main_layout) scroll_area.setWidget(dummy) m_l.addWidget(scroll_area, 3) final_buttons = QHBoxLayout() final_buttons.setAlignment(Qt.AlignRight) m_l.addLayout(final_buttons) self.done = QPushButton("Done") self.done.setDefault(True) cancel = QPushButton("Cancel") final_buttons.addWidget(cancel) final_buttons.addWidget(self.done) def new_gallery(): self.setWindowTitle('Add a new gallery') self.newUI() self.commonUI() self.done.clicked.connect(self.accept) cancel.clicked.connect(self.reject) if arg: if isinstance(arg, list): self.setWindowTitle('Edit gallery') self.position = arg[0].row() for index in arg: gallery = index.data(Qt.UserRole+1) self.commonUI() self.setGallery(gallery) self.done.clicked.connect(self.accept_edit) cancel.clicked.connect(self.reject_edit) elif isinstance(arg, str): new_gallery() self.choose_dir(arg) else: new_gallery() log_d('GalleryDialog: Create UI: successful') #TODO: Implement a way to mass add galleries #IDEA: Extend dialog in a ScrollArea with more forms... self.setLayout(m_l) self.resize(500,560) frect = self.frameGeometry() frect.moveCenter(QDesktopWidget().availableGeometry().center()) self.move(frect.topLeft()) #self.setAttribute(Qt.WA_DeleteOnClose) def commonUI(self): f_web = QGroupBox("Metadata from the Web") f_web.setCheckable(False) self.main_layout.addWidget(f_web) web_main_layout = QVBoxLayout() web_layout = QHBoxLayout() web_main_layout.addLayout(web_layout) f_web.setLayout(web_main_layout) f_gallery = QGroupBox("Gallery Info") f_gallery.setCheckable(False) self.main_layout.addWidget(f_gallery) gallery_layout = QFormLayout() f_gallery.setLayout(gallery_layout) def basic_web(name): return QLabel(name), QLineEdit(), QPushButton("Get metadata"), QProgressBar() url_lbl, self.url_edit, url_btn, url_prog = basic_web("URL:") url_btn.clicked.connect(lambda: self.web_metadata(self.url_edit.text(), url_btn, url_prog)) url_prog.setTextVisible(False) url_prog.setMinimum(0) url_prog.setMaximum(0) web_layout.addWidget(url_lbl, 0, Qt.AlignLeft) web_layout.addWidget(self.url_edit, 0) web_layout.addWidget(url_btn, 0, Qt.AlignRight) web_layout.addWidget(url_prog, 0, Qt.AlignRight) self.url_edit.setPlaceholderText("Paste g.e-hentai/exhentai gallery url or just press the button.") url_prog.hide() self.title_edit = QLineEdit() self.author_edit = QLineEdit() author_completer = misc.GCompleter(self, False, True, False) author_completer.setCaseSensitivity(Qt.CaseInsensitive) self.author_edit.setCompleter(author_completer) self.descr_edit = QTextEdit() self.descr_edit.setFixedHeight(45) self.descr_edit.setAcceptRichText(True) self.lang_box = QComboBox() self.lang_box.addItems(["English", "Japanese", "Other"]) self.lang_box.setCurrentIndex(0) tags_l = QVBoxLayout() tag_info = misc.ClickedLabel("How do i write namespace & tags? (hover)", parent=self) tag_info.setToolTip("Ways to write tags:\n\nNormal tags:\ntag1, tag2, tag3\n\n"+ "Namespaced tags:\nns1:tag1, ns1:tag2\n\nNamespaced tags with one or more"+ " tags under same namespace:\nns1:[tag1, tag2, tag3], ns2:[tag1, tag2]\n\n"+ "Those three ways of writing namespace & tags can be combined freely.\n"+ "Tags are seperated by a comma, NOT whitespace.\nNamespaces will be capitalized while tags"+ " will be lowercased.") tag_info.setToolTipDuration(99999999) tags_l.addWidget(tag_info) self.tags_edit = misc.CompleterTextEdit() self.tags_edit.setCompleter(misc.GCompleter(self, False, False)) tags_l.addWidget(self.tags_edit, 3) self.tags_edit.setFixedHeight(70) self.tags_edit.setPlaceholderText("Press Tab to autocomplete (Ctrl + E to show popup)") self.type_box = QComboBox() self.type_box.addItems(["Manga", "Doujinshi", "Artist CG Sets", "Game CG Sets", "Western", "Image Sets", "Non-H", "Cosplay", "Other"]) self.type_box.setCurrentIndex(0) #self.type_box.currentIndexChanged[int].connect(self.doujin_show) #self.doujin_parent = QLineEdit() #self.doujin_parent.setVisible(False) self.status_box = QComboBox() self.status_box.addItems(["Unknown", "Ongoing", "Completed"]) self.status_box.setCurrentIndex(0) self.pub_edit = QDateEdit() self.pub_edit.setCalendarPopup(True) self.pub_edit.setDate(QDate.currentDate()) self.path_lbl = QLabel("") self.path_lbl.setWordWrap(True) link_layout = QHBoxLayout() self.link_lbl = QLabel("") self.link_lbl.setWordWrap(True) self.link_edit = QLineEdit() link_layout.addWidget(self.link_edit) link_layout.addWidget(self.link_lbl) self.link_edit.hide() self.link_btn = QPushButton("Modify") self.link_btn.setFixedWidth(50) self.link_btn2 = QPushButton("Set") self.link_btn2.setFixedWidth(40) self.link_btn.clicked.connect(self.link_modify) self.link_btn2.clicked.connect(self.link_set) link_layout.addWidget(self.link_btn) link_layout.addWidget(self.link_btn2) self.link_btn2.hide() gallery_layout.addRow("Title:", self.title_edit) gallery_layout.addRow("Author:", self.author_edit) gallery_layout.addRow("Description:", self.descr_edit) gallery_layout.addRow("Language:", self.lang_box) gallery_layout.addRow("Tags:", tags_l) gallery_layout.addRow("Type:", self.type_box) gallery_layout.addRow("Status:", self.status_box) gallery_layout.addRow("Publication Date:", self.pub_edit) gallery_layout.addRow("Path:", self.path_lbl) gallery_layout.addRow("Link:", link_layout) self.title_edit.setFocus() def _find_combobox_match(self, combobox, key, default): f_index = combobox.findText(key, Qt.MatchFixedString) try: combobox.setCurrentIndex(f_index) except: combobox.setCurrentIndex(default) def setGallery(self, gallery): "To be used for when editing a gallery" self.gallery = gallery self.url_edit.setText(gallery.link) self.title_edit.setText(gallery.title) self.author_edit.setText(gallery.artist) self.descr_edit.setText(gallery.info) self.tags_edit.setText(utils.tag_to_string(gallery.tags)) self._find_combobox_match(self.lang_box, gallery.language, 2) self._find_combobox_match(self.type_box, gallery.type, 0) self._find_combobox_match(self.status_box, gallery.status, 0) gallery_pub_date = "{}".format(gallery.pub_date).split(' ') try: self.gallery_time = datetime.strptime(gallery_pub_date[1], '%H:%M:%S').time() except IndexError: pass qdate_pub_date = QDate.fromString(gallery_pub_date[0], "yyyy-MM-dd") self.pub_edit.setDate(qdate_pub_date) self.link_lbl.setText(gallery.link) self.path_lbl.setText(gallery.path) def newUI(self): f_local = QGroupBox("Directory/Archive") f_local.setCheckable(False) self.main_layout.addWidget(f_local) local_layout = QHBoxLayout() f_local.setLayout(local_layout) choose_folder = QPushButton("From Directory") choose_folder.clicked.connect(lambda: self.choose_dir('f')) local_layout.addWidget(choose_folder) choose_archive = QPushButton("From Archive") choose_archive.clicked.connect(lambda: self.choose_dir('a')) local_layout.addWidget(choose_archive) self.file_exists_lbl = QLabel() local_layout.addWidget(self.file_exists_lbl) self.file_exists_lbl.hide() def choose_dir(self, mode): """ Pass which mode to open the folder explorer in: 'f': directory 'a': files Or pass a predefined path """ self.done.show() self.file_exists_lbl.hide() if mode == 'a': name = QFileDialog.getOpenFileName(self, 'Choose archive', filter=utils.FILE_FILTER) name = name[0] elif mode == 'f': name = QFileDialog.getExistingDirectory(self, 'Choose folder') elif mode: if os.path.exists(mode): name = mode else: return None if not name: return head, tail = os.path.split(name) name = os.path.join(head, tail) parsed = utils.title_parser(tail) self.title_edit.setText(parsed['title']) self.author_edit.setText(parsed['artist']) self.path_lbl.setText(name) l_i = self.lang_box.findText(parsed['language']) if l_i != -1: self.lang_box.setCurrentIndex(l_i) if gallerydb.GalleryDB.check_exists(name): self.file_exists_lbl.setText('<font color="red">Gallery already exists.</font>') self.file_exists_lbl.show() # check galleries gs = 1 if name.endswith(utils.ARCHIVE_FILES): gs = len(utils.check_archive(name)) elif os.path.isdir(name): g_dirs, g_archs = utils.recursive_gallery_check(name) gs = len(g_dirs) + len(g_archs) if gs == 0: self.file_exists_lbl.setText('<font color="red">Invalid gallery source.</font>') self.file_exists_lbl.show() self.done.hide() if app_constants.SUBFOLDER_AS_GALLERY: if gs > 1: self.file_exists_lbl.setText('<font color="red">More than one galleries detected in source! Use other methods to add.</font>') self.file_exists_lbl.show() self.done.hide() def check(self): if len(self.title_edit.text()) is 0: self.title_edit.setFocus() self.title_edit.setStyleSheet("border-style:outset;border-width:2px;border-color:red;") return False elif len(self.author_edit.text()) is 0: self.author_edit.setText("Unknown") if len(self.path_lbl.text()) == 0 or self.path_lbl.text() == 'No path specified': self.path_lbl.setStyleSheet("color:red") self.path_lbl.setText('No path specified') return False return True def set_chapters(self, gallery_object, add_to_model=True): path = gallery_object.path chap_container = gallerydb.ChaptersContainer(gallery_object) metafile = utils.GMetafile() try: log_d('Listing dir...') con = scandir.scandir(path) # list all folders in gallery dir log_i('Gallery source is a directory') log_d('Sorting') chapters = sorted([sub.path for sub in con if sub.is_dir() or sub.name.endswith(utils.ARCHIVE_FILES)]) #subfolders # if gallery has chapters divided into sub folders if len(chapters) != 0: log_d('Chapters divided in folders..') for ch in chapters: chap = chap_container.create_chapter() chap.title = utils.title_parser(ch)['title'] chap.path = os.path.join(path, ch) metafile.update(utils.GMetafile(chap.path)) chap.pages = len(list(scandir.scandir(chap.path))) else: #else assume that all images are in gallery folder chap = chap_container.create_chapter() chap.title = utils.title_parser(os.path.split(path)[1])['title'] chap.path = path metafile.update(utils.GMetafile(path)) chap.pages = len(list(scandir.scandir(path))) except NotADirectoryError: if path.endswith(utils.ARCHIVE_FILES): gallery_object.is_archive = 1 log_i("Gallery source is an archive") archive_g = sorted(utils.check_archive(path)) for g in archive_g: chap = chap_container.create_chapter() chap.path = g chap.in_archive = 1 metafile.update(utils.GMetafile(g, path)) arch = utils.ArchiveFile(path) chap.pages = len(arch.dir_contents(g)) arch.close() metafile.apply_gallery(gallery_object) if add_to_model: self.SERIES.emit([gallery_object]) log_d('Sent gallery to model') def reject(self): if self.check(): msgbox = QMessageBox() msgbox.setText("<font color='red'><b>Noo oniichan! You were about to add a new gallery.</b></font>") msgbox.setInformativeText("Do you really want to discard?") msgbox.setStandardButtons(QMessageBox.Yes | QMessageBox.No) msgbox.setDefaultButton(QMessageBox.No) if msgbox.exec() == QMessageBox.Yes: self.close() else: self.close() def web_metadata(self, url, btn_widget, pgr_widget): self.link_lbl.setText(url) f = fetch.Fetch() thread = QThread(self) thread.setObjectName('Gallerydialog web metadata') btn_widget.hide() pgr_widget.show() def status(stat): def do_hide(): try: pgr_widget.hide() btn_widget.show() except RuntimeError: pass if stat: do_hide() else: danger = """QProgressBar::chunk { background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0,stop: 0 #FF0350,stop: 0.4999 #FF0020,stop: 0.5 #FF0019,stop: 1 #FF0000 ); border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; border: .px solid black;}""" pgr_widget.setStyleSheet(danger) QTimer.singleShot(3000, do_hide) f.deleteLater() def gallery_picker(gallery, title_url_list, q): self.parent_widget._web_metadata_picker(gallery, title_url_list, q, self) try: dummy_gallery = self.make_gallery(self.gallery) except AttributeError: dummy_gallery = self.make_gallery(gallerydb.Gallery(), False) if not dummy_gallery: status(False) return None dummy_gallery.link = url f.galleries = [dummy_gallery] f.moveToThread(thread) f.GALLERY_PICKER.connect(gallery_picker) f.GALLERY_EMITTER.connect(self.set_web_metadata) thread.started.connect(f.auto_web_metadata) thread.finished.connect(thread.deleteLater) f.FINISHED.connect(status) thread.start() def set_web_metadata(self, metadata): assert isinstance(metadata, gallerydb.Gallery) self.link_lbl.setText(metadata.link) self.title_edit.setText(metadata.title) self.author_edit.setText(metadata.artist) tags = "" lang = ['English', 'Japanese'] self._find_combobox_match(self.lang_box, metadata.language, 2) self.tags_edit.setText(utils.tag_to_string(metadata.tags)) pub_string = "{}".format(metadata.pub_date) pub_date = QDate.fromString(pub_string.split()[0], "yyyy-MM-dd") self.pub_edit.setDate(pub_date) self._find_combobox_match(self.type_box, metadata.type, 0) def make_gallery(self, new_gallery, add_to_model=True, new=False): if self.check(): new_gallery.title = self.title_edit.text() log_d('Adding gallery title') new_gallery.artist = self.author_edit.text() log_d('Adding gallery artist') log_d('Adding gallery path') if new and app_constants.MOVE_IMPORTED_GALLERIES: app_constants.OVERRIDE_MONITOR = True new_gallery.path = utils.move_files(self.path_lbl.text()) else: new_gallery.path = self.path_lbl.text() new_gallery.info = self.descr_edit.toPlainText() log_d('Adding gallery descr') new_gallery.type = self.type_box.currentText() log_d('Adding gallery type') new_gallery.language = self.lang_box.currentText() log_d('Adding gallery lang') new_gallery.status = self.status_box.currentText() log_d('Adding gallery status') new_gallery.tags = utils.tag_to_dict(self.tags_edit.toPlainText()) log_d('Adding gallery: tagging to dict') qpub_d = self.pub_edit.date().toString("ddMMyyyy") dpub_d = datetime.strptime(qpub_d, "%d%m%Y").date() try: d_t = self.gallery_time except AttributeError: d_t = datetime.now().time().replace(microsecond=0) dpub_d = datetime.combine(dpub_d, d_t) new_gallery.pub_date = dpub_d log_d('Adding gallery pub date') new_gallery.link = self.link_lbl.text() log_d('Adding gallery link') if not new_gallery.chapters: log_d('Starting chapters') thread = threading.Thread(target=self.set_chapters, args=(new_gallery,add_to_model), daemon=True) thread.start() thread.join() log_d('Finished chapters') return new_gallery def link_set(self): t = self.link_edit.text() self.link_edit.hide() self.link_lbl.show() self.link_lbl.setText(t) self.link_btn2.hide() self.link_btn.show() def link_modify(self): t = self.link_lbl.text() self.link_lbl.hide() self.link_edit.show() self.link_edit.setText(t) self.link_btn.hide() self.link_btn2.show() def accept(self): new_gallery = self.make_gallery(gallerydb.Gallery(), new=True) if new_gallery: self.close() def accept_edit(self): new_gallery = self.make_gallery(self.gallery) #for ser in self.gallery: if new_gallery: self.SERIES_EDIT.emit([new_gallery], self.position) self.close() def reject_edit(self): self.close()
class SeriesDialog(QDialog): "A window for adding/modifying series" series_queue = queue.Queue() SERIES = pyqtSignal(list) SERIES_EDIT = pyqtSignal(list, int) #series_list = [] # might want to extend this to allow mass series adding def _init__(self, parent=None): super().__init__() #TODO: Implement a way to mass add series' #IDEA: Extend dialog in a ScrollArea with more forms... def initUI(self): main_layout = QVBoxLayout() f_web = QGroupBox("From the Web") f_web.setCheckable(False) main_layout.addWidget(f_web) web_layout = QHBoxLayout() f_web.setLayout(web_layout) f_local = QGroupBox("From local folder") f_local.setCheckable(False) main_layout.addWidget(f_local) local_layout = QHBoxLayout() f_local.setLayout(local_layout) f_series = QGroupBox("Series Info") f_series.setCheckable(False) main_layout.addWidget(f_series) series_layout = QFormLayout() f_series.setLayout(series_layout) def basic_web(name): return QLabel(name), QLineEdit(), QPushButton("Fetch") exh_lbl, exh_edit, exh_btn = basic_web("ExHentai:") web_layout.addWidget(exh_lbl, 0, Qt.AlignLeft) web_layout.addWidget(exh_edit, 0) web_layout.addWidget(exh_btn, 0, Qt.AlignRight) choose_folder = QPushButton("Choose Folder") choose_folder.clicked.connect(self.choose_dir) local_layout.addWidget(choose_folder, Qt.AlignLeft) self.title_edit = QLineEdit() self.title_edit.setFocus() self.author_edit = QLineEdit() self.descr_edit = QTextEdit() self.descr_edit.setFixedHeight(70) self.descr_edit.setPlaceholderText("HTML 4 tags are supported") self.lang_box = QComboBox() self.lang_box.addItems(["English", "Japanese", "Other"]) self.lang_box.setCurrentIndex(0) self.tags_edit = QLineEdit() self.tags_edit.setPlaceholderText("namespace1:tag1, tag2, namespace3:tag3, etc..") self.type_box = QComboBox() self.type_box.addItems(["Manga", "Doujinshi", "Other"]) self.type_box.setCurrentIndex(0) #self.type_box.currentIndexChanged[int].connect(self.doujin_show) #self.doujin_parent = QLineEdit() #self.doujin_parent.setVisible(False) self.status_box = QComboBox() self.status_box.addItems(["Unknown", "Ongoing", "Completed"]) self.status_box.setCurrentIndex(0) self.pub_edit = QDateEdit() self.pub_edit.setCalendarPopup(True) self.pub_edit.setDate(QDate.currentDate()) self.path_lbl = QLabel("unspecified...") self.path_lbl.setWordWrap(True) series_layout.addRow("Title:", self.title_edit) series_layout.addRow("Author:", self.author_edit) series_layout.addRow("Description:", self.descr_edit) series_layout.addRow("Language:", self.lang_box) series_layout.addRow("Tags:", self.tags_edit) series_layout.addRow("Type:", self.type_box) series_layout.addRow("Publication Date:", self.pub_edit) series_layout.addRow("Path:", self.path_lbl) final_buttons = QHBoxLayout() final_buttons.setAlignment(Qt.AlignRight) main_layout.addLayout(final_buttons) done = QPushButton("Done") done.setDefault(True) done.clicked.connect(self.accept) cancel = QPushButton("Cancel") cancel.clicked.connect(self.reject) final_buttons.addWidget(cancel) final_buttons.addWidget(done) self.setLayout(main_layout) # TODO: complete this... maybe another time.. #def doujin_show(self, index): # if index is 1: # self.doujin_parent.setVisible(True) # else: # self.doujin_parent.setVisible(False) def choose_dir(self): dir_name = QFileDialog.getExistingDirectory(self, 'Choose a folder') head, tail = os.path.split(dir_name) self.title_edit.setText(tail) self.path_lbl.setText(dir_name) def check(self): if len(self.title_edit.text()) is 0: self.title_edit.setFocus() self.title_edit.setStyleSheet("border-style:outset;border-width:2px;border-color:red;") return False elif len(self.author_edit.text()) is 0: self.author_edit.setText("Anon") if len(self.descr_edit.toPlainText()) is 0: self.descr_edit.setText("<i>No description..</i>") #if self.path_lbl.text() == "unspecified...": # return False return True def accept(self): from ..database import seriesdb def do_chapters(series): thread = threading.Thread(target=self.set_chapters, args=(series,)) thread.start() thread.join() return self.series_queue.get() if self.check(): new_series = seriesdb.Series() new_series.title = self.title_edit.text() new_series.artist = self.author_edit.text() new_series.path = self.path_lbl.text() new_series.info = self.descr_edit.toPlainText() new_series.type = self.type_box.currentText() new_series.language = self.lang_box.currentText() new_series.status = self.status_box.currentText() qpub_d = self.pub_edit.date().toString("ddMMyyyy") dpub_d = datetime.strptime(qpub_d, "%d%m%Y").date() new_series.pub_date = dpub_d updated_series = do_chapters(new_series) #for ser in self.series: self.SERIES.emit([updated_series]) super().accept() def set_chapters(self, series_object): path = series_object.path con = os.listdir(path) # list all folders in series dir chapters = sorted([os.path.join(path,sub) for sub in con if os.path.isdir(os.path.join(path, sub))]) #subfolders # if series has chapters divided into sub folders if len(chapters) != 0: for numb, ch in enumerate(chapters): chap_path = os.path.join(path, ch) series_object.chapters[numb] = chap_path else: #else assume that all images are in series folder series_object.chapters[0] = path #find last edited file times = set() for root, dirs, files in os.walk(path, topdown=False): for img in files: fp = os.path.join(root, img) times.add( os.path.getmtime(fp) ) series_object.last_update = time.asctime(time.gmtime(max(times))) self.series_queue.put(series_object) return True def reject(self): if self.check(): msgbox = QMessageBox() msgbox.setText("<font color='red'><b>Noo oniichan! You were about to add a new series.</b></font>") msgbox.setInformativeText("Do you really want to discard?") msgbox.setStandardButtons(QMessageBox.Yes | QMessageBox.No) msgbox.setDefaultButton(QMessageBox.No) if msgbox.exec() == QMessageBox.Yes: super().reject() else: super().reject() def trigger(self, list_of_index=None): if not list_of_index: self.initUI() else: assert isinstance(list_of_index, list) self.position = list_of_index[0].row() for index in list_of_index: series = index.data(Qt.UserRole+1) self.setSeries(series) from ..constants import WINDOW as parent self.resize(500,200) frect = self.frameGeometry() frect.moveCenter(QDesktopWidget().availableGeometry().center()) self.move(frect.topLeft()-QPoint(0,120)) self.setAttribute(Qt.WA_DeleteOnClose) self.setWindowFlags(Qt.FramelessWindowHint) self.exec() def setSeries(self, series): "To be used for when editing a series" self.series = series main_layout = QVBoxLayout() f_web = QGroupBox("Fetch metadata from Web") f_web.setCheckable(False) main_layout.addWidget(f_web) web_layout = QHBoxLayout() f_web.setLayout(web_layout) f_series = QGroupBox("Series Info") f_series.setCheckable(False) main_layout.addWidget(f_series) series_layout = QFormLayout() f_series.setLayout(series_layout) def basic_web(name): return QLabel(name), QLineEdit(), QPushButton("Fetch") exh_lbl, exh_edit, exh_btn = basic_web("ExHentai:") web_layout.addWidget(exh_lbl, 0, Qt.AlignLeft) web_layout.addWidget(exh_edit, 0) web_layout.addWidget(exh_btn, 0, Qt.AlignRight) self.title_edit = QLineEdit() self.title_edit.setText(series.title) self.author_edit = QLineEdit() self.author_edit.setText(series.artist) self.descr_edit = QTextEdit() self.descr_edit.setText(series.info) self.descr_edit.setAcceptRichText(True) self.descr_edit.setFixedHeight(70) self.lang_box = QComboBox() self.lang_box.addItems(["English", "Japanese", "Other"]) if series.language is "English": self.lang_box.setCurrentIndex(0) elif series.language is "Japanese": self.lang_box.setCurrentIndex(1) else: self.lang_box.setCurrentIndex(2) self.tags_edit = QLineEdit() #TODO Finish this.. self.tags_edit.setPlaceholderText("namespace1:tag1, tag2, namespace3:tag3, etc..") self.type_box = QComboBox() self.type_box.addItems(["Manga", "Doujinshi", "Other"]) if series.type is "Manga": self.type_box.setCurrentIndex(0) elif series.type is "Doujinshi": self.type_box.setCurrentIndex(1) else: self.type_box.setCurrentIndex(2) #self.type_box.currentIndexChanged[int].connect(self.doujin_show) #self.doujin_parent = QLineEdit() #self.doujin_parent.setVisible(False) self.status_box = QComboBox() self.status_box.addItems(["Unknown", "Ongoing", "Completed"]) if series.status is "Ongoing": self.status_box.setCurrentIndex(1) elif series.status is "Completed": self.status_box.setCurrentIndex(2) else: self.status_box.setCurrentIndex(0) self.pub_edit = QDateEdit() # TODO: Finish this.. self.pub_edit.setCalendarPopup(True) series_pub_date = "{}".format(series.pub_date) qdate_pub_date = QDate.fromString(series_pub_date, "yyyy-MM-dd") self.pub_edit.setDate(qdate_pub_date) self.path_lbl = QLabel("unspecified...") self.path_lbl.setWordWrap(True) self.path_lbl.setText(series.path) series_layout.addRow("Title:", self.title_edit) series_layout.addRow("Author:", self.author_edit) series_layout.addRow("Description:", self.descr_edit) series_layout.addRow("Language:", self.lang_box) series_layout.addRow("Tags:", self.tags_edit) series_layout.addRow("Type:", self.type_box) series_layout.addRow("Publication Date:", self.pub_edit) series_layout.addRow("Path:", self.path_lbl) final_buttons = QHBoxLayout() final_buttons.setAlignment(Qt.AlignRight) main_layout.addLayout(final_buttons) done = QPushButton("Done") done.setDefault(True) done.clicked.connect(self.accept_edit) cancel = QPushButton("Cancel") cancel.clicked.connect(self.reject_edit) final_buttons.addWidget(cancel) final_buttons.addWidget(done) self.setLayout(main_layout) def accept_edit(self): if self.check(): new_series = self.series new_series.title = self.title_edit.text() new_series.artist = self.author_edit.text() new_series.path = self.path_lbl.text() new_series.info = self.descr_edit.toPlainText() new_series.type = self.type_box.currentText() new_series.language = self.lang_box.currentText() new_series.status = self.status_box.currentText() qpub_d = self.pub_edit.date().toString("ddMMyyyy") dpub_d = datetime.strptime(qpub_d, "%d%m%Y").date() new_series.pub_date = dpub_d #for ser in self.series: self.SERIES_EDIT.emit([new_series], self.position) super().accept() def reject_edit(self): super().reject()
class Qt_Test_Frame(QMainWindow): Items = [] def __init__(self): #super(Qt_Test_Frame, self).__init__(*args, **kw) super().__init__() # 初始化界面 self._initUI() self.show() def _initUI(self): self.setWindowTitle("QT图形界面测试") self.resize(800, 600) wwg = QWidget() # 全局布局 wlayout = QVBoxLayout() h1_wlayout = QHBoxLayout() h2_wlayout = QHBoxLayout() h3_wlayout = QHBoxLayout() v4_wlayout = QVBoxLayout() v5_wlayout = QVBoxLayout() self.statusBar().showMessage("状态栏") # 第一层 self._frist_story(h1_wlayout) # 第二层 self._second_story(h2_wlayout) # 第三层 左 self._third_left(v4_wlayout, v5_wlayout) # 第三层 右 self._fouth_right(v5_wlayout) # 加载 splt = self._my_line() splt2 = self._my_line(False) wlayout.addSpacing(10) # 增加布局间距 wlayout.addLayout(h1_wlayout) wlayout.addSpacing(10) # 增加布局间距 wlayout.addLayout(h2_wlayout) wlayout.addSpacing(10) # 增加布局间距 wlayout.addWidget(splt) wlayout.addLayout(h3_wlayout) wlayout.addWidget(self.statusBar()) h3_wlayout.addLayout(v4_wlayout, 0) h3_wlayout.addWidget(splt2) h3_wlayout.addLayout(v5_wlayout, 2) #wlayout.setAlignment(Qt.AlignTop) wwg.setLayout(wlayout) self.setCentralWidget(wwg) def _frist_story(self, h1_wlayout): # 第一层布局 self.h1_combox1 = QComboBox(minimumWidth=100) self.h1_combox1.addItems(wind_field) self.h1_combox2 = QComboBox(minimumWidth=100) self.h1_combox2.addItems( wind_mach_chooice(self.h1_combox1.currentText())) self.h1_combox3 = QComboBox(minimumWidth=100) self.h1_combox3.addItems(wind_blade) self.h1_combox4 = QComboBox(minimumWidth=100) self.h1_combox4.addItems(signal_type) # 行为测试 暂时无法使用 h1_cb1_action = QAction("风场选择", self) h1_cb1_action.setStatusTip("请选择风场") self.h1_combox1.addAction(h1_cb1_action) h1_wlayout.addItem(QSpacerItem(20, 20)) h1_wlayout.addWidget(QLabel("风场"), 0) h1_wlayout.addWidget(self.h1_combox1, 0) h1_wlayout.addItem(QSpacerItem(40, 20)) h1_wlayout.addWidget(QLabel("风机"), 0) h1_wlayout.addWidget(self.h1_combox2, 0) h1_wlayout.addItem(QSpacerItem(40, 20)) h1_wlayout.addWidget(QLabel("叶片ID"), 0) h1_wlayout.addWidget(self.h1_combox3, 0) h1_wlayout.addItem(QSpacerItem(40, 20)) h1_wlayout.addWidget(QLabel("信号类型"), 0) h1_wlayout.addWidget(self.h1_combox4, 0) h1_wlayout.setAlignment(Qt.AlignLeft) # 事件绑定 self.h1_combox1.currentIndexChanged.connect(self._wind_chooice) def _second_story(self, h2_wlayout): # 第二层布局 self.h2_date1 = QDateEdit(QDate.currentDate()) self.h2_date1.setCalendarPopup(True) self.h2_date2 = QDateEdit(QDate.currentDate()) self.h2_date2.setCalendarPopup(True) self.h2_button = QPushButton("运行") self.h2_button2 = QPushButton("停止") h2_wlayout.addItem(QSpacerItem(20, 20)) h2_wlayout.addWidget(QLabel("起始"), 0) h2_wlayout.addWidget(self.h2_date1) h2_wlayout.addItem(QSpacerItem(50, 20)) h2_wlayout.addWidget(QLabel("结束"), 0) h2_wlayout.addWidget(self.h2_date2) h2_wlayout.addItem(QSpacerItem(70, 20)) h2_wlayout.addWidget(self.h2_button) h2_wlayout.addWidget(self.h2_button2) h2_wlayout.setAlignment(Qt.AlignLeft) # 事件绑定 self.h2_button.clicked.connect(lambda: self._start_func()) self.h2_button2.clicked.connect(lambda: self._stop_func()) def _third_left(self, v4_wlayout, v5_wlayout): # 第三层布局 # 分量布局 v4_group_imf = QGridLayout() vbox1 = QGroupBox("分量值") self.radio_1 = QRadioButton("分量1") self.radio_2 = QRadioButton("分量2") self.radio_3 = QRadioButton("分量3") self.radio_4 = QRadioButton("分量4") self.radio_5 = QRadioButton("分量5") self.radio_6 = QRadioButton("分量6") self.radio_7 = QRadioButton("分量7") self.radio_8 = QRadioButton("分量8") self.radio_9 = QRadioButton("分量9") self.radio_1.setChecked(True) self.radio_val = self.radio_1.text() # 优先级布局 v4_group_prior = QGridLayout() vbox2 = QGroupBox("优先级") cb1 = QCheckBox("叶片1") cb2 = QCheckBox("叶片2") cb3 = QCheckBox("叶片3") self.v4_lineEdit = QLineEdit() # 时间布局 v4_group_time = QGridLayout() vbox3 = QGroupBox("时间选择") self.v4_combox1 = QComboBox(minimumWidth=100) self.v4_combox1.addItem("空") # 按键 v4_button = QPushButton("显示图形") # 写入网格格布局 v4_group_imf.addWidget(self.radio_1, 0, 0) v4_group_imf.addWidget(self.radio_2, 0, 1) v4_group_imf.addWidget(self.radio_3, 1, 0) v4_group_imf.addWidget(self.radio_4, 1, 1) v4_group_imf.addWidget(self.radio_5, 2, 0) v4_group_imf.addWidget(self.radio_6, 2, 1) v4_group_imf.addWidget(self.radio_7, 3, 0) v4_group_imf.addWidget(self.radio_8, 3, 1) v4_group_imf.addWidget(self.radio_9, 4, 0) v4_group_prior.addWidget(cb1, 1, 0) v4_group_prior.addWidget(cb2, 2, 0) v4_group_prior.addWidget(cb3, 3, 0) v4_group_prior.addWidget(QLabel("选择是:"), 4, 0) v4_group_prior.addWidget(self.v4_lineEdit, 5, 0) v4_group_time.addWidget(self.v4_combox1) # 写入左侧布局 vbox1.setLayout(v4_group_imf) vbox2.setLayout(v4_group_prior) vbox3.setLayout(v4_group_time) v4_wlayout.addItem(QSpacerItem(50, 20)) v4_wlayout.addWidget(vbox1) v4_wlayout.addItem(QSpacerItem(50, 20)) v4_wlayout.addWidget(vbox2) v4_wlayout.addItem(QSpacerItem(50, 20)) v4_wlayout.addWidget(vbox3) v4_wlayout.addItem(QSpacerItem(50, 20)) v4_wlayout.addWidget(v4_button) v4_wlayout.addItem(QSpacerItem(50, 20)) # 事件绑定 self.radio_1.toggled.connect(lambda: self._changestyle(self.radio_1)) self.radio_2.toggled.connect(lambda: self._changestyle(self.radio_2)) self.radio_3.toggled.connect(lambda: self._changestyle(self.radio_3)) self.radio_4.toggled.connect(lambda: self._changestyle(self.radio_4)) self.radio_5.toggled.connect(lambda: self._changestyle(self.radio_5)) self.radio_6.toggled.connect(lambda: self._changestyle(self.radio_6)) self.radio_7.toggled.connect(lambda: self._changestyle(self.radio_7)) self.radio_8.toggled.connect(lambda: self._changestyle(self.radio_8)) self.radio_9.toggled.connect(lambda: self._changestyle(self.radio_9)) cb1.stateChanged.connect(lambda: self._prior_func(cb1)) cb2.stateChanged.connect(lambda: self._prior_func(cb2)) cb3.stateChanged.connect(lambda: self._prior_func(cb3)) v4_button.clicked.connect(lambda: self._show_func(v5_wlayout)) def _fouth_right(self, v5_wlayout): # 加载波形图 self.tmp_plt = plt_init() v5_wlayout.addWidget(self.tmp_plt) def _my_line(self, var=True): # var 为True时,为横线,否则为竖线 line = QFrame(self) line_var = QFrame.HLine sp_var = Qt.Horizontal if not var: line_var = QFrame.VLine sp_var = Qt.Vertical line.setFrameShape(line_var) line.setFrameShadow(QFrame.Sunken) splitter = QSplitter(sp_var) splitter.addWidget(line) return splitter def _wind_chooice(self): tmp_list = wind_mach_chooice(self.h1_combox1.currentText()) self.h1_combox2.clear() self.h1_combox2.addItems(tmp_list) def _start_func(self): a = self.h1_combox1.currentText() b = self.h1_combox2.currentText() c = self.h1_combox3.currentText() d = self.h1_combox4.currentText() e = self.h2_date1.dateTime().toString("yy-MM-dd") f = self.h2_date2.dateTime().toString("yy-MM-dd") self.start_func = RunThread(target=self._start_thread, args=(a, b, c, d, e, f)) #self.start_func = MyThread(target=self._print, args=(a, b, c, d, e, f)) self.start_func.start() def _stop_func(self): self.start_func.stop() print("运行结束") def _start_thread(self, a, b, c, d, e, f): print("*****运行打印*****") print(wind_mach_chooice(a)) print(a, b, c, d) print(e) print(f) print("%s" % (time.strftime('<%H:%M:%S>', time.localtime()))) self.v4_combox1.clear() self.v4_combox1.addItems(tmp_time_list) print("*****运行打印*****") def _changestyle(self, btn): # 单选项的判断函数 if btn.isChecked(): self.radio_val = btn.text() #print("%s"%(time.strftime('<%H:%M:%S>', time.localtime()))) def _prior_func(self, cb): # 复选框内容添加 if cb.isChecked(): if cb.text()[-1] not in self.Items: self.Items.append(cb.text()[-1]) shop_cart = ",".join(self.Items) self.v4_lineEdit.setText(shop_cart) else: if cb.text()[-1] in self.Items: self.Items.remove(cb.text()[-1]) shop_cart = ",".join(self.Items) self.v4_lineEdit.setText(shop_cart) def _show_func(self, v5_wlayout): print("*****显示打印*****") print(self.radio_val) num = self.v4_lineEdit.text() print(self.v4_combox1.currentText()) v5_wlayout.removeWidget(self.tmp_plt) self.tmp_plt = plt_show(num) v5_wlayout.addWidget(self.tmp_plt) print("*****显示打印*****")
class ThirdTab(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): grid = QGridLayout() grid.addWidget(self.create_choice_groupbox(), 0, 0) grid.addWidget(self.create_view_groupbox(), 0, 1) self.setLayout(grid) # Groupbox : 기간 선택 def create_choice_groupbox(self): gbox = QGroupBox() hbox = QHBoxLayout() vbox = QVBoxLayout() hbox2 = QHBoxLayout() # widget lbl_period = QLabel('조회기간') self.dateed_start = QDateEdit() lbl_mark = QLabel('~') self.dateed_end = QDateEdit() self.dateed_start.setDate(QDate.currentDate()) self.dateed_end.setDate(QDate.currentDate()) self.dateed_start.setCalendarPopup(True) self.dateed_end.setCalendarPopup(True) btn_week = QPushButton('1주') btn_view = QPushButton('조회') # Signal btn_week.clicked.connect(self.change_week_period) btn_view.clicked.connect(self.lookup_period_sales) hbox.addWidget(lbl_period) hbox.addWidget(self.dateed_start) hbox.addWidget(lbl_mark) hbox.addWidget(self.dateed_end) hbox2.addWidget(btn_week) hbox2.addWidget(btn_view) vbox.addLayout(hbox) vbox.addLayout(hbox2) gbox.setLayout(vbox) return gbox # Groupbox : 조회 def create_view_groupbox(self): gbox = QGroupBox() vbox = QVBoxLayout() # widget '''cbox = QComboBox() cbox.addItem('매출건수') cbox.addItem('매출수량') cbox.addItem('매출총액') cbox.activated[str].connect()''' self.canvas = PlotCanvas(self, width=5, height=4) vbox.addWidget(self.canvas) gbox.setLayout(vbox) return gbox @pyqtSlot() def change_week_period(self): self.dateed_start.setDate(self.dateed_end.date().addDays(-6)) @pyqtSlot() def lookup_period_sales(self): if self.dateed_end.date() < self.dateed_start.date(): self.warn_period() else: stats.stats_period_sales(self.dateed_start.date().toPyDate(), self.dateed_end.date().toPyDate()) self.canvas.plot() @pyqtSlot() def warn_period(self): msg = QMessageBox.information(self, '조회기간 경고', '시작일은 종료일보다 나중일 수 없습니다.', QMessageBox.Ok, QMessageBox.Ok)
class TaskView(QWidget): close = pyqtSignal() def __init__(self, model): super().__init__() self.header = QLabel('') self.desc = QLineEdit() self.date = QDateEdit() self.time = QTimeEdit() self.init_ui() self.mapper = QDataWidgetMapper() self.mapper.setModel(model) self.mapper.setSubmitPolicy(QDataWidgetMapper.ManualSubmit) self.mapper.addMapping(self.desc, TaskModel.col_desc) self.mapper.addMapping(self.date, TaskModel.col_date) self.mapper.addMapping(self.time, TaskModel.col_time) def set_task(self, index): self.mapper.setCurrentIndex(index) self.header.setText('РЕДАКТИРОВАНИЕ ЗАДАЧИ') # text = 'НОВАЯ ЗАДАЧА' # self.date.setDate(QDate().currentDate()) def create_date(self): self.date.setDisplayFormat('dd.MM.yyyy') self.date.setCalendarPopup(True) self.date.setFixedWidth(120) return self.date def create_time(self): self.time.setDisplayFormat('hh.mm') self.time.setFixedWidth(120) return self.time def create_date_buttons(self): date_lt = QHBoxLayout() btn_now = QPushButton('сегодня') btn_now.clicked.connect(lambda: self.date.setDate(QDate().currentDate())) date_lt.addWidget(btn_now, 0, Qt.AlignCenter) btn_tomorrow = QPushButton('завтра') btn_tomorrow.clicked.connect(lambda: self.date.setDate(QDate().currentDate().addDays(1))) date_lt.addWidget(btn_tomorrow, 0, Qt.AlignCenter) btn_week_later = QPushButton('через неделю') btn_week_later.clicked.connect(lambda: self.date.setDate(QDate().currentDate().addDays(7))) date_lt.addWidget(btn_week_later, 0, Qt.AlignCenter) return date_lt # def create_time_choice(self): # self.time.setMaxVisibleItems(15) # self.time.setStyleSheet('QComboBox { combobox-popup: 0; }') # for it in range(24): # self.time.insertItem(it * 2 + 0, '%.2d:00' % it) # self.time.insertItem(it * 2 + 1, '%.2d:30' % it) # # return self.time def save(self): print('save', self.mapper.submit()) self.close.emit() def cancel(self): self.close.emit() def remove(self): self.mapper.model().removeRow(self.mapper.currentIndex()) self.close.emit() def create_control_buttons(self): control_lt = QHBoxLayout() btn_save = QPushButton('Сохранить') btn_save.clicked.connect(self.save) control_lt.addWidget(btn_save, 0, Qt.AlignCenter) btn_cancel = QPushButton('Отменить') btn_cancel.clicked.connect(self.cancel) control_lt.addWidget(btn_cancel, 0, Qt.AlignCenter) btn_remove = QPushButton('Удалить') btn_remove.clicked.connect(self.remove) control_lt.addWidget(btn_remove, 1, Qt.AlignRight) return control_lt def create_main_form(self): fm = QFormLayout() fm.addRow(self.header) fm.addRow(QLabel('')) fm.addRow(self.desc) fm.addRow(QLabel('')) fm.addRow(QLabel('Когда это нужно сделать?')) fm.addRow(self.create_date()) fm.addRow(self.create_date_buttons()) fm.addRow(QLabel('')) fm.addRow(QLabel('Во сколько?')) fm.addRow(self.create_time()) return fm def init_ui(self): layout = QVBoxLayout() layout.addLayout(self.create_main_form()) layout.addStretch() layout.addLayout(self.create_control_buttons()) self.setLayout(layout)