def setEditorData(self, editor, index): val = index.data(Qt.EditRole) if is_date_undefined(val): val = QDate(2000, 1, 1) if isinstance(val, QDateTime): val = val.date() editor.setDate(val)
def use_setting_date_value(self): """ 将日期恢复到原值 """ start_time = settings.value(Configs.start_time) self.dateEdit.setDate(QDate.fromString(start_time, "yyyy-MM-dd")) end_time = settings.value(Configs.end_time) self.dateEdit_2.setDate(QDate.fromString(end_time, "yyyy-MM-dd"))
def setEditorData(self, editor, index): val = index.data(Qt.EditRole) if is_date_undefined(val) or check_key_modifier(Qt.ControlModifier): val = QDate(2000, 1, 1) elif check_key_modifier(Qt.ShiftModifier): val = now() if isinstance(val, QDateTime): val = val.date() editor.setDate(val)
def setEditorData(self, editor, index): val = index.data(Qt.EditRole) if check_key_modifier(Qt.ControlModifier): val = UNDEFINED_QDATETIME elif check_key_modifier(Qt.ShiftModifier + Qt.ControlModifier): val = now() elif is_date_undefined(val): val = QDate(2000, 1, 1) if isinstance(val, QDateTime): val = val.date() editor.setDate(val)
def _init_date(self): # 日期设置 current = QDate.currentDate() self.dateEdit.setDate(QDate(current.year(), current.month(), 1)) self.dateEdit.setDisplayFormat("yyyy-MM-dd") self.dateEdit_2.setDate(current) self.dateEdit_2.setDisplayFormat("yyyy-MM-dd") settings.setValue(Configs.start_time, self.dateEdit.text()) settings.setValue(Configs.end_time, self.dateEdit_2.text())
def _init(self): from .History import History minTs = HistoryDbModel.select(peewee.fn.Min( HistoryDbModel.date)).scalar() if minTs <= 0: return today = QDate.currentDate() week = today.addDays(1 - today.dayOfWeek()) month = QDate(today.year(), today.month(), 1) currentTs = QDateTime.currentMSecsSinceEpoch() ts = currentTs while ts > minTs: tsDate = QDateTime.fromMSecsSinceEpoch(ts).date() endTs = 0 itemName = '' if tsDate == today: endTs = QDateTime(today).toMSecsSinceEpoch() itemName = _('Today') elif tsDate >= week: endTs = QDateTime(week).toMSecsSinceEpoch() itemName = _('This Week') elif tsDate.month() == month.month() and tsDate.year( ) == month.year(): endTs = QDateTime(month).toMSecsSinceEpoch() itemName = _('This Month') else: startDate = QDate(tsDate.year(), tsDate.month(), tsDate.daysInMonth()) endDate = QDate(startDate.year(), startDate.month(), 1) ts = QDateTime(startDate, QTime(23, 59, 59)).toMSecsSinceEpoch() endTs = QDateTime(endDate).toMSecsSinceEpoch() itemName = '%s %s' % (tsDate.year(), History.titleCaseLocalizedMonth( tsDate.month())) dbobj = HistoryDbModel.select().where( HistoryDbModel.date.between(endTs, ts)).first() if dbobj: item = HistoryItem(self._rootItem) item.setStartTimestamp(ts == currentTs and -1 or ts) item.setEndTimestamp(endTs) item.title = itemName item.canFetchMore = True if ts == currentTs: self._todayItem = item ts = endTs - 1
def historyEntryAdded(self, entry): ''' @param: entry HistoryEntry ''' if not self._todayItem: self.beginInsertRows(QModelIndex(), 0, 0) self._todayItem = HistoryItem(None) self._todayItem.canFetchMore = True self._todayItem.setStartTimestamp(-1) self._todayItem.setEndTimestamp( QDateTime(QDate.currentDate()).toMSecsSinceEpoch()) self._todayItem.title = _('Today') self._rootItem.prependChild(self._todayItem) self.endInsertRows() self.beginInsertRows(self.createIndex(0, 0, self._todayItem), 0, 0) item = HistoryItem() item.historyEntry = entry self._todayItem.prependChild(item) self.endInsertRows()
def show_detail(self, r): """ 选中table行后,显示数据明细 :param r: 选中的行号 :return: """ self.dateEdit.setDate( QDate.fromString(self.tableWidget.item(r.row(), 0).text(), 1)) # 时间 self.comboBox.setCurrentText(self.tableWidget.item(r.row(), 1).text()) # 工作分类 self.textEdit.setPlainText(self.tableWidget.item(r.row(), 2).text()) # 事项内容 self.comboBox_2.setCurrentText( self.tableWidget.item(r.row(), 3).text()) # 工时 self.comboBox_3.setCurrentText( self.tableWidget.item(r.row(), 4).text()) # 性质 self.comboBox_4.setCurrentText( self.tableWidget.item(r.row(), 5).text()) # 重要等级 self.comboBox_5.setCurrentText( self.tableWidget.item(r.row(), 6).text()) # 状态 self.comboBox_6.setCurrentText( self.tableWidget.item(r.row(), 7).text()) # 工作配合 self.textEdit_2.setPlainText(self.tableWidget.item(r.row(), 8).text()) # 问题和困难 self.id = self.tableWidget.item(r.row(), 9).text()
def pd_timestamp_to_q_datetime(pd_timestamp: datetime): if pd_timestamp is None or pd.isna(pd_timestamp): return QDateTime() return QDateTime( QDate(pd_timestamp.year, pd_timestamp.month, pd_timestamp.day), QTime(pd_timestamp.hour, pd_timestamp.minute, pd_timestamp.second, pd_timestamp.microsecond / 1000))
def _initUI(self): self._name = QLineEdit() self._name.setFixedHeight(30) self._name.setPlaceholderText("produto") self._stock = QSpinBox() self._stock.setMaximum(100000) self._stock.setFixedHeight(30) self._stock.setValue(10) self._price = QDoubleSpinBox() self._price.setDecimals(2) self._price.setMaximum(99999.99) self._price.setFixedHeight(30) self._price.setValue(10.0) self.inputCategory = QComboBox() self.inputCategory.setFixedHeight(30) self._date = QDateEdit() self._date.setDate(QDate.currentDate()) self.addField("Nome do Produto", self._name) self.addField("Preço(R$)", self._price) self.addField("Estoque(Unidade)", self._stock) self.addField("Categoria", self.inputCategory) #self.addField("Validade", self._date) super(ProductWindow, self)._initUI()
def __init__(self, jsonFile=None, bucketName=None): super().__init__() self.setupUi(self) self.jsonFile = jsonFile self.bucketName = bucketName self.extra = Generic_extra() self.shelvePath = None self.lstImg = [] self.lstPdf = [] self.lstDocTypes = [] self.lstPathFiles = [] self.dictMetaData = {} self.clkFilePath = None #self.configCbModel() self.setLstDocType() self.setUpIcons() self.setLstPaths() self.setCombox() self.PBAdd.clicked.connect(self.addFilesToLst) #working 100% self.PBRemove.clicked.connect(self.removeFileFromLst) #working 100% self.LWPaths.clicked.connect(self.clickedItem) #working 100% self.LWPaths.doubleClicked.connect( self.DoubleclickedItem) #working 100% self.PBSave.clicked.connect(self.start_Save) self.PBClose.clicked.connect(self.ToClosed) #working 100% self.DEData.setDate(QDate.currentDate()) self.settingsButton.clicked.connect(self.onSettingsClicekd)
def _dialogAccepted(self): QApplication.setOverrideCursor(Qt.WaitCursor) if self._ui.history.isChecked(): start = QDateTime.currentMSecsSinceEpoch() end = 0 # QDate today = QDate.currentDate() week = today.addDays(1 - today.dayOfWeek()) month = QDate(today.year(), today.month(), 1) index = self._ui.historyLength.currentIndex() if index == 0: # Later Today end = QDateTime(today).toMSecsSinceEpoch() elif index == 1: # Week end = QDateTime(week).toMSecsSinceEpoch() elif index == 2: # Month end = QDateTime(month).toMSecsSinceEpoch() elif index == 3: # All end = 0 if end == 0: gVar.app.history().clearHistory() else: indexes = gVar.app.history().indexesFromTimeRange(start, end) gVar.app.history().deleteHistoryEntry(indexes) if self._ui.cookies.isChecked(): gVar.app.cookieJar().deleteAllCookies() if self._ui.cache.isChecked(): self.clearCache() if self._ui.databases.isChecked(): self.clearWebDatabases() if self._ui.localStorage.isChecked(): self.clearLocalStorage() QApplication.restoreOverrideCursor() self._ui.clear.setEnabled(False) self._ui.clear.setText(_('Done')) QTimer.singleShot(1000, self.close)
def import_expenses(self): try: row = int(self.le_initial_row.text()) - 1 description_col = int(self.le_description_col.text()) - 1 date_col = int(self.le_date_col.text()) - 1 default_date = self.default_date.date() date_format = self.le_date_format.text() percent = 1.0 / len(list(self.current_group.getMembers())) while self.model.item(row) is not None: print("Row ", row) expense = Expense() expense.setDescription( self.model.item(row, description_col).text()) print("Expense: ", expense.getDescription()) date = QDate.fromString( self.model.item(row, date_col).text(), date_format) if not date.isValid(): date = default_date expense.setDate(date.toString(Qt.ISODate)) print("Date: ", expense.getDate()) cost = 0 users = [] for member in self.current_group.getMembers(): print("Processing member ", member.getFirstName()) member_column = int( self.member_widget_map[member.getId()].text()) - 1 paid = 0 try: paid = float( self.model.item(row, member_column).text()) print("Expense: ", self.model.item(row, member_column).text()) except: pass cost = cost + paid expense_user = ExpenseUser() expense_user.setId(member.getId()) expense_user.setPaidShare(str(paid)) users.append(expense_user) for expense_user in users: expense_user.setOwedShare(str(cost * percent)) if cost == 0: raise Exception( self.tr('No se ha introducido monto para el gasto')) expense.setCost(str(cost)) expense.setUsers(users) expense.setGroupId(self.current_group.id) self.sObj.createExpense(expense) row = row + 1 self.le_initial_row.setText(str(row + 1)) except Exception as inst: QMessageBox.critical( self, self.tr("Error"), self.tr("Se ha producido un error en la fila") + str(row + 1) + "\n" + str(inst)) traceback.print_exc()
def clear(self): self._name.clear() self._price.setValue(1) self._stock.setValue(1) self.inputCategory.setCurrentIndex(0) self._date.setDate(QDate.currentDate()) self._name.parent().setProperty("hint", False) self.inputCategory.parent().setProperty("hint", False) self.update()
def set_month_and_year(self): """ Sets initial values for year and month boxes. """ self.yearBox.addItems(YEARS) self.monthBox.addItems(MONTHS) current_date = QDate.currentDate() self.yearBox.setCurrentText(str(current_date.year())) self.monthBox.setCurrentText(MONTHS[current_date.month()])
def setEditorData(self, editor, index): val = index.data(Qt.ItemDataRole.EditRole) if check_key_modifier(Qt.KeyboardModifier.ControlModifier): val = UNDEFINED_QDATETIME elif check_key_modifier(Qt.KeyboardModifier.ShiftModifier + Qt.KeyboardModifier.ControlModifier): val = now() elif is_date_undefined(val): val = QDate.currentDate() if isinstance(val, QDateTime): val = val.date() editor.setDate(val)
def __init__(self,user_id): super(act_modify_panel,self).__init__() self.setupUi(self) self.user_id=user_id sql='select * from activity where acId=%s' self.data=LinkMysql().select_sql(sql,user_id) print(self.data) self.time.setDate(QDate(self.data[0][2])) self.title_ln.setText(self.data[0][1]) self.con_ln.setText(self.data[0][3])
def setEditorData(self, editor, index): val = index.data(Qt.EditRole) if check_key_modifier(Qt.ControlModifier): val = UNDEFINED_QDATETIME elif check_key_modifier(Qt.ShiftModifier + Qt.ControlModifier): val = now() elif is_date_undefined(val): val = QDate.currentDate() if isinstance(val, QDateTime): val = val.date() editor.setDate(val)
def __init__(self, user_id): super(check_modify_panel, self).__init__() self.setupUi(self) self.user_id = user_id sql = 'select * from checking_in where staId=%s' self.data = LinkMysql().select_sql(sql, user_id) self.ch_id.setText(str(self.data[0][0])) self.ch_name.setText(self.data[0][1]) self.ch_dep.setText(self.data[0][2]) self.ch_work.setText(self.data[0][3]) self.ch_date.setDate(QDate(self.data[0][4]))
def __init__(self): QWidget.__init__(self) self.ui = Ui_DateTimeWidget() self.ui.setupUi(self) self.timer = QTimer(self) self.from_time_updater = True self.is_date_changed = False self.current_zone = "" self.tz_dict = {} self.continents = [] self.countries = [] for country, data in yali.localedata.locales.items(): if country == ctx.consts.lang: if data.has_key("timezone"): ctx.installData.timezone = data["timezone"] # Append continents and countries the time zone dictionary self.createTZDictionary() # Sort continent list self.sortContinents() # Append sorted continents to combobox self.loadContinents() # Load current continents country list self.getCountries(self.current_zone["continent"]) # Highlight the current zone self.index = self.ui.continentList.findText( self.current_zone["continent"]) self.ui.continentList.setCurrentIndex(self.index) self.index = self.ui.countryList.findText(self.current_zone["country"]) self.ui.countryList.setCurrentIndex(self.index) # Initialize widget signal and slots self.__initSignals__() self.ui.calendarWidget.setDate(QDate.currentDate()) self.pthread = None self.pds_messagebox = PMessageBox(self) self.pds_messagebox.enableOverlay() self.timer.start(1000)
def __init__(self): QWidget.__init__(self) self.ui = Ui_DateTimeWidget() self.ui.setupUi(self) self.timer = QTimer(self) self.from_time_updater = True self.is_date_changed = False self.current_zone = "" self.tz_dict = {} self.continents = [] self.countries = [] for country, data in yali.localedata.locales.items(): if country == ctx.consts.lang: if data.has_key("timezone"): ctx.installData.timezone = data["timezone"] # Append continents and countries the time zone dictionary self.createTZDictionary() # Sort continent list self.sortContinents() # Append sorted continents to combobox self.loadContinents() # Load current continents country list self.getCountries(self.current_zone["continent"]) # Highlight the current zone self.index = self.ui.continentList.findText(self.current_zone["continent"]) self.ui.continentList.setCurrentIndex(self.index) self.index = self.ui.countryList.findText(self.current_zone["country"]) self.ui.countryList.setCurrentIndex(self.index) # Initialize widget signal and slots self.__initSignals__() self.ui.calendarWidget.setDate(QDate.currentDate()) self.pthread = None self.pds_messagebox = PMessageBox(self) self.pds_messagebox.enableOverlay() self.timer.start(1000)
def setupUi(self, my_win): super().setupUi(my_win) self.sub_menu_inicio.aboutToShow.connect(self.volver_incio) self.sub_menu_registro.triggered.connect(self.mostrar_registrar_cancion) self.sub_meni_listado_canciones.triggered.connect(self.mostrar_listado_canciones) self.sub_menu_tabla_Canciones.triggered.connect(self.mostrar_tabla_canciones) self.sub_menu_registro_usuario.triggered.connect(self.registrar_usuario) #incluir fecha date = QDate.currentDate() date = str(date.toPyDate()) self.txt_fecha.setText(date) #incluir hora hora = QTime.currentTime() hora_txt = hora.toString("hh:mm") self.lcdNumber.display(hora_txt)
def __init__(self, categories, record=None): super().__init__() self.setupUi(self) self.categories = categories self.record = record self.setup() if self.record: self.budgetBox.setValue(self.record.amount) self.categoryBox.setCurrentText(self.record.category) self.typeBox.setCurrentText(self.record.type) self.yearBox.setCurrentText(str(self.record.year)) self.monthBox.setCurrentIndex(self.record.month - 1) self.dayBox.setCurrentText(str(self.record.day)) else: today = QDate.currentDate() self.yearBox.setCurrentText(str(today.year())) self.monthBox.setCurrentIndex(today.month() - 1)
def getDate(dateIn): month_string = { "Jan": 1, "Feb": 2, "Mar": 3, "Apr": 4, "May": 5, "Jun": 6, "Jul": 7, "Aug": 8, "Sep": 9, "Oct": 10, "Nov": 11, "Dec": 12 } ano = int(dateIn.split('_')[0]) mes = month_string[dateIn.split('_')[1]] dia = int(dateIn.split('_')[2]) dateQ = QDate(ano, mes, dia) return dateQ
def __init__(self, categories, transaction=None): super().__init__() self.setupUi(self) self.categories = categories self.transaction = transaction # List all categories self.categories_model = CategoryListModel() for cat in self.categories: self.categories_model.addItem(cat) self.categorysBox.setModel(self.categories_model) if self.transaction: self.dateEdit.setDate(self.transaction.date) self.amountBox.setValue(self.transaction.amount) self.infoEdit.setText(self.transaction.info) self.categorysBox.setCurrentText(self.transaction.category) else: today = QDate.currentDate() self.dateEdit.setDate(today)
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 __init__(self, QWidget_parent=None): QWidget.__init__(self, QWidget_parent) # параметры self._Margin = 50 self._isWatcher = False self._isChangeIndex = False self._is1Day = False self._isMore1Day = False self._date = QDate() self._curves = {} self._legend = "" self._plotterScale = PlotterScale(self) # параметры, которые сохраняются self._colorExt = QColor(Qt.white) self._colorInside = QColor(Qt.white) self._colorCurve = QColor(Qt.red) self._fontGrid = QFont('Arial', 8, QFont.Normal) self._fontTitle = QFont('Arial', 20, QFont.Normal) self._fontLegend = QFont('Arial', 8, QFont.Normal) self._fontTitleY = QFont('Arial', 16, QFont.Normal) self._pixmapSaveWidth = 800 self._pixmapSaveHeight = 600 self._toolbar = QToolBar(self) self._contexMenu = QMenu(self) saveAction = self._contexMenu.addAction(self.tr('Сохранить...')) saveAction.triggered.connect(self.onSavePlotter) self._timer = QTimer(self) self._timer.setTimerType(Qt.VeryCoarseTimer) self._timer.timeout.connect(self.tickTimer) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.timerTick = pyqtSignal(name='timerTick') self.noWatching = pyqtSignal(bool, name='noWatching') self.variablesPlotter = pyqtSignal(QDate, int, name='variablesPlotter')
def __init__(self, *args, **kwargs): super(SpotCommodityPage, self).__init__(*args, **kwargs) layout = QVBoxLayout(margin=0, spacing=2) # 日期选择、信息展示与新增按钮 message_button_layout = QHBoxLayout() self.date_edit = QDateEdit(QDate.currentDate(), dateChanged=self.getCurrentSpotCommodity) 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_spot_table), alignment=Qt.AlignRight) layout.addLayout(message_button_layout) # 当前数据显示表格 self.spot_table = SpotCommodityTable() layout.addWidget(self.spot_table) self.setLayout(layout) # 上传数据的进度条 self.process_widget = QWidget(self) self.process_widget.resize(self.width(), self.height()) process_layout = QVBoxLayout(self.process_widget) process_layout.addStretch() self.process_message = QLabel("数据上传处理中..", self.process_widget) process_layout.addWidget(self.process_message) process = QProgressBar(parent=self.process_widget) process.setMinimum(0) process.setMaximum(0) process.setTextVisible(False) process_layout.addWidget(process) process_layout.addStretch() self.process_widget.setLayout(process_layout) self.process_widget.hide() self.process_widget.setStyleSheet("background:rgb(200,200,200);opacity:0.6")
def __init__(self): super().__init__() self.setupUi(self) self.tableWidget.setColumnWidth(9, 0) self.dateEdit.setDate(QDate.currentDate()) # 设置日期为当天 self.id = ""
def init_gui(self): self.form_layout = QFormLayout() self.cmb_ods_sheets = QComboBox() self.le_initial_row = QLineEdit("1") self.le_initial_row.setValidator(QIntValidator(1, 99999)) self.cmb_group = QComboBox() self.le_date_col = QLineEdit("1") self.le_date_col.setValidator(QIntValidator(1, 999999)) self.default_date = QDateTimeEdit(QDate.currentDate()) self.default_date.setMinimumDate(QDate.currentDate().addDays(-365)) self.default_date.setMaximumDate(QDate.currentDate().addDays(365)) self.default_date.setDisplayFormat("dd.MM.yyyy") self.default_date.setCalendarPopup(True) self.le_date_format = QLineEdit("d/M/yyyy") self.le_description_col = QLineEdit("2") self.le_description_col.setValidator(QIntValidator(1, 9999)) self.sObj = get_splitwise() groups = self.sObj.getGroups() self.cmb_ods_sheets.currentTextChanged.connect(self.sheet_changed) for group in groups: self.cmb_group.addItem(group.getName(), group) self.cmb_group.currentIndexChanged.connect(self.current_group_changed) self.cmb_group.setCurrentIndex(0) btn_open_filename = QPushButton("Open") btn_open_filename.clicked.connect(self.open_filename) self.form_layout.addRow(self.tr("Archivo"), btn_open_filename) self.form_layout.addRow(self.tr("Hoja"), self.cmb_ods_sheets) self.form_layout.addRow(self.tr("Grupos"), self.cmb_group) self.form_layout.addRow(self.tr("Fila Inicial"), self.le_initial_row) self.form_layout.addRow(self.tr("Columna Fecha"), self.le_date_col) self.form_layout.addRow(self.tr("Formato de fecha"), self.le_date_format) self.form_layout.addRow(self.tr("Fecha por defecto"), self.default_date) self.form_layout.addRow(self.tr("Columna Concepto"), self.le_description_col) self.group_members_layout = QFormLayout() self.btn_import = QPushButton(self.tr("Importar")) self.btn_import.clicked.connect(self.import_expenses) self.model = QStandardItemModel(self) tableView = QTableView(self) tableView.setModel(self.model) self.vlayout = QVBoxLayout() self.vlayout.addLayout(self.form_layout) self.vlayout.addLayout(self.group_members_layout) self.vlayout.addWidget(self.btn_import) self.vlayout.setStretch(1, 1) hlayout = QHBoxLayout() hlayout.addWidget(tableView) hlayout.addLayout(self.vlayout) hlayout.setStretch(1, 0) hlayout.setStretch(0, 1) self.setLayout(hlayout) self._enable_widgets(False) self.show()
def __show_form(self): if self.__showed: return self.gridLayout.addWidget( QLabel(tr('№ дела (обращения) <em style="color: red">*</em>'))) w = QLineEdit() self.gridLayout.addWidget(w) w.setFocus() self.__wgts['declar_number'] = w self.gridLayout.addWidget( QLabel( tr('Услуга (код или номер, или наименование)<em style="color: red">*</em>' ))) w = QLineEdit() self.gridLayout.addWidget(w) self.__wgts['service'] = w self.gridLayout.addWidget( QLabel( tr('Дата регистрации запроса <em style="color: red">*</em>'))) de = QDateEdit(QDate().currentDate()) de.setCalendarPopup(True) self.gridLayout.addWidget(de) self.__wgts['register_date'] = de self.gridLayout.addWidget( QLabel( tr('Плановый срок предоставления услуги <em style="color: red">*</em>' ))) de = QDateEdit() self.__wgts['register_date'].dateChanged.connect(de.setMinimumDate) de.setCalendarPopup(True) de.setMinimumDate(self.__wgts['register_date'].date()) self.gridLayout.addWidget(de) self.__wgts['end_date'] = de gb = QGroupBox(tr('Место нахождения объекта услуги')) gb_l = QGridLayout() self.__wgts['object_address'] = self.__add_address(gb_l) gb.setLayout(gb_l) self.gridLayout.addWidget(gb, self.gridLayout.rowCount() + 1, 0, 1, 2) doc = {} gb = QGroupBox(tr('Приложенный документ *')) gb_l = QGridLayout() gb_l.addWidget( QLabel(tr('Наименование документа <em style="color: red">*</em>'))) w = QLineEdit() w.setMaxLength(1024) gb_l.addWidget(w, 0, 1, 1, 1) doc['title'] = w gb_l.addWidget( QLabel(tr('Номер документа <em style="color: red">*</em>'))) w = QLineEdit() w.setMaxLength(50) gb_l.addWidget(w) doc['number'] = w gb_l.addWidget( QLabel(tr('Дата документа <em style="color: red">*</em>'))) w = QDateEdit() w.setCalendarPopup(True) gb_l.addWidget(w) doc['date'] = w gb_l.addWidget( QLabel( tr('Прямая ссылка на файл. Поддерживаются только пртоколы ' 'HTTP, FTP <em style="color: red">*</em>'))) w = QLineEdit() gb_l.addWidget(w) doc['url'] = w gb.setLayout(gb_l) self.gridLayout.addWidget(gb, self.gridLayout.rowCount() + 1, 0, 1, 2) self.documents.append(doc) gb = QGroupBox(tr('Заявители *')) self.dec_layout = QGridLayout() self.cb = QComboBox() self.cb.addItems(('Физическое лицо', 'Юридическое лицо/Индивидуальный предприниматель')) self.dec_layout.addWidget(self.cb) b = QPushButton(tr('Добавить')) b.clicked.connect(self.add_declarant) self.dec_layout.addWidget(b, 0, 1, 1, 1) gb.setLayout(self.dec_layout) self.gridLayout.addWidget(gb, self.gridLayout.rowCount() + 1, 0, 1, 2) b = QPushButton(tr('Добавить файл документа')) b.clicked.connect(self.__add_doc_file) self.gridLayout.addWidget(b) self.file_label = QLabel() self.gridLayout.addWidget(self.file_label) self.warn_label = QLabel(tr("Не удаляйте файл до отправки запроса")) self.warn_label.setStyleSheet('color: red') self.warn_label.setVisible(False) self.gridLayout.addWidget(self.warn_label, self.gridLayout.rowCount() + 1, 0, 1, 2) self.__showed = True
def alterTable(self, mtd1, mtd2, key): util = FLUtil() oldMTD = None newMTD = None doc = QDomDocument("doc") docElem = None if not util.docDocumentSetContect(doc, mtd1): print("FLManager::alterTable : " + qApp.tr("Error al cargar los metadatos.")) else: docElem = doc.documentElement() oldMTD = self.db_.manager().metadata(docElem, True) if oldMTD and oldMTD.isQuery(): return True if not util.docDocumentSetContect(doc, mtd2): print("FLManager::alterTable : " + qApp.tr("Error al cargar los metadatos.")) return False else: docElem = doc.documentElement() newMTD = self.db_.manager().metadata(docElem, True) if not oldMTD: oldMTD = newMTD if not oldMTD.name() == newMTD.name(): print("FLManager::alterTable : " + qApp.tr("Los nombres de las tablas nueva y vieja difieren.")) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False oldPK = oldMTD.primaryKey() newPK = newMTD.primaryKey() if not oldPK == newPK: print("FLManager::alterTable : " + qApp.tr("Los nombres de las claves primarias difieren.")) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False if not self.db_.manager().checkMetaData(oldMTD, newMTD): if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return True if not self.db_.manager().existsTable(oldMTD.name()): print("FLManager::alterTable : " + qApp.tr( "La tabla %1 antigua de donde importar los registros no existe." ).arg(oldMTD.name())) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False fieldList = oldMTD.fieldList() oldField = None if not fieldList: print("FLManager::alterTable : " + qApp.tr("Los antiguos metadatos no tienen campos.")) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False renameOld = "%salteredtable%s" % (oldMTD.name()[0:5], QDateTime( ).currentDateTime().toString("ddhhssz")) if not self.db_.dbAux(): if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False self.db_.dbAux().transaction() if key and len(key) == 40: c = FLSqlCursor("flfiles", True, self.db_.dbAux()) c.setForwardOnly(True) c.setFilter("nombre = '%s.mtd'" % renameOld) c.select() if not c.next(): buffer = c.primeInsert() buffer.setValue("nombre", "%s.mtd" % renameOld) buffer.setValue("contenido", mtd1) buffer.setValue("sha", key) c.insert() q = FLSqlQuery("", self.db_.dbAux()) if not q.exec_("CREATE TABLE %s AS SELECT * FROM %s;" % (renameOld, oldMTD.name())) or not q.exec_( "DROP TABLE %s;" % oldMTD.name()): print("FLManager::alterTable : " + qApp.tr("No se ha podido renombrar la tabla antigua.")) self.db_.dbAux().rollback() if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False if not self.db_.manager().createTable(newMTD): self.db_.dbAux().rollback() if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False oldCursor = FLSqlCursor(renameOld, True, self.db_.dbAux()) oldCursor.setModeAccess(oldCursor.Browse) newCursor = FLSqlCursor(newMTD.name(), True, self.db_.dbAux()) newCursor.setMode(newCursor.Insert) oldCursor.select() totalSteps = oldCursor.size() progress = QProgressDialog( qApp.tr("Reestructurando registros para %1...").arg( newMTD.alias()), qApp.tr("Cancelar"), 0, totalSteps) progress.setLabelText(qApp.tr("Tabla modificada")) step = 0 newBuffer = None # sequence = "" fieldList = newMTD.fieldList() newField = None if not fieldList: print("FLManager::alterTable : " + qApp.tr("Los nuevos metadatos no tienen campos.")) self.db_.dbAux().rollback() if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False v = None ok = True while oldCursor.next(): v = None newBuffer = newCursor.primeInsert() for it in fieldList: oldField = oldMTD.field(newField.name()) if not oldField or not oldCursor.field(oldField.name()): if not oldField: oldField = newField v = newField.defaultValue() else: v = oldCursor.value(newField.name()) if (not oldField.allowNull() or not newField.allowNull()) and (v is None): defVal = newField.defaultValue() if defVal is not None: v = defVal if not newBuffer.field( newField.name()).type() == newField.type(): print("FLManager::alterTable : " + qApp.tr( "Los tipos del campo %1 no son compatibles. Se introducirá un valor nulo." ).arg(newField.name())) if not oldField.allowNull( ) or not newField.allowNull() and v is not None: if oldField.type() in ("int", "serial", "uint", "bool", "unlock"): v = 0 elif oldField.type() == "double": v = 0.0 elif oldField.type() == "time": v = QTime().currentTime() elif oldField.type() == "date": v = QDate().currentDate() else: v = "NULL"[0:newField.length()] newBuffer.setValue(newField.name(), v) if not newCursor.insert(): ok = False break step = step + 1 progress.setProgress(step) progress.setProgress(totalSteps) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD if ok: self.db_.dbAux().commit() else: self.db_.dbAux().rollback() return False return True
def clearPlotter(self, b_newData): self.deleteCurves() self._legend = "" if b_newData: self._date = QDate()
class BasePlotter(QWidget): """ Базовый класс для отображения данных """ __metaclass__ = ABCMeta _mSecs_for_grid = (1000, 5000, 15000, 30000, 60000, 300000, 900000, 1800000, 3600000, 7200000, 10800000, 14400000, 18000000, 21600000, 43200000, 86400000, 172800000, 259200000, 345600000, 432000000, 518400000, 604800000, 691200000, 777600000, 864000000, 950400000, 1036800000, 1123200000, 1209600000, 1296000000, 1382400000, 1468800000, 1555200000, 1641600000, 1728000000, 1814400000, 1900800000, 1987200000, 2073600000, 2160000000, 2246400000, 2332800000, 2419200000, 2505600000, 2592000000, 5184000000, 7776000000, 10368000000, 12960000000, 15552000000, 18144000000, 20736000000, 23328000000, 25920000000, 28512000000) def __init__(self, QWidget_parent=None): QWidget.__init__(self, QWidget_parent) # параметры self._Margin = 50 self._isWatcher = False self._isChangeIndex = False self._is1Day = False self._isMore1Day = False self._date = QDate() self._curves = {} self._legend = "" self._plotterScale = PlotterScale(self) # параметры, которые сохраняются self._colorExt = QColor(Qt.white) self._colorInside = QColor(Qt.white) self._colorCurve = QColor(Qt.red) self._fontGrid = QFont('Arial', 8, QFont.Normal) self._fontTitle = QFont('Arial', 20, QFont.Normal) self._fontLegend = QFont('Arial', 8, QFont.Normal) self._fontTitleY = QFont('Arial', 16, QFont.Normal) self._pixmapSaveWidth = 800 self._pixmapSaveHeight = 600 self._toolbar = QToolBar(self) self._contexMenu = QMenu(self) saveAction = self._contexMenu.addAction(self.tr('Сохранить...')) saveAction.triggered.connect(self.onSavePlotter) self._timer = QTimer(self) self._timer.setTimerType(Qt.VeryCoarseTimer) self._timer.timeout.connect(self.tickTimer) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.timerTick = pyqtSignal(name='timerTick') self.noWatching = pyqtSignal(bool, name='noWatching') self.variablesPlotter = pyqtSignal(QDate, int, name='variablesPlotter') @abstractmethod def drawOnPlotter(self, painter): """ рисуем на форме """ @abstractmethod def addData(self, receiver): """ добавляем данные на форму :param receiver: объект, содержащий информацию о данных и сами данные """ @abstractmethod def setLegend(self, receiver): """ устанавливаем легенду формы :param receiver: объект, содержащий информацию о данных и сами данные """ @abstractmethod def drawGridY(self, painter): """ Рисуем сетку по Y """ def readSettings(self): station = App.settings.value(App.stationName()) App.settings.beginGroup('/Settings') App.settings.beginGroup('/' + station) App.settings.beginGroup('/Plotters') App.settings.beginGroup('/BasePlotter') self._colorExt = QColor(App.settings.value('/ColorExt', self._colorExt)) self._colorInside = QColor(App.settings.value('/ColorInside', self._colorInside)) self._colorCurve = QColor(App.settings.value('/ColorCurve', self._colorCurve)) self._fontGrid = QFont(App.settings.value('/FontGrid', self._fontGrid)) self._fontTitle = QFont(App.settings.value('/FontTitle', self._fontTitle)) self._fontLegend = QFont(App.settings.value('/FontLegend', self._fontLegend)) self._fontTitleY = QFont(App.settings.value('/FontTitleY', self._fontTitleY)) self._pixmapSaveWidth = int(App.settings.value('/PixmapSaveWidth', self._pixmapSaveWidth)) self._pixmapSaveHeight = int(App.settings.value('/PixmapSaveHeight', self._pixmapSaveHeight)) App.settings.endGroup() App.settings.endGroup() App.settings.endGroup() App.settings.endGroup() def updateSettings(self): self.readSettings() self.repaint() def deleteCurves(self): print('---delete {0} curves'.format(self)) self._curves.clear() def getRectPlotter(self): return QRect(self._Margin + 50, self._Margin, self.width() - 2 * self._Margin - 50, self.height() - 2 * self._Margin) def drawBackground(self, painter): painter.save() painter.setBrush(self._colorExt) painter.setPen(Qt.NoPen) painter.drawRect(0, 0, painter.window().width(), painter.window().height()) painter.setBrush(self._colorInside) painter.setPen(Qt.SolidLine) painter.drawRect(self.getRectPlotter()) painter.restore() def drawLegend(self, painter): rect = self.getRectPlotter() painter.save() fontMetricsF = QFontMetricsF(self._fontLegend) painter.setFont(self._fontLegend) rect_legend = QRect(rect.left(), rect.top() - fontMetricsF.height(), fontMetricsF.width(self._legend) + 10, fontMetricsF.height()) painter.drawText(rect_legend, self._legend) painter.rectore() def drawTitle(self, painter): rect = self.getRectPlotter() painter.save() fontMetricsF = QFontMetricsF(self._fontTitle) painter.setFont(self._fontTitle) title = self._date.toString('dd.MM.yyyy') rect_title = QRect(rect.left() + (rect.width() / 2) - (fontMetricsF.width(title) / 2), rect.top() - fontMetricsF.height(), fontMetricsF.width(self._legend) + 10, fontMetricsF.height()) painter.drawText(rect_title, self._legend) painter.rectore() def drawTitleY(self, painter): rect = self.getRectPlotter() painter.save() fontMetricsF = QFontMetricsF(self._fontTitleY) painter.setFont(self._fontTitleY) rect_titley = QRect(-(rect.top() + (rect.height() / 2) + (fontMetricsF.width(self._titleY) / 2)), (rect.left() / 2) - fontMetricsF.height(), fontMetricsF.width(self._titleY), fontMetricsF.height()) painter.rotate(-90) painter.drawText(rect_titley, self._legend) painter.rectore() def drawGridX(self, painter): rect = self.getRectPlotter() if not rect.isValid(): return painter.save() painter.setFont(self._fontGrid) painter.setPen(QPen(Qt.black)) painter.setBrush(Qt.NoBrush) # Axis ticks dxmsec = rect.width() / self._plotterScale.Scale.X.span() fontMetricsF = QFontMetricsF(self._fontGrid) index = findIndex(fontMetricsF.width(' 00:00 ') / dxmsec, BasePlotter._mSecs_for_grid) msec0 = self._plotterScale.Scale.X.Min offset = findOffset(msec0, BasePlotter._mSecs_for_grid[index]) dx = dxmsec * BasePlotter._mSecs_for_grid[index] step = BasePlotter._mSecs_for_grid[index] for x in numpy.arange(rect.left() - dxmsec * offset, rect.right(), dx): if x < rect.left(): continue painter.save() heightTick = 3 datetimelabel = QDateTime.fromMSecsSinceEpoch(msec0, Qt.UTC) if step >= 60000: # больше минуты if step >= 86400000: # больше суток label = datetimelabel.toString('dd.MM.yy') if datetimelabel.time().minute() == 0: heightTick = 8 painter.setPen(Qt.SolidLine) else: t0 = QDateTime.fromMSecsSinceEpoch(self._plotterScale.Scale.X.Min, Qt.UTC) t1 = QDateTime.fromMSecsSinceEpoch(self._plotterScale.Scale.X.Max, Qt.UTC) if (datetimelabel.time().hour() == 0 and datetimelabel.time().minute() == 0) and ( t1.date() > t0.date()): # Метка даты. Появляется,если листаем график между днями font = QFont(painter.font().family(), painter.font().pointSize()) font.setBold(True) painter.setFont(font) label = datetimelabel.toString('dd.MM.yy') else: label = datetimelabel.toString('hh:mm') if datetimelabel.time().minute() == 0: heightTick = 8 painter.setPen(Qt.SolidLine) if datetimelabel.time().minute() == 30: heightTick = 6 painter.setPen(Qt.DashLine) if datetimelabel.time().minute() == 15 or datetimelabel.time().minute() == 45: heightTick = 4 painter.setPen(Qt.DashLine) else: label = datetimelabel.time().toString('hh:mm:ss') painter.drawLine(x, rect.bottom(), x, rect.top()) rect_label = QRectF(x - fontMetricsF.width(label) / 2, rect.bottom() + heightTick, fontMetricsF.width(label), 2 * fontMetricsF.height()) painter.drawLine(x, rect.bottom() - heightTick, x, rect.bottom() + heightTick) painter.drawText(rect_label, label) msec0 += step painter.restore() painter.restore() def clearPlotter(self, b_newData): self.deleteCurves() self._legend = "" if b_newData: self._date = QDate() def contextMenuEvent(self, event): self._contexMenu.exec(event.globalPos()) def onSavePlotter(self): saveFile, exp = QFileDialog.getSaveFileName(self, '', '', self.tr('Рисунок (*.png *.jpg)')) if not saveFile: return pixmap = QPixmap(self._pixmapSaveWidth, self._pixmapSaveHeight) painter = QPainter(pixmap) self.drawOnPlotter(painter) pixmap.save(saveFile) def onToggledTimer(self, b_check): if self._isWatcher: if b_check: self.timerTick.emit() self._timer.start( App.settings.value('/Settings/{0}/Main/TimeInterval'.format(App.settings.value(App.stationName())), 5000) * 1000) else: self._timer.stop() else: self.noWatching.emit(b_check) def setCurves(self, data, indexFreq): for key in data: canals = data[key] if not key in self._curves.keys(): if indexFreq == -1: self._curves[key] = canals else: pass
def get_date(self): date_now = list( map(int, str(datetime.datetime.now()).split()[0].split('-'))) self.date.setDate(QDate(*date_now))
def showEvent(self, ev): if self.selectedDate().year() == UNDEFINED_DATE.year: self.setSelectedDate(QDate.currentDate())