def date_edit_start_change(self, date: QDate) -> None: """ Slot for changing the end of a range of dates. :param date: Start of the date range """ end_date = self.date_edit_end.date().addDays( self._date_start_temp.daysTo(date)) self.date_edit_end.setDateRange(date.addDays(self._date_delta), date.addDays(365)) self.date_edit_end.setDate(end_date) self._date_start_temp = QDate(date)
def forecasting(self): siteId = getRequest( 'https://cisco-presence.unit.ua/api/config/v1/sites').stat().json( )[0]['aesUidString'] start = QDateTime(QDate(2017, 12, 21)).toTime_t() past = QDate().currentDate().addDays(-6) tomorrow = collections.OrderedDict({ '5-30 minutes': [], '30-60 minutes': [], '1-5 hours': [], '5-8 hours': [], 'more than 8 hours': [] }) while QDateTime(past).toTime_t() > start: ret = getRequest( 'https://cisco-presence.unit.ua/api/presence/v1/dwell/count?siteId=' + siteId + '&date=' + past.toString('yyyy-MM-dd')).stat().json() tomorrow['5-30 minutes'].append(ret['FIVE_TO_THIRTY_MINUTES']) tomorrow['30-60 minutes'].append(ret['THIRTY_TO_SIXTY_MINUTES']) tomorrow['1-5 hours'].append(ret['ONE_TO_FIVE_HOURS']) tomorrow['5-8 hours'].append(ret['FIVE_TO_EIGHT_HOURS']) tomorrow['more than 8 hours'].append(ret['EIGHT_PLUS_HOURS']) past = past.addDays(-7) tomorrow['5-30 minutes'] = int( statistics.median(tomorrow['5-30 minutes'])) tomorrow['30-60 minutes'] = int( statistics.median(tomorrow['30-60 minutes'])) tomorrow['1-5 hours'] = int(statistics.median(tomorrow['1-5 hours'])) tomorrow['5-8 hours'] = int(statistics.median(tomorrow['5-8 hours'])) tomorrow['more than 8 hours'] = int( statistics.median(tomorrow['more than 8 hours'])) return tomorrow
def on_btnIniData_clicked(self): ''' 初始化表格,根据表格行数,生成数据填充表格,为每个单元格对象设置属性 :return: ''' self.ui.tableInfo.clearContents()#清除表格内容,不包括表头 # self.ui.tableInfo.clear()#清除包括表头 birth = QDate(1998,6,23) isParth = True nation = '汉族' score= 70 rowCount = self.ui.tableInfo.rowCount()#获取表格行数 for i in range(rowCount): strName = '学生%d'%i if (i%2)==0: strSex = '男' else: strSex = '女' self.__createItemARow(i,strName,strSex,birth,nation,isParth,score) birth = birth.addDays(20) isParth = not isParth self.__tableInitialized = True
def dateAt( self, dayIndex ): prevMonthDays = self.daysFromPreviousMonth() dayOffset = dayIndex - prevMonthDays currYear = self.yearShown() currMonth = self.monthShown() currDate = QDate( currYear, currMonth, 1 ) return currDate.addDays( dayOffset )
def giorniDelMese(data: QDate) -> list: """ritorna una lista con i giorni del mese""" _mese = data.month() mese = data.month() primo = QDate(data.year(), data.month(), 1) lista = [] while mese == _mese: lista.append(primo) primo = primo.addDays(1) mese = primo.month() return lista
def date_edit_start_changed(self, date: QDate): """ Slot for changing the end of a range of dates. :param date: Start of the date range """ end_date = self.date_edit_end.date().addDays( self._date_start_cache.daysTo(date)) self.date_edit_end.setMinimumDate(date.addDays(7)) self.date_edit_end.setDate(end_date) self._date_start_cache = QDate(date)
def on_qPushButton3_clicked(self): # 初始化表格数据 self.ui.qTableWidget.clearContents() birth = QDate(1998, 6, 23) isParty = True nation = "汉族" score = 70 rowCount = self.ui.qTableWidget.rowCount() for i in range(rowCount): strName = "学生%d" % i if i % 2 == 0: strSex = "男" else: strSex = "女" self.__createItemsARow(i, strName, strSex, birth, nation, isParty, score) birth = birth.addDays(20) isParty = not isParty self.__tableInitialized = True
def createEditors(self): """Creates dialog input widgets. Override base class for specific forms""" today = QDate().currentDate() min_OD = today.addDays(-7) editors = { 'OD': DateEdit(parent=self, placeholderText='Date Observed', minimumDate=min_OD, image=DATE_OBSERVED_ICO), 'Tool': FilteringComboBox(parent=self, placeholderText='Tool', table='tool', column='name'), 'Category': FilteringComboBox(parent=self, placeholderText='Category', table='category', column='name', image=CATEGORY_ICO), 'Description': LineEdit(parent=self, placeholderText='Short Description', image=DESCRIPTION_ICO), 'Root Cause': LineEdit( parent=self, placeholderText='Possible root cause of the issue, if known', image=ROOT_CAUSE_ICO), 'RCD': DateEdit(parent=self, placeholderText='Requested Completion Date', minimumDate=today, image=REQUESTED_CD_ICO), # 'Tasks': PlainTextEdit( # parent=self, # placeholderText='Add tasks required for issue resoltion') } return editors
def reformatCalendarPage(self): if self.firstFridayCheckBox.isChecked(): firstFriday = QDate(self.calendar.yearShown(), self.calendar.monthShown(), 1) while firstFriday.dayOfWeek() != Qt.Friday: firstFriday = firstFriday.addDays(1) firstFridayFormat = QTextCharFormat() firstFridayFormat.setForeground(Qt.blue) self.calendar.setDateTextFormat(firstFriday, firstFridayFormat) # May 1st in Red takes precedence. if self.mayFirstCheckBox.isChecked(): mayFirst = QDate(self.calendar.yearShown(), 5, 1) mayFirstFormat = QTextCharFormat() mayFirstFormat.setForeground(Qt.red) self.calendar.setDateTextFormat(mayFirst, mayFirstFormat)
def on_btnIniData_clicked(self): self.ui.tableInfo.clearContents() #清除表格内容 birth = QDate(1998, 6, 23) isParty = True nation = "汉族" score = 70 rowCount = self.ui.tableInfo.rowCount() #表格行数 for i in range(rowCount): strName = "学生%d" % i if ((i % 2) == 0): strSex = "男" else: strSex = "女" self.__createItemsARow(i, strName, strSex, birth, nation, isParty, score) birth = birth.addDays(20) isParty = not isParty self.__tableInitialized = True #表格数据已初始化
def on_pushButton_initTableData_clicked(self): """初始化表格数据 生产每一行的信息 利用__createItemsARow()创建行 将__tableInitialized 置为True """ self._ui.tableWidget.clearContents() # 清除表格内容 birth = QDate(2000, 1, 20) isParty = True nation = '汉' score = 99 rowCount = self._ui.tableWidget.rowCount() # 表格行数 for i in range(rowCount): name = f'学生:{i}' sex = '女' if i % 2 else '男' self.__createItemsARow(i, name, sex, birth, nation, isParty, score) # 创建行 birth = birth.addDays(20) isParty = not isParty self.__tableInitialized = True # 表格数据初始化标识设置为True
def __init__(self, parent: QWidget = None): super().__init__(parent) self._size: int = os.cpu_count() if self._size is None: self._size = 2 self._processes_pool = [] self._manager = ImportManager(self._size) self._max_progress: int = 0 self._timer: QTimer = QTimer() self._confuser = ConfuseWindow(self) self._date_start_cache = None self._tesseract_path_cache = None self._poppler_path_cache = None # window settings self.setWindowFlag(Qt.WindowContextHelpButtonHint, False) self.setWindowTitle(self.tr("Import window")) # list widget with files self.list_widget = QListWidget() self.list_widget.setSortingEnabled(True) self.layout_open_folder = QHBoxLayout() self.label_find = QLabel(self.tr("Schedules: ") + "0") self.layout_open_folder.addWidget(self.label_find) self.layout_open_folder.addStretch(1) self.push_button_open_folder = QToolButton() self.layout_open_folder.addWidget(self.push_button_open_folder) self.push_button_open_folder.setText(self.tr("Open folder")) self.push_button_open_folder.setPopupMode(QToolButton.MenuButtonPopup) self.action_open_files = QAction(self.tr("Open files")) self.push_button_open_folder.addAction(self.action_open_files) # main progress self.group_box_main_progress = QGroupBox(self.tr("Main progress")) self.layout_main_progress = QVBoxLayout(self.group_box_main_progress) self.process_bar_main = QProgressBar() self.layout_main_progress.addWidget(self.process_bar_main) self.layout_start_process = QHBoxLayout() self.layout_start_process.addStretch(1) self.push_button_import = QPushButton(self.tr("Import")) self.layout_start_process.addWidget(self.push_button_import) self.push_button_stop = QPushButton(self.tr("Stop")) self.layout_start_process.addWidget(self.push_button_stop) self.push_button_stop.setEnabled(False) self.layout_main_progress.addLayout(self.layout_start_process) # threads process self.group_box_threads = QGroupBox(self.tr("Threads")) self.grid_layout_threads = QGridLayout(self.group_box_threads) self._progresses_bars = [] rows = self._size // 2 columns = 2 for i in range(rows): for j in range(columns): progress_bar = QProgressBar() progress_bar.setTextVisible(True) self._progresses_bars.append(progress_bar) self.grid_layout_threads.addWidget(progress_bar, i, j) # options self.group_box_options = QGroupBox(self.tr("Options")) self.form_layout_options = QFormLayout(self.group_box_options) self.check_box_weekly = QCheckBox(self.tr("Create weekly schedule")) self.form_layout_options.addRow(self.check_box_weekly) self.check_box_full = QCheckBox(self.tr("Create full schedule")) self.form_layout_options.addRow(self.check_box_full) self.check_box_debug_img = QCheckBox(self.tr("Create debug image")) self.form_layout_options.addRow(self.check_box_debug_img) self.spin_box_dpi = QSpinBox() self.form_layout_options.addRow(self.tr("DPI"), self.spin_box_dpi) self.combo_box_tesseract_path = QComboBox() self.form_layout_options.addRow(self.tr("Tesseract path"), self.combo_box_tesseract_path) self.combo_box_poppler_path = QComboBox() self.form_layout_options.addRow(self.tr("Poppler path"), self.combo_box_poppler_path) self.check_box_debug_img.setChecked(True) self.check_box_debug_img.setEnabled(False) self.spin_box_dpi.setRange(200, 800) self.spin_box_dpi.setValue(500) self.combo_box_tesseract_path.addItem( self.tr("<select tesseract path>")) self.combo_box_tesseract_path.addItem("Default", "tesseract") self.combo_box_tesseract_path.setCurrentIndex(1) self._tesseract_path_cache = self.combo_box_tesseract_path.currentText( ) self.combo_box_poppler_path.addItem(self.tr("<select poppler path>")) self.combo_box_poppler_path.addItem("Default", None) self.combo_box_poppler_path.setCurrentIndex(1) self._poppler_path_cache = self.combo_box_poppler_path.currentText() # font edit self.group_box_font = QGroupBox(self.tr("Font settings")) self.form_layout_font = QFormLayout(self.group_box_font) self.label_font = QLabel(self.tr("Font")) self.form_layout_font.setWidget(0, QFormLayout.LabelRole, self.label_font) self.combo_box_font = QComboBox() self.form_layout_font.setWidget(0, QFormLayout.FieldRole, self.combo_box_font) self.label_encoding = QLabel(self.tr("Encoding")) self.form_layout_font.setWidget(1, QFormLayout.LabelRole, self.label_encoding) self.combo_box_encoding = QComboBox() self.form_layout_font.setWidget(1, QFormLayout.FieldRole, self.combo_box_encoding) for font_name, font_path in util.get_fonts(): self.combo_box_font.addItem(font_name, font_path) self.combo_box_font.setCurrentText(qApp.font().family()) self.combo_box_font.setEditable(True) self.combo_box_encoding.addItem("UTF-8") self.combo_box_encoding.addItem("Latin-1") self.combo_box_encoding.addItem("Windows-1252") # date edit self.group_box_date = QGroupBox(self.tr("Date settings")) self.form_layout_date = QFormLayout(self.group_box_date) self.label_date_start = QLabel(self.tr("Start")) self.form_layout_date.setWidget(0, QFormLayout.LabelRole, self.label_date_start) self.date_edit_start = QDateEdit() self.form_layout_date.setWidget(0, QFormLayout.FieldRole, self.date_edit_start) self.label_date_end = QLabel(self.tr("End")) self.form_layout_date.setWidget(1, QFormLayout.LabelRole, self.label_date_end) self.date_edit_end = QDateEdit() self.form_layout_date.setWidget(1, QFormLayout.FieldRole, self.date_edit_end) self.date_edit_start.setCalendarPopup(True) self.date_edit_end.setCalendarPopup(True) if QDate.currentDate().day() < QDate.currentDate().dayOfYear() / 2: date = QDate(QDate.currentDate().year(), 2, 1) else: date = QDate(QDate.currentDate().year(), 9, 1) self._date_start_cache = date.addDays(8 - date.dayOfWeek()) self.date_edit_start.setDate(self._date_start_cache) self.date_edit_end.setMinimumDate(self._date_start_cache.addDays(7)) self.date_edit_end.setDate(self._date_start_cache.addDays(16 * 7)) # subgroup edit self.group_box_subgroup = QGroupBox(self.tr("Subgroup settings")) self.form_layout_subgroup = QFormLayout(self.group_box_subgroup) self.label_color_a = QLabel(self.tr("Color A")) self.form_layout_subgroup.setWidget(0, QFormLayout.LabelRole, self.label_color_a) self.combo_box_color_a = QComboBox() self.form_layout_subgroup.setWidget(0, QFormLayout.FieldRole, self.combo_box_color_a) self.label_color_b = QLabel(self.tr("Color B")) self.form_layout_subgroup.setWidget(1, QFormLayout.LabelRole, self.label_color_b) self.combo_box_color_b = QComboBox() self.form_layout_subgroup.setWidget(1, QFormLayout.FieldRole, self.combo_box_color_b) self.label_pattern_a_b = QLabel(self.tr("Pattern A and B")) self.form_layout_subgroup.setWidget(2, QFormLayout.LabelRole, self.label_pattern_a_b) self.combo_box_pattern_a_b = QComboBox() self.form_layout_subgroup.setWidget(2, QFormLayout.FieldRole, self.combo_box_pattern_a_b) self.add_standard_colors(self.combo_box_color_a) self.add_standard_colors(self.combo_box_color_b) self.combo_box_color_a.setCurrentIndex(9) # lime self.combo_box_color_b.setCurrentIndex(15) # yellow self.combo_box_pattern_a_b.addItem(self.tr("Chess order")) self.combo_box_pattern_a_b.setEnabled(False) # navigate self.layout_navigate = QHBoxLayout() self.layout_navigate.addStretch(1) self.push_button_ok = QPushButton(self.tr("OK")) self.layout_navigate.addWidget(self.push_button_ok) self.push_button_cancel = QPushButton(self.tr("Cancel")) self.layout_navigate.addWidget(self.push_button_cancel) # layout setup self.layout_left = QVBoxLayout() self.layout_left.addWidget(self.list_widget) self.layout_left.addLayout(self.layout_open_folder) self.layout_right = QVBoxLayout() self.layout_right.addWidget(self.group_box_main_progress) self.layout_right.addWidget(self.group_box_threads) self.layout_down = QGridLayout() self.layout_down.addWidget(self.group_box_options, 0, 0) self.layout_down.addWidget(self.group_box_font, 1, 0) self.layout_down.addWidget(self.group_box_date, 0, 1) self.layout_down.addWidget(self.group_box_subgroup, 1, 1) self.layout_right.addLayout(self.layout_down) self.layout_right.addStretch(1) self.layout_right.addLayout(self.layout_navigate) self.layout_main = QHBoxLayout() self.layout_main.addLayout(self.layout_left, 1) self.layout_main.addLayout(self.layout_right, 2) self.setLayout(self.layout_main) # connections self._timer.timeout.connect(self.check_processes) self.push_button_open_folder.clicked.connect(self.open_folder_clicked) self.action_open_files.triggered.connect(self.open_files_clicked) self.push_button_import.clicked.connect( self.push_button_import_clicked) self.push_button_stop.clicked.connect(self.push_button_stop_clicked) self.check_box_weekly.clicked.connect(self.check_box_weekly_clicked) self.combo_box_tesseract_path.activated.connect( self.combo_box_tesseract_path_clicked) self.combo_box_poppler_path.activated.connect( self.combo_box_poppler_path_clicked) self.date_edit_start.dateChanged.connect(self.date_edit_start_changed) self.combo_box_color_a.activated.connect( self.combo_box_color_a_clicked) self.combo_box_color_b.activated.connect( self.combo_box_color_b_clicked) self.push_button_ok.clicked.connect(self.close) self.push_button_cancel.clicked.connect(self.close)
def insertCalendar(self): self.editor.clear() cursor = self.editor.textCursor() cursor.beginEditBlock() date = QDate(self.selectedDate.year(), self.selectedDate.month(), 1) tableFormat = QTextTableFormat() tableFormat.setAlignment(Qt.AlignHCenter) tableFormat.setBackground(QColor("#e0e0e0")) tableFormat.setCellPadding(2) tableFormat.setCellSpacing(4) constraints = [ QTextLength(QTextLength.PercentageLength, 14), QTextLength(QTextLength.PercentageLength, 14), QTextLength(QTextLength.PercentageLength, 14), QTextLength(QTextLength.PercentageLength, 14), QTextLength(QTextLength.PercentageLength, 14), QTextLength(QTextLength.PercentageLength, 14), QTextLength(QTextLength.PercentageLength, 14), ] tableFormat.setColumnWidthConstraints(constraints) table = cursor.insertTable(1, 7, tableFormat) frame = cursor.currentFrame() frameFormat = frame.frameFormat() frameFormat.setBorder(1) frame.setFrameFormat(frameFormat) format = cursor.charFormat() format.setFontPointSize(self.fontSize) boldFormat = QTextCharFormat(format) boldFormat.setFontWeight(QFont.Bold) highlightedFormat = QTextCharFormat(boldFormat) highlightedFormat.setBackground(Qt.yellow) for weekDay in range(1, 8): cell = table.cellAt(0, weekDay - 1) cellCursor = cell.firstCursorPosition() cellCursor.insertText(QDate.longDayName(weekDay), boldFormat) table.insertRows(table.rows(), 1) while date.month() == self.selectedDate.month(): weekDay = date.dayOfWeek() cell = table.cellAt(table.rows() - 1, weekDay - 1) cellCursor = cell.firstCursorPosition() if date == QDate.currentDate(): cellCursor.insertText(str(date.day()), highlightedFormat) else: cellCursor.insertText(str(date.day()), format) date = date.addDays(1) if weekDay == 7 and date.month() == self.selectedDate.month(): table.insertRows(table.rows(), 1) cursor.endEditBlock() self.setWindowTitle( "Calendar for %s %d" % (QDate.longMonthName(self.selectedDate.month()), self.selectedDate.year()) )
def insertCalendar(self): self.editor.clear() cursor = self.editor.textCursor() cursor.beginEditBlock() #self.editor.setStyleSheet("QTextTableFormat {border-color:white}") date = QDate(self.selectedDate.year(), self.selectedDate.month(), 1) tableFormat = QTextTableFormat() self.setStyleSheet( "selection-color: yellow;" "selection-background-color: black;" "border-width: 1px;border-style: solid;border-color: white;") tableFormat.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) tableFormat.setBackground(QColor('#ffffff')) tableFormat.setCellPadding(1) tableFormat.setCellSpacing(0) constraints = [ QTextLength(QTextLength.PercentageLength, 7), QTextLength(QTextLength.PercentageLength, 7), QTextLength(QTextLength.PercentageLength, 7), QTextLength(QTextLength.PercentageLength, 7), QTextLength(QTextLength.PercentageLength, 7), QTextLength(QTextLength.PercentageLength, 7), QTextLength(QTextLength.PercentageLength, 7) ] tableFormat.setColumnWidthConstraints(constraints) table = cursor.insertTable(1, 7, tableFormat) # frame = cursor.currentFrame() # frameFormat = frame.frameFormat() # frameFormat.setBorder(2) # frame.setFrameFormat(frameFormat) format = cursor.charFormat() format.setFontPointSize(self.fontSize) boldFormat = QTextCharFormat(format) boldFormat.setFontWeight(QFont.Bold) dayFormat = QTextCharFormat(format) #self.editor.setStyleSheet("color:red;") dayFormat.setForeground(QColor('#f44336')) highlightedFormat = QTextCharFormat(boldFormat) highlightedFormat.setBackground(Qt.yellow) highlightedFormat.setFontUnderline(True) highlightedFormat.setUnderlineColor(QColor('#f44336')) # highlightedFormat.setColor(Qt.white) for weekDay in range(1, 8): cell = table.cellAt(0, weekDay - 1) cellCursor = cell.firstCursorPosition() cellCursor.insertText(day[weekDay - 1], dayFormat) table.insertRows(table.rows(), 1) while date.month() == self.selectedDate.month(): weekDay = date.dayOfWeek() cell = table.cellAt(table.rows() - 1, weekDay - 1) cellCursor = cell.firstCursorPosition() if date == QDate.currentDate(): cellCursor.insertText(str(date.day()), highlightedFormat) else: cellCursor.insertText(str(date.day()), format) date = date.addDays(1) if weekDay == 7 and date.month() == self.selectedDate.month(): table.insertRows(table.rows(), 1) cursor.endEditBlock() self.setWindowTitle("Calendar for %s %d" % (QDate.longMonthName( self.selectedDate.month()), self.selectedDate.year()))
def initUI(self): self.layout = QGridLayout() self.setLayout(self.layout) self.btns = [] self.spremi = QPushButton("Save") self.uvezi = QPushButton("Import") self.prebaci = QPushButton("Export to Excell") self.i = 0 self.j = 0 self.setAcceptDrops(True) self.scroll = QScrollArea() self.widget = QWidget() self.drag = QDrag(self) SL = [] ST1 = [] ST2 = [] ostalo = [] date = QDate() label = [] maximum = 0 minimum = 53 cursor.execute('SELECT naziv, dana, rok FROM pozicija JOIN pozicijaNarudzba ON pozicija.nacrt = pozicijaNarudzba.nacrt JOIN narudzba ON pozicijaNarudzba.narudzbenica = narudzba.narudzbenica WHERE pozicija.nacrt IN (SELECT nacrt FROM tehnologijapozicija WHERE cnc LIKE "SL")') tmp = cursor.fetchall() for x in range(len(tmp)): SL.append(x) for x in range(len(tmp)): SL[x] = Stroj(tmp[x][2], tmp[x][0], tmp[x][1]) cursor.execute('SELECT naziv, dana, rok FROM pozicija JOIN pozicijaNarudzba ON pozicija.nacrt = pozicijaNarudzba.nacrt JOIN narudzba ON pozicijaNarudzba.narudzbenica = narudzba.narudzbenica WHERE pozicija.nacrt IN (SELECT nacrt FROM tehnologijapozicija WHERE cnc LIKE "ST1")') tmp = cursor.fetchall() for x in range(len(tmp)): ST1.append(x) for x in range(len(tmp)): ST1[x] = Stroj(tmp[x][2], tmp[x][0], tmp[x][1]) cursor.execute('SELECT naziv, dana, rok FROM pozicija JOIN pozicijaNarudzba ON pozicija.nacrt = pozicijaNarudzba.nacrt JOIN narudzba ON pozicijaNarudzba.narudzbenica = narudzba.narudzbenica WHERE pozicija.nacrt IN (SELECT nacrt FROM tehnologijapozicija WHERE cnc LIKE "ST2")') tmp = cursor.fetchall() for x in range(len(tmp)): ST2.append(x) for x in range(len(tmp)): ST2[x] = Stroj(tmp[x][2], tmp[x][0], tmp[x][1]) cursor.execute('SELECT naziv, dana, rok FROM pozicija JOIN pozicijaNarudzba ON pozicija.nacrt = pozicijaNarudzba.nacrt JOIN narudzba ON pozicijaNarudzba.narudzbenica = narudzba.narudzbenica WHERE pozicija.nacrt IN (SELECT nacrt FROM tehnologijapozicija WHERE NOT cnc LIKE "SL" AND NOT cnc LIKE "ST1" AND NOT cnc LIKE "ST2")') tmp = cursor.fetchall() for x in range(len(tmp)): ostalo.append(x) for x in range(len(tmp)): ostalo[x] = Stroj(tmp[x][2], tmp[x][0], tmp[x][1]) for x in range(7): label.append(0) label = (QLabel("Ponedjeljak"), QLabel("Utorak"), QLabel("Srijeda"), QLabel("Četvrtak"), QLabel("Petak"), QLabel("Subota"), QLabel("Nedjelja")) for x in range(7): self.layout.addWidget(label[x], 0, x+1) for x in range(len(SL)): date = date.fromString(str(SL[x].rok), "yyyy-MM-dd") SL[x].trajanje = math.ceil(SL[x].trajanje) date = date.addDays(-SL[x].trajanje) tmp = date.weekNumber() if int(str(tmp[0])) > maximum: maximum = tmp[0] if int(str(tmp[0])) < minimum: minimum = tmp[0] for x in range(len(ST1)): date = date.fromString(str(ST1[x].rok), "yyyy-MM-dd") ST1[x].trajanje = math.ceil(ST1[x].trajanje) date = date.addDays(-ST1[x].trajanje) tmp = date.weekNumber() if int(str(tmp[0])) > maximum: maximum = tmp[0] if int(str(tmp[0])) < minimum: minimum = tmp[0] for x in range(len(ST2)): date = date.fromString(str(ST2[x].rok), "yyyy-MM-dd") ST2[x].trajanje = math.ceil(ST2[x].trajanje) date = date.addDays(-ST2[x].trajanje) tmp = date.weekNumber() if int(str(tmp[0])) > maximum: maximum = tmp[0] if int(str(tmp[0])) < minimum: minimum = tmp[0] for x in range(len(ostalo)): date = date.fromString(str(ostalo[x].rok), "yyyy-MM-dd") ostalo[x].trajanje = math.ceil(ostalo[x].trajanje) date = date.addDays(-ostalo[x].trajanje) tmp = date.weekNumber() if int(str(tmp[0])) > maximum: maximum = tmp[0] if int(str(tmp[0])) < minimum: minimum = tmp[0] for x in range((maximum - minimum + 1) * 28): self.btns.append(0) for x in range(maximum - minimum + 1): label = QLabel(str(minimum + x)+". Tjedan") self.layout.addWidget(label, 1 + x * 5, 0) label = (QLabel("SL"), QLabel("ST1"), QLabel("ST2"), QLabel("Ostalo")) for y in range(4): self.layout.addWidget(label[y], 2 + y + x * 5, 0) for z in range(7): self.btns[self.i] = Button("/", self) self.btns[self.i].setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) self.layout.addWidget(self.btns[self.i], y + 2 + x * 5, z + 1) self.i += 1 self.spremi.clicked.connect(self.toCSV) self.uvezi.clicked.connect(self.uvoz) self.prebaci.clicked.connect(self.izvoz) self.layout.addWidget(self.spremi, 1 + (maximum - minimum + 1) * 5, 3) self.layout.addWidget(self.uvezi, 1 + (maximum - minimum + 1) * 5, 4) self.layout.addWidget(self.prebaci, 1 + (maximum - minimum + 1) * 5, 5) self.ubaci(SL, minimum, date, 2) self.ubaci(ST1, minimum, date, 3) self.ubaci(ST2, minimum, date, 4) self.ubaci(ostalo, minimum, date, 5) self.widget.setLayout(self.layout) self.scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self.scroll.setWidgetResizable(True) self.scroll.setWidget(self.widget) self.setCentralWidget(self.scroll) self.setWindowTitle('Raspored') self.showMaximized()
def run(self): """Run method that performs all the real work""" # Create the dialog with elements (after translation) and keep reference # Only create GUI ONCE in callback, so that it will only load when the plugin is started if self.first_start == True: self.first_start = False self.dlg = SurvexImportDialog() self.dlg.selectedFile.clear() self.dlg.fileSelector.clicked.connect(self.select_3d_file) self.dlg.selectedGPKG.clear() self.dlg.GPKGSelector.clicked.connect(self.select_gpkg) self.dlg.CRSFromProject.setChecked(False) self.dlg.CRSFromFile.clicked.connect(self.crs_from_file) self.dlg.CRSFromFile.setChecked(False) self.dlg.CRSFromProject.clicked.connect(self.crs_from_project) self.dlg.ImportAll.clicked.connect(self.toggle_import_all) self.dlg.Legs.clicked.connect(self.all_checked) self.dlg.Stations.clicked.connect(self.all_checked) self.dlg.Polygons.clicked.connect(self.all_checked) self.dlg.Walls.clicked.connect(self.all_checked) self.dlg.XSections.clicked.connect(self.all_checked) self.dlg.Traverses.clicked.connect(self.all_checked) self.dlg.LegsSurface.clicked.connect(self.all_checked) self.dlg.LegsSplay.clicked.connect(self.all_checked) self.dlg.LegsDuplicate.clicked.connect(self.all_checked) self.dlg.StationsSurface.clicked.connect(self.all_checked) self.dlg.show() # show the dialog result = self.dlg.exec_() # Run the dialog event loop if result: # The user pressed OK, and this is what happened next! survex_3d = self.dlg.selectedFile.text() gpkg_file = self.dlg.selectedGPKG.text() include_legs = self.dlg.Legs.isChecked() include_stations = self.dlg.Stations.isChecked() include_polygons = self.dlg.Polygons.isChecked() include_walls = self.dlg.Walls.isChecked() include_xsections = self.dlg.XSections.isChecked() include_traverses = self.dlg.Traverses.isChecked() exclude_surface_legs = not self.dlg.LegsSurface.isChecked() exclude_splay_legs = not self.dlg.LegsSplay.isChecked() exclude_duplicate_legs = not self.dlg.LegsDuplicate.isChecked() exclude_surface_stations = not self.dlg.StationsSurface.isChecked() use_clino_wgt = self.dlg.UseClinoWeights.isChecked() include_up_down = self.dlg.IncludeUpDown.isChecked() discard_features = not self.dlg.KeepFeatures.isChecked() if not os.path.exists(survex_3d): raise Exception("File '%s' doesn't exist" % survex_3d) if discard_features: self.leg_list = [] self.station_list = [] self.station_xyz = {} self.xsect_list = [] # Read .3d file as binary, parse, and save data structures with open(survex_3d, 'rb') as fp: line = fp.readline().rstrip() # File ID check if not line.startswith(b'Survex 3D Image File'): raise IOError('Not a survex .3d file: ' + survex_3d) line = fp.readline().rstrip() # File format version if not line.startswith(b'v'): raise IOError('Unrecognised survex .3d version in ' + survex_3d) version = int(line[1:]) if version < 8: raise IOError('Survex .3d version >= 8 required in ' + survex_3d) line = fp.readline().rstrip( ) # Metadata (title and coordinate system) fields = line.split(b'\x00') previous_title = '' if discard_features else self.title if previous_title: self.title = previous_title + ' + ' + fields[0].decode( 'ascii') else: self.title = fields[0].decode('ascii') self.set_crs( fields[1].decode('ascii') if len(fields) > 1 else None) line = fp.readline().rstrip( ) # Timestamp, unused in present application if not line.startswith(b'@'): raise IOError('Unrecognised timestamp in ' + survex_3d) # timestamp = int(line[1:]) flag = ord(fp.read(1)) # file-wide flag if flag & 0x80: # abort if extended elevation raise IOError("Can't deal with extended elevation in " + survex_3d) # All file-wide header data read in, now read byte-wise # according to .3d spec. Note that all elements must # be processed, in order, otherwise we get out of sync. # We first define some baseline dates date0 = QDate(1900, 1, 1) date1 = QDate(1900, 1, 1) date2 = QDate(1900, 1, 1) label, style = '', 0xff # initialise label and style legs = [] # will be used to capture leg data between MOVEs xsect = [] # will be used to capture XSECT data nlehv = None # .. remains None if there isn't any error data... while True: # start of byte-gobbling while loop char = fp.read(1) if not char: # End of file (reached prematurely?) raise IOError('Premature end of file in ' + survex_3d) byte = ord(char) if byte <= 0x05: # STYLE if byte == 0x00 and style == 0x00: # this signals end of data if legs: # there may be a pending list of legs to save self.leg_list.append((legs, nlehv)) break # escape from byte-gobbling while loop else: style = byte elif byte <= 0x0e: # Reserved continue elif byte == 0x0f: # MOVE xyz = self.read_xyz(fp) if legs: self.leg_list.append((legs, nlehv)) legs = [] elif byte == 0x10: # DATE (none) date1 = date2 = date0 elif byte == 0x11: # DATE (single date) days = unpack('<H', fp.read(2))[0] date1 = date2 = date0.addDays(days) elif byte == 0x12: # DATE (date range, short format) days, extra = unpack('<HB', fp.read(3)) date1 = date0.addDays(days) date2 = date0.addDays(days + extra + 1) elif byte == 0x13: # DATE (date range, long format) days1, days2 = unpack('<HH', fp.read(4)) date1 = date0.addDays(days1) date2 = date0.addDays(days2) elif byte <= 0x1e: # Reserved continue elif byte == 0x1f: # Error info nlehv = unpack('<iiiii', fp.read(20)) elif byte <= 0x2f: # Reserved continue elif byte <= 0x33: # XSECT label = self.read_label(fp, label) if byte & 0x02: lrud = unpack('<iiii', fp.read(16)) else: lrud = unpack('<hhhh', fp.read(8)) xsect.append((label, lrud)) if byte & 0x01: # XSECT_END self.xsect_list.append(xsect) xsect = [] elif byte <= 0x3f: # Reserved continue elif byte <= 0x7f: # LINE flag = byte & 0x3f if not (flag & 0x20): label = self.read_label(fp, label) xyz_prev = xyz xyz = self.read_xyz(fp) while (True): # code pattern to implement logic if exclude_surface_legs and flag & 0x01: break if exclude_duplicate_legs and flag & 0x02: break if exclude_splay_legs and flag & 0x04: break legs.append(((xyz_prev, xyz), label, style, date1, date2, flag)) break elif byte <= 0xff: # LABEL (or NODE) flag = byte & 0x7f label = self.read_label(fp, label) xyz = self.read_xyz(fp) while (True): # code pattern to implement logic if exclude_surface_stations and flag & 0x01 and not flag & 0x02: break self.station_list.append((xyz, label, flag)) break self.station_xyz[label] = xyz # End of byte-gobbling while loop # file closes automatically, with open(survex_3d, 'rb') as fp: layers = [] # used to keep a list of the created layers if include_stations and self.station_list: # station layer station_layer = self.add_layer('stations', 'PointZ') attrs = [ QgsField(self.station_attr[k], QVariant.Int) for k in self.station_flags ] attrs.insert(0, QgsField('ELEVATION', QVariant.Double)) attrs.insert(0, QgsField('NAME', QVariant.String)) station_layer.dataProvider().addAttributes(attrs) station_layer.updateFields() features = [] for (xyz, label, flag) in self.station_list: xyz = [0.01 * v for v in xyz] attrs = [1 if flag & k else 0 for k in self.station_flags] attrs.insert(0, round(xyz[2], 2)) # elevation attrs.insert(0, label) feat = QgsFeature() geom = QgsGeometry(QgsPoint(*xyz)) feat.setGeometry(geom) feat.setAttributes(attrs) features.append(feat) station_layer.dataProvider().addFeatures(features) layers.append(station_layer) if include_legs and self.leg_list: # leg layer leg_layer = self.add_layer('legs', 'LineStringZ') attrs = [ QgsField(self.leg_attr[k], QVariant.Int) for k in self.leg_flags ] if nlehv: [ attrs.insert(0, QgsField(s, QVariant.Double)) for s in self.error_fields ] attrs.insert(0, QgsField('NLEGS', QVariant.Int)) attrs.insert(0, QgsField('DATE2', QVariant.Date)) attrs.insert(0, QgsField('DATE1', QVariant.Date)) attrs.insert(0, QgsField('STYLE', QVariant.String)) attrs.insert(0, QgsField('ELEVATION', QVariant.Double)) attrs.insert(0, QgsField('NAME', QVariant.String)) leg_layer.dataProvider().addAttributes(attrs) leg_layer.updateFields() features = [] for legs, nlehv in self.leg_list: for (xyz_pair, label, style, from_date, to_date, flag) in legs: elev = 0.5 * sum([0.01 * xyz[2] for xyz in xyz_pair]) points = [] for xyz in xyz_pair: xyz = [0.01 * v for v in xyz] points.append(QgsPoint(*xyz)) attrs = [1 if flag & k else 0 for k in self.leg_flags] if nlehv: [ attrs.insert(0, 0.01 * v) for v in reversed(nlehv[1:5]) ] attrs.insert(0, nlehv[0]) attrs.insert(0, to_date) attrs.insert(0, from_date) attrs.insert(0, self.style_type[style]) attrs.insert(0, round(elev, 2)) attrs.insert(0, label) linestring = QgsLineString() linestring.setPoints(points) feat = QgsFeature() geom = QgsGeometry(linestring) feat.setGeometry(geom) feat.setAttributes(attrs) features.append(feat) leg_layer.dataProvider().addFeatures(features) layers.append(leg_layer) # Now do wall features if asked if (include_traverses or include_xsections or include_walls or include_polygons) and self.xsect_list: trav_features = [] wall_features = [] xsect_features = [] quad_features = [] for xsect in self.xsect_list: if len(xsect) < 2: # if there's only one station .. continue # .. give up as we don't know which way to face centerline = [ ] # will contain the station position and LRUD data for label, lrud in xsect: xyz = self.station_xyz[ label] # look up coordinates from label lrud_or_zero = tuple([max(0, v) for v in lrud ]) # deal with missing data centerline.append( xyz + lrud_or_zero) # and collect as 7-uple direction = [ ] # will contain the corresponding direction vectors # The calculations below use integers for xyz and lrud, and # conversion to metres is left to the end. Then dh2 is an # integer and the test for a plumb is safely dh2 = 0. # The directions are unit vectors optionally weighted by # cos(inclination) = dh/dl where dh^2 = dx^2 + dy^2 (note, no dz^2), # and dl^2 = dh^2 + dz^2. The normalisation is correspondingly # either 1/dh, or 1/dh * dh/dl = 1/dl. for i, xyzlrud in enumerate(centerline): x, y, z = xyzlrud[0:3] if i > 0: dx, dy, dz = x - xp, y - yp, z - zp dh2 = dx * dx + dy * dy # integer horizontal displacement (mm^2) norm = sqrt(dh2 + dz * dz) if use_clino_wgt else sqrt(dh2) dx, dy = (dx / norm, dy / norm) if dh2 > 0 and norm > 0 else (0, 0) direction.append((dx, dy)) xp, yp, zp = x, y, z left_wall = [] right_wall = [] up_down = [] # We build the walls by walking through the list # of stations and directions, with simple defaults # for the start and end stations for i, (x, y, z, l, r, u, d) in enumerate(centerline): d1x, d1y = direction[i - 1] if i > 0 else (0, 0) d2x, d2y = direction[i] if i + 1 < len( centerline) else (0, 0) dx, dy = d1x + d2x, d1y + d2y # mean (sum of) direction vectors norm = sqrt(dx * dx + dy * dy) # normalise to unit vector ex, ey = (dx / norm, dy / norm) if norm > 0 else (0, 0) # Convert to metres when saving the points left_wall.append((0.01 * (x - l * ey), 0.01 * (y + l * ex), 0.01 * z)) right_wall.append((0.01 * (x + r * ey), 0.01 * (y - r * ex), 0.01 * z)) up_down.append((0.01 * u, 0.01 * d)) # Mean elevation of centerline, used for elevation attribute elev = 0.01 * sum([xyzlrud[2] for xyzlrud in centerline ]) / len(centerline) attrs = [round(elev, 2)] # Now create the feature sets - first the centerline traverse points = [] for xyzlrud in centerline: xyz = [0.01 * v for v in xyzlrud[0:3] ] # These were mm, convert to metres points.append(QgsPoint(*xyz)) linestring = QgsLineString() linestring.setPoints(points) feat = QgsFeature() geom = QgsGeometry(linestring) feat.setGeometry(geom) feat.setAttributes(attrs) trav_features.append(feat) # The walls as line strings for wall in (left_wall, right_wall): points = [QgsPoint(*xyz) for xyz in wall] linestring = QgsLineString() linestring.setPoints(points) feat = QgsFeature() geom = QgsGeometry(linestring) feat.setGeometry(geom) feat.setAttributes(attrs) wall_features.append(feat) # Slightly more elaborate, pair up points on left # and right walls, and build a cross section as a # 2-point line string, and a quadrilateral polygon # with a closed 5-point line string for the # exterior ring. Note that QGIS polygons are # supposed to have their points ordered clockwise. for i, xyz_pair in enumerate(zip(left_wall, right_wall)): elev = 0.01 * centerline[i][ 2] # elevation of station in centerline attrs = [round(elev, 2)] points = [QgsPoint(*xyz) for xyz in xyz_pair] linestring = QgsLineString() linestring.setPoints(points) feat = QgsFeature() geom = QgsGeometry(linestring) feat.setGeometry(geom) feat.setAttributes(attrs) xsect_features.append(feat) if i > 0: elev = 0.5 * (prev_xyz_pair[0][2] + xyz_pair[0][2] ) # average elevation attrs = [round(elev, 2)] if include_up_down: # average up / down attrs += [ 0.5 * (v1 + v2) for (v1, v2) in zip(up_down[i - 1], up_down[i]) ] points = [ ] # will contain the exterior 5-point ring, as follows... for xyz in tuple( reversed(prev_xyz_pair)) + xyz_pair + ( prev_xyz_pair[1], ): points.append(QgsPoint(*xyz)) linestring = QgsLineString() linestring.setPoints(points) polygon = QgsPolygon() polygon.setExteriorRing(linestring) feat = QgsFeature() geom = QgsGeometry(polygon) feat.setGeometry(geom) feat.setAttributes(attrs) quad_features.append(feat) prev_xyz_pair = xyz_pair # End of processing xsect_list - now add features to requested layers attrs = [QgsField('ELEVATION', QVariant.Double)] # common to all if include_traverses and trav_features: # traverse layer travs_layer = self.add_layer('traverses', 'LineStringZ') travs_layer.dataProvider().addAttributes(attrs) travs_layer.updateFields() travs_layer.dataProvider().addFeatures(trav_features) layers.append(travs_layer) if include_xsections and xsect_features: # xsection layer xsects_layer = self.add_layer('xsections', 'LineStringZ') xsects_layer.dataProvider().addAttributes(attrs) xsects_layer.updateFields() xsects_layer.dataProvider().addFeatures(xsect_features) layers.append(xsects_layer) if include_walls and wall_features: # wall layer walls_layer = self.add_layer('walls', 'LineStringZ') walls_layer.dataProvider().addAttributes(attrs) walls_layer.updateFields() walls_layer.dataProvider().addFeatures(wall_features) layers.append(walls_layer) if include_up_down: # add fields if requested for polygons attrs += [ QgsField(s, QVariant.Double) for s in ('MEAN_UP', 'MEAN_DOWN') ] if include_polygons and quad_features: # polygon layer quads_layer = self.add_layer('polygons', 'PolygonZ') quads_layer.dataProvider().addAttributes(attrs) quads_layer.updateFields() quads_layer.dataProvider().addFeatures(quad_features) layers.append(quads_layer) # All layers have been created, now update extents and add to QGIS registry if layers: [layer.updateExtents() for layer in layers] QgsProject.instance().addMapLayers(layers) # Write to GeoPackage if requested if gpkg_file: opts = [ QgsVectorFileWriter.CreateOrOverwriteFile, QgsVectorFileWriter.CreateOrOverwriteLayer ] for i, layer in enumerate(layers): options = QgsVectorFileWriter.SaveVectorOptions() options.actionOnExistingFile = opts[int( i > 0)] # create file or layer layer_name = layer.name() match = search( ' - ([a-z]*)', layer_name) # ie, extract 'legs', 'stations', etc options.layerName = str( match.group(1)) if match else layer_name writer = QgsVectorFileWriter.writeAsVectorFormat( layer, gpkg_file, options) if writer: msg = "'{}' -> {} in {}".format( layer_name, options.layerName, gpkg_file) QgsMessageLog.logMessage(msg, tag='Import .3d', level=Qgis.Info) options, writer = None, None
def generate_actions(self, plan): action_list = [] begin = QDate(plan.begin_date) deadline = QDate(plan.deadline) include = self.cb_include.isChecked() if plan.frequency == PlanFrequency.NoRepeat: days = begin.daysTo(deadline) if not include: if days == 0: return -1, 'There is not time to complete the plan' for i in range(plan.repeat): action = Action(content=plan.content, begin_date=plan.begin_date, deadline=plan.deadline, degree_importance=plan.degree_importance, degree_urgency=plan.degree_urgency, status=1) action_list.append(action) elif plan.frequency == PlanFrequency.Day: days = begin.daysTo(deadline) if not include: if days == 0: return -1, 'There is not time to complete the plan' for day in range(days + 1): if not include and day == 0: continue begin_date = begin.addDays(day) begin_date = datetime.date(begin_date.year(), begin_date.month(), begin_date.day()) for i in range(plan.repeat): action = Action(content=plan.content, begin_date=begin_date, deadline=begin_date, degree_importance=plan.degree_importance, degree_urgency=plan.degree_urgency, status=1) action_list.append(action) elif plan.frequency == PlanFrequency.Week: begin_week, begin_year = begin.weekNumber() begin_day_of_week = begin.dayOfWeek() deadline_week, deadline_year = deadline.weekNumber() weeks = deadline_week + (deadline_year - begin_year) * 52 - begin_week if not include: if weeks == 0: return -1, 'There is not time to complete the plan' current_week_deadline = begin.addDays(7 - begin_day_of_week) for week in range(weeks + 1): if not include and week == 0: continue current_week_deadline = current_week_deadline.addDays(7 * week) current_week_begin = current_week_deadline.addDays(-6) if week == 0: begin_date = plan.begin_date if week == weeks: deadline = plan.deadline else: deadline = datetime.date(current_week_deadline.year(), current_week_deadline.month(), current_week_deadline.day()) elif week == weeks: begin_date = datetime.date(current_week_begin.year(), current_week_begin.month(), current_week_begin.day()) deadline = plan.deadline else: begin_date = datetime.date(current_week_begin.year(), current_week_begin.month(), current_week_begin.day()) deadline = datetime.date(current_week_deadline.year(), current_week_deadline.month(), current_week_deadline.day()) for i in range(plan.repeat): action = Action(content=plan.content, begin_date=begin_date, deadline=deadline, degree_importance=plan.degree_importance, degree_urgency=plan.degree_urgency, status=1) action_list.append(action) elif plan.frequency == PlanFrequency.Month: begin_year = begin.year() deadline_year = deadline.year() years = deadline_year - begin_year begin_month = begin.month() deadline_month = deadline.month() months = deadline_month + 12 * years - begin_month if not include: if months == 0: return -1, 'There is not time to complete the plan' current_year = begin_year for month in range(months + 1): if not include and month == 0: continue current_month = begin_month + month if current_month > 12: current_month -= 12 current_year += 1 if month == 0: begin_date = plan.begin_date if month == months: deadline = plan.deadline else: deadline = datetime.date(current_year, current_month, begin.daysInMonth()) elif month == months: begin_date = datetime.date(current_year, current_month, 1) deadline = plan.deadline else: begin_date = datetime.date(current_year, current_month, 1) deadline = datetime.date(current_year, current_month, 1) deadline = datetime.date( current_year, current_month, QDate(deadline.year(), deadline.month(), deadline.day()).daysInMonth()) for i in range(plan.repeat): action = Action(content=plan.content, begin_date=begin_date, deadline=deadline, degree_importance=plan.degree_importance, degree_urgency=plan.degree_urgency, status=1) action_list.append(action) elif plan.frequency == PlanFrequency.Quarter: begin_year = begin.year() deadline_year = deadline.year() years = deadline_year - begin_year begin_month = begin.month() deadline_month = deadline.month() begin_quarter = (begin_month + 2) / 3 deadline_quarter = (deadline_month + 2) / 3 quarters = deadline_quarter + years * 4 - begin_quarter if not include: if quarters == 0: return -1, 'There is not time to complete the plan' current_year = begin_year for quarter in range(quarters + 1): if not include and quarter == 0: continue current_quarter = begin_quarter + quarter if current_quarter > 4: current_quarter -= 4 current_year += 1 begin_month = (current_quarter - 1) * 3 + 1 deadline_month = begin_month + 2 if quarter == 0: begin_date = plan.begin_date if quarter == quarters: deadline = plan.deadline else: deadline = datetime.date( current_year, deadline_month, (30 if deadline_month == 4 else 31)) elif quarter == quarters: begin_date = datetime.date(current_year, begin_month, 1) deadline = plan.deadline else: begin_date = datetime.date(current_year, begin_month, 1) deadline = datetime.date( current_year, deadline_month, (30 if deadline_month == 4 else 31)) for i in range(plan.repeat): action = Action(content=plan.content, begin_date=begin_date, deadline=deadline, degree_importance=plan.degree_importance, degree_urgency=plan.degree_urgency, status=1) action_list.append(action) elif plan.frequency == PlanFrequency.Year: begin_year = begin.year() deadline_year = deadline.year() years = deadline_year - begin_year if not include: if years == 0: return -1, 'There is not time to complete the plan' for year in range(years + 1): if not include and year == 0: continue current_year = begin_year + year if year == 0: begin_date = plan.begin_date if year == years: deadline = plan.deadline else: deadline = datetime.date(current_year, 12, 31) elif year == years: begin_date = datetime.date(current_year, 1, 1) deadline = plan.deadline else: begin_date = datetime.date(current_year, 1, 1) deadline = datetime.date(current_year, 12, 31) for i in range(plan.repeat): action = Action(content=plan.content, begin_date=begin_date, deadline=deadline, degree_importance=plan.degree_importance, degree_urgency=plan.degree_urgency, status=1) action_list.append(action) return 0, action_list
def __init__(self, schedule: Schedule, parent: QWidget = None): super().__init__(parent) self._schedule_ref = schedule self._date_start_cache = None # window settings self.setWindowFlag(Qt.WindowContextHelpButtonHint, False) self.setWindowTitle(self.tr("Export window")) self.setMinimumWidth(800) # title, add_date, work mode self.layout_title_date_mode = QHBoxLayout() self.label_title = QLabel(self.tr("Title")) self.layout_title_date_mode.addWidget(self.label_title) self.line_edit_title = QLineEdit() self.layout_title_date_mode.addWidget(self.line_edit_title) self.check_box_add_date = QCheckBox(self.tr("Add date")) self.layout_title_date_mode.addWidget(self.check_box_add_date) self.combo_box_work_mode = QComboBox() self.layout_title_date_mode.addWidget(self.combo_box_work_mode) self.line_edit_title.setPlaceholderText( self.tr("My Group. A subgroup - green color, " "B subgroup - yellow color. ")) self.check_box_add_date.setChecked(True) self.combo_box_work_mode.addItem(self.tr("Weekly")) self.combo_box_work_mode.addItem(self.tr("Full")) # list widget with files self.layout_list_widget = QVBoxLayout() self.check_box_use_current = QCheckBox(self.tr("Use current schedule")) self.layout_list_widget.addWidget(self.check_box_use_current) self.check_box_use_current.setChecked(True) self.list_widget = QListWidget() self.layout_list_widget.addWidget(self.list_widget) self.list_widget.setSortingEnabled(True) self.list_widget.setEnabled(False) self.layout_open_folder = QHBoxLayout() self.layout_list_widget.addLayout(self.layout_open_folder) self.label_find = QLabel(self.tr("Schedules: ") + "0") self.layout_open_folder.addWidget(self.label_find) self.layout_open_folder.addStretch(1) self.push_button_open_folder = QToolButton() self.layout_open_folder.addWidget(self.push_button_open_folder) self.push_button_open_folder.setEnabled(False) self.push_button_open_folder.setText(self.tr("Open folder")) self.push_button_open_folder.setPopupMode(QToolButton.MenuButtonPopup) self.action_open_files = QAction(self.tr("Open files")) self.push_button_open_folder.addAction(self.action_open_files) # font edit self.group_box_font = QGroupBox(self.tr("Font settings")) self.form_layout_font = QFormLayout(self.group_box_font) self.label_font = QLabel(self.tr("Font")) self.form_layout_font.setWidget(0, QFormLayout.LabelRole, self.label_font) self.combo_box_font = QComboBox() self.form_layout_font.setWidget(0, QFormLayout.FieldRole, self.combo_box_font) self.label_encoding = QLabel(self.tr("Encoding")) self.form_layout_font.setWidget(1, QFormLayout.LabelRole, self.label_encoding) self.combo_box_encoding = QComboBox() self.form_layout_font.setWidget(1, QFormLayout.FieldRole, self.combo_box_encoding) for font_name, font_path in util.get_fonts(): self.combo_box_font.addItem(font_name, font_path) self.combo_box_font.setCurrentText(qApp.font().family()) self.combo_box_font.setEditable(True) self.combo_box_encoding.addItem("UTF-8") self.combo_box_encoding.addItem("Latin-1") self.combo_box_encoding.addItem("Windows-1252") # date edit self.group_box_date = QGroupBox(self.tr("Date settings")) self.form_layout_date = QFormLayout(self.group_box_date) self.label_date_start = QLabel(self.tr("Start")) self.form_layout_date.setWidget(0, QFormLayout.LabelRole, self.label_date_start) self.date_edit_start = QDateEdit() self.form_layout_date.setWidget(0, QFormLayout.FieldRole, self.date_edit_start) self.label_date_end = QLabel(self.tr("End")) self.form_layout_date.setWidget(1, QFormLayout.LabelRole, self.label_date_end) self.date_edit_end = QDateEdit() self.form_layout_date.setWidget(1, QFormLayout.FieldRole, self.date_edit_end) self.date_edit_start.setCalendarPopup(True) self.date_edit_end.setCalendarPopup(True) if QDate.currentDate().day() < (QDate.currentDate().dayOfYear() / 2): date = QDate(QDate.currentDate().year(), 2, 1) else: date = QDate(QDate.currentDate().year(), 9, 1) self._date_start_cache = date.addDays(8 - date.dayOfWeek()) self.date_edit_start.setDate(self._date_start_cache) self.date_edit_end.setMinimumDate(self._date_start_cache.addDays(7)) self.date_edit_end.setDate(self._date_start_cache.addDays(16 * 7)) # subgroup edit self.group_box_subgroup = QGroupBox(self.tr("Subgroup settings")) self.form_layout_subgroup = QFormLayout(self.group_box_subgroup) self.label_color_a = QLabel(self.tr("Color A")) self.form_layout_subgroup.setWidget(0, QFormLayout.LabelRole, self.label_color_a) self.combo_box_color_a = QComboBox() self.form_layout_subgroup.setWidget(0, QFormLayout.FieldRole, self.combo_box_color_a) self.label_color_b = QLabel(self.tr("Color B")) self.form_layout_subgroup.setWidget(1, QFormLayout.LabelRole, self.label_color_b) self.combo_box_color_b = QComboBox() self.form_layout_subgroup.setWidget(1, QFormLayout.FieldRole, self.combo_box_color_b) self.label_pattern_a_b = QLabel(self.tr("Pattern A and B")) self.form_layout_subgroup.setWidget(2, QFormLayout.LabelRole, self.label_pattern_a_b) self.combo_box_pattern_a_b = QComboBox() self.form_layout_subgroup.setWidget(2, QFormLayout.FieldRole, self.combo_box_pattern_a_b) self.add_standard_colors(self.combo_box_color_a) self.add_standard_colors(self.combo_box_color_b) self.combo_box_color_a.setCurrentIndex(9) # lime self.combo_box_color_b.setCurrentIndex(15) # yellow self.combo_box_pattern_a_b.addItem(self.tr("Chess order")) self.combo_box_pattern_a_b.setEnabled(False) # navigate buttons self.layout_navigate = QHBoxLayout() self.layout_navigate.addStretch(1) self.push_button_export = QPushButton(self.tr("Export")) self.layout_navigate.addWidget(self.push_button_export) self.push_button_cancel = QPushButton(self.tr("Cancel")) self.layout_navigate.addWidget(self.push_button_cancel) # layout setup self.layout_right_setting = QVBoxLayout() self.layout_right_setting.addWidget(self.group_box_font) self.layout_right_setting.addWidget(self.group_box_date) self.layout_right_setting.addWidget(self.group_box_subgroup) self.layout_right_setting.addStretch(1) self.layout_center = QHBoxLayout() self.layout_center.addLayout(self.layout_list_widget) self.layout_center.addLayout(self.layout_right_setting) self.layout_main = QVBoxLayout() self.layout_main.addLayout(self.layout_title_date_mode) self.layout_main.addLayout(self.layout_center) self.layout_main.addLayout(self.layout_navigate) self.setLayout(self.layout_main) # connection self.check_box_use_current.clicked.connect( self.check_box_use_current_clicked) self.push_button_open_folder.clicked.connect(self.open_folder_clicked) self.action_open_files.triggered.connect(self.open_files_clicked) self.date_edit_start.dateChanged.connect(self.date_edit_start_changed) self.combo_box_color_a.activated.connect( self.combo_box_color_a_clicked) self.combo_box_color_b.activated.connect( self.combo_box_color_b_clicked) self.push_button_export.clicked.connect(self.export_to_pdf) self.push_button_cancel.clicked.connect(self.close)
def insertCalendar(self): self.editor.clear() cursor = self.editor.textCursor() cursor.beginEditBlock() date = QDate(self.selectedDate.year(), self.selectedDate.month(), 1) tableFormat = QTextTableFormat() tableFormat.setAlignment(Qt.AlignHCenter) tableFormat.setBackground(QColor('#e0e0e0')) tableFormat.setCellPadding(2) tableFormat.setCellSpacing(4) constraints = [QTextLength(QTextLength.PercentageLength, 14), QTextLength(QTextLength.PercentageLength, 14), QTextLength(QTextLength.PercentageLength, 14), QTextLength(QTextLength.PercentageLength, 14), QTextLength(QTextLength.PercentageLength, 14), QTextLength(QTextLength.PercentageLength, 14), QTextLength(QTextLength.PercentageLength, 14)] tableFormat.setColumnWidthConstraints(constraints) table = cursor.insertTable(1, 7, tableFormat) frame = cursor.currentFrame() frameFormat = frame.frameFormat() frameFormat.setBorder(1) frame.setFrameFormat(frameFormat) format = cursor.charFormat() format.setFontPointSize(self.fontSize) boldFormat = QTextCharFormat(format) boldFormat.setFontWeight(QFont.Bold) highlightedFormat = QTextCharFormat(boldFormat) highlightedFormat.setBackground(Qt.yellow) for weekDay in range(1, 8): cell = table.cellAt(0, weekDay-1) cellCursor = cell.firstCursorPosition() cellCursor.insertText(QDate.longDayName(weekDay), boldFormat) table.insertRows(table.rows(), 1) while date.month() == self.selectedDate.month(): weekDay = date.dayOfWeek() cell = table.cellAt(table.rows()-1, weekDay-1) cellCursor = cell.firstCursorPosition() if date == QDate.currentDate(): cellCursor.insertText(str(date.day()), highlightedFormat) else: cellCursor.insertText(str(date.day()), format) date = date.addDays(1) if weekDay == 7 and date.month() == self.selectedDate.month(): table.insertRows(table.rows(), 1) cursor.endEditBlock() self.setWindowTitle("Calendar for %s %d" % (QDate.longMonthName(self.selectedDate.month()), self.selectedDate.year()))
def drawChart(self): conn=sqlite3.connect('emaildb.sqlite') cur=conn.cursor() title=self.lineEditProdName.text() mall_url=self.farm_combo.currentText() sql=f"select dt, jjim, sold, review from PROD3 where title='{title}'" cur.execute(sql) conn.commit() rows=cur.fetchall() series=[] # series = QLineSeries(self) series.append(QLineSeries(self)) series.append(QLineSeries(self)) series.append(QLineSeries(self)) tod=datetime.today() nextday=datetime.today()+timedelta(days=1) d=QDate(2020,1,3) dt=QDateTime(d) d2=d.addDays(1) dt2=dt.addDays(1) for i,row in enumerate(rows): for j, serie in enumerate(series): # serie.append((dt.addDays(i)).toMSecsSinceEpoch(),int(row[j+1])) serie.append(i,int(row[j+1])) for serie in series: serie.setPointsVisible(True) self.linechart.removeAllSeries() self.linechart2.removeAllSeries() self.linechart3.removeAllSeries() self.linechart.addSeries(series[0]) self.linechart2.addSeries(series[1]) self.linechart3.addSeries(series[2]) dateAxis=QDateTimeAxis() dateAxis2=QDateTimeAxis() dateAxis3=QDateTimeAxis() self.linechart.addAxis(dateAxis, Qt.AlignBottom) self.linechart2.addAxis(dateAxis2, Qt.AlignBottom) self.linechart3.addAxis(dateAxis3, Qt.AlignBottom) self.linechart.createDefaultAxes() self.linechart2.createDefaultAxes() self.linechart3.createDefaultAxes() self.linechart.setAnimationOptions(QChart.SeriesAnimations) self.linechart.setTitle("찜") self.linechart.legend().setVisible(True) self.linechart2.setAnimationOptions(QChart.SeriesAnimations) self.linechart2.setTitle("구매") self.linechart2.legend().setVisible(True) self.linechart3.setAnimationOptions(QChart.SeriesAnimations) self.linechart3.setTitle("리뷰") self.linechart3.legend().setVisible(True) self.chartview.setRenderHint(QPainter.Antialiasing) self.chartview2.setRenderHint(QPainter.Antialiasing) self.chartview3.setRenderHint(QPainter.Antialiasing) cur.close() conn.close()
class Hoje: soma_entrada = 0 soma_saida = 0 soma_fixo = 0 soma_reserva = 0 soma_hoje = 0 soma_semana = 0 mes_limite = 0 mes_resta = 0 hoje_limite = 0 hoje_resta = 0 media_dia = 0 dia_limite = 0 semana_limite = 0 semana_resta = 0 ajuste = 0 def __init__(self, Tabela, Janela, Info): self.Tabela = Tabela self.Info = Info self.Dia = Janela.groupDia.setTitle self.Inicio = QDate() self.Inicio.setDate(self.Info.ano_int, self.Info.mes_int, 1) self.Referencia = QDate() self.Referencia.setDate(self.Info.ano_int, self.Info.mes_int, self.Info.referencia) self.Ontem = self.Referencia.addDays(-1) self.HojeGasto = Janela.labelHojeGastoV self.HojeLimite = Janela.labelHojeLimiteV self.HojeResto = Janela.labelHojeRestaV self.HojeBarra = Janela.progressBarHoje self.SemanaGasto = Janela.labelSemanaGastoV self.SemanaLimite = Janela.labelSemanaLimiteV self.SemanaResto = Janela.labelSemanaRestaV self.SemanaBarra = Janela.progressBarSemana self.MesGasto = Janela.labelMesGastoV self.MesLimite = Janela.labelMesLimiteV self.MesResto = Janela.labelMesRestaV self.MesBarra = Janela.progressBarMes self.Ajuste = Janela.labelAjuste self.BoxAjuste = Janela.boxAjuste self.LimiteDia = Janela.labelLimiteDia self.Media = Janela.labelMedia self.TotalAjuste = Janela.labelTotalAjustesV self.TotalEntrada = Janela.labelTotalEntradaV self.TotalFixo = Janela.labelTotalFixoV self.TotalReserva = Janela.labelTotalReservaV self.atualiza() def atualiza( self ): # todo o que fazer na virada da meia noite?? Quando muda o dia? Talvez costum no config? self.soma_saida = self.Tabela.Saida.soma() self.soma_entrada = self.Tabela.Entrada.soma() self.soma_fixo = self.Tabela.Fixo.soma() self.soma_reserva = self.Tabela.Reserva.soma() self.soma_hoje = self.Tabela.Saida.soma_data(self.Referencia) self.soma_ajuste = self.Info.reserva + self.Info.erro self.mes_limite = self.soma_entrada + self.soma_ajuste - self.soma_fixo - self.soma_reserva self.mes_resta = self.mes_limite - self.soma_saida dia_mes = self.Info.referencia dia_total = self.Info.tempo.daysInMonth() try: dia_percent = (dia_mes / dia_total) * 100 except ZeroDivisionError: dia_percent = 0 self.Dia("Dia: " + str(dia_mes) + " de " + str(dia_total) + " (" + f'{dia_percent:.0f}' + "%)") if self.Referencia.day() > 1: self.media_dia = self.Tabela.Saida.soma_intervalo( self.Inicio, self.Ontem) / self.Ontem.day() dia_restante = dia_total - self.Ontem.day() else: self.media_dia = 0 dia_restante = dia_total try: self.dia_limite = self.mes_limite / dia_total except ZeroDivisionError: self.dia_limite = 0 gasto_base = self.Tabela.Saida.soma_intervalo(self.Inicio, self.Ontem) try: self.hoje_limite = (self.mes_limite - gasto_base) / dia_restante except ZeroDivisionError: self.hoje_limite = 0 self.hoje_resta = self.hoje_limite - self.soma_hoje self.ajuste = (self.dia_limite - self.media_dia) * self.Ontem.day() economia = 0 if self.ajuste >= 0: self.BoxAjuste.setTitle("Acumulado") else: self.BoxAjuste.setTitle("Excesso") if self.dia_limite == 0: economia = -999 else: economia = -self.ajuste / self.dia_limite economia = int(economia) + (economia > 0) print("Semana\n") calendario = calendar.monthcalendar(self.Info.ano_int, self.Info.mes_int) num_semanas = len(calendario) for i in range(0, num_semanas): if self.Info.dia_int in calendario[i]: semana_atual = calendario[i] ultima_semana = calendario[-1] print(semana_atual) semana_fim = QDate(self.Info.ano_int, self.Info.mes_int, max(semana_atual)) if semana_atual[0]: semana_inicio = QDate(self.Info.ano_int, self.Info.mes_int, semana_atual[0]) semana_anterior_fim = QDate(self.Info.ano_int, self.Info.mes_int, semana_atual[0] - 1) soma_anterior = self.Tabela.Saida.soma_intervalo( self.Inicio, semana_anterior_fim) resta = (self.mes_limite - soma_anterior) / (dia_total - semana_anterior_fim.day()) print(resta) count = 0 while semana_atual[count] and count < 6: count += 1 self.semana_limite = resta * (count + 1) else: self.semana_limite = self.dia_limite * sum( 1 for x in calendario[0] if x) semana_inicio = QDate(self.Info.ano_int, self.Info.mes_int, sorted(list(set(semana_atual)))[1]) print(semana_inicio, semana_fim) self.soma_semana = self.Tabela.Saida.soma_intervalo( semana_inicio, semana_fim) self.semana_resta = self.semana_limite - self.soma_semana self.escreve_dinheiro([{ 'valor': self.soma_saida, 'label': self.MesGasto }, { 'valor': self.soma_entrada, 'label': self.TotalEntrada }, { 'valor': self.soma_fixo, 'label': self.TotalFixo }, { 'valor': self.soma_reserva, 'label': self.TotalReserva }, { 'valor': self.soma_hoje, 'label': self.HojeGasto }, { 'valor': self.mes_limite, 'label': self.MesLimite }, { 'valor': self.mes_resta, 'label': self.MesResto }, { 'valor': self.dia_limite, 'label': self.LimiteDia }, { 'valor': self.media_dia, 'label': self.Media }, { 'valor': self.hoje_limite, 'label': self.HojeLimite }, { 'valor': self.hoje_resta, 'label': self.HojeResto }, { 'valor': self.ajuste, 'label': self.Ajuste }, { 'valor': self.soma_semana, 'label': self.SemanaGasto }, { 'valor': self.semana_limite, 'label': self.SemanaLimite }, { 'valor': self.semana_resta, 'label': self.SemanaResto }, { 'valor': self.soma_ajuste, 'label': self.TotalAjuste }]) if economia: if economia > 1: texto = "\n(" + str(economia) + " dias)" else: texto = "\n(" + str(economia) + " dia)" self.Ajuste.setText(self.Ajuste.text() + texto) self.escreve_barra(self.MesBarra, self.soma_saida, self.mes_limite) self.escreve_barra(self.HojeBarra, self.soma_hoje, self.hoje_limite) self.escreve_barra(self.SemanaBarra, self.soma_semana, self.semana_limite) def escreve_dinheiro(self, itens): for item in itens: valor = "R$" + f"{item['valor']:.2f}" valor = valor.replace(".", ",") item['label'].setText(valor) def escreve_barra(self, barra, valor, total): if total == 0: barra.setValue(0) else: if valor > total: barra.setValue(100) else: barra.setValue((valor / total) * 100)