def __init__(self, plugin_action): self.gui = plugin_action.gui self.opts = plugin_action.opts QWidget.__init__(self) self.l = QVBoxLayout() self.setLayout(self.l) # ~~~~~~~~ Create the runtime options group box ~~~~~~~~ self.cfg_runtime_options_gb = QGroupBox(self) self.cfg_runtime_options_gb.setTitle(_('Runtime options')) self.l.addWidget(self.cfg_runtime_options_gb) self.cfg_runtime_options_qvl = QVBoxLayout(self.cfg_runtime_options_gb) # ~~~~~~~~ Disable caching checkbox ~~~~~~~~ self.cfg_disable_caching_checkbox = QCheckBox(_('Disable caching')) self.cfg_disable_caching_checkbox.setObjectName('cfg_disable_caching_checkbox') self.cfg_disable_caching_checkbox.setToolTip(_('Force reload of reader database')) self.cfg_disable_caching_checkbox.setChecked(False) self.cfg_runtime_options_qvl.addWidget(self.cfg_disable_caching_checkbox) # ~~~~~~~~ plugin logging checkbox ~~~~~~~~ self.cfg_plugin_debug_log_checkbox = QCheckBox(_('Enable debug logging for Annotations plugin')) self.cfg_plugin_debug_log_checkbox.setObjectName('cfg_plugin_debug_log_checkbox') self.cfg_plugin_debug_log_checkbox.setToolTip(_('Print plugin diagnostic messages to console')) self.cfg_plugin_debug_log_checkbox.setChecked(False) self.cfg_runtime_options_qvl.addWidget(self.cfg_plugin_debug_log_checkbox) # ~~~~~~~~ libiMobileDevice logging checkbox ~~~~~~~~ self.cfg_libimobiledevice_debug_log_checkbox = QCheckBox(_('Enable debug logging for libiMobileDevice')) self.cfg_libimobiledevice_debug_log_checkbox.setObjectName('cfg_libimobiledevice_debug_log_checkbox') self.cfg_libimobiledevice_debug_log_checkbox.setToolTip(_('Print libiMobileDevice debug messages to console')) self.cfg_libimobiledevice_debug_log_checkbox.setChecked(False) self.cfg_libimobiledevice_debug_log_checkbox.setEnabled(LIBIMOBILEDEVICE_AVAILABLE) self.cfg_runtime_options_qvl.addWidget(self.cfg_libimobiledevice_debug_log_checkbox) # ~~~~~~~~ Create the Annotations options group box ~~~~~~~~ self.cfg_annotation_options_gb = QGroupBox(self) self.cfg_annotation_options_gb.setTitle(_('Annotation options')) self.l.addWidget(self.cfg_annotation_options_gb) self.cfg_annotation_options_qgl = QGridLayout(self.cfg_annotation_options_gb) current_row = 0 # Add the label/combobox for annotations destination self.cfg_annotations_destination_label = QLabel(_('<b>Add fetched annotations to<b>')) self.cfg_annotations_destination_label.setAlignment(Qt.AlignLeft) self.cfg_annotation_options_qgl.addWidget(self.cfg_annotations_destination_label, current_row, 0) current_row += 1 self.cfg_annotations_destination_comboBox = QComboBox(self.cfg_annotation_options_gb) self.cfg_annotations_destination_comboBox.setObjectName('cfg_annotations_destination_comboBox') self.cfg_annotations_destination_comboBox.setToolTip(_('Custom field to store annotations')) self.cfg_annotation_options_qgl.addWidget(self.cfg_annotations_destination_comboBox, current_row, 0) # Populate annotations_field combobox db = self.gui.current_db all_custom_fields = db.custom_field_keys() self.custom_fields = {} for custom_field in all_custom_fields: field_md = db.metadata_for_field(custom_field) if field_md['datatype'] in ['comments']: self.custom_fields[field_md['name']] = {'field': custom_field, 'datatype': field_md['datatype']} all_fields = self.custom_fields.keys() + ['Comments'] for cf in sorted(all_fields): self.cfg_annotations_destination_comboBox.addItem(cf) # Add CC Wizard self.cfg_annotations_wizard = QToolButton() self.cfg_annotations_wizard.setIcon(QIcon(I('wizard.png'))) self.cfg_annotations_wizard.setToolTip(_("Create a custom column to store annotations")) self.cfg_annotations_wizard.clicked.connect(partial(self.launch_cc_wizard, 'Annotations')) self.cfg_annotation_options_qgl.addWidget(self.cfg_annotations_wizard, current_row, 2) current_row += 1 # ~~~~~~~~ Add a horizontal line ~~~~~~~~ self.cfg_appearance_hl = QFrame(self) self.cfg_appearance_hl.setGeometry(QRect(0, 0, 1, 3)) self.cfg_appearance_hl.setFrameShape(QFrame.HLine) self.cfg_appearance_hl.setFrameShadow(QFrame.Raised) self.cfg_annotation_options_qgl.addWidget(self.cfg_appearance_hl, current_row, 0) current_row += 1 # ~~~~~~~~ Add the Modify… button ~~~~~~~~ self.cfg_annotations_appearance_pushbutton = QPushButton(_("Modify appearance…")) self.cfg_annotations_appearance_pushbutton.clicked.connect(self.configure_appearance) self.cfg_annotation_options_qgl.addWidget(self.cfg_annotations_appearance_pushbutton, current_row, 0) current_row += 1 self.spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.cfg_annotation_options_qgl.addItem(self.spacerItem, current_row, 0, 1, 1) # ~~~~~~~~ Compilations group box ~~~~~~~~ self.cfg_compilation_options_gb = QGroupBox(self) self.cfg_compilation_options_gb.setTitle(_('Compilations')) self.l.addWidget(self.cfg_compilation_options_gb) self.cfg_compilation_options_qgl = QGridLayout(self.cfg_compilation_options_gb) current_row = 0 # News clippings self.cfg_news_clippings_checkbox = QCheckBox(_('Collect News clippings')) self.cfg_news_clippings_checkbox.setObjectName('cfg_news_clippings_checkbox') self.cfg_compilation_options_qgl.addWidget(self.cfg_news_clippings_checkbox, current_row, 0) self.cfg_news_clippings_lineEdit = QLineEdit() self.cfg_news_clippings_lineEdit.setObjectName('cfg_news_clippings_lineEdit') self.cfg_news_clippings_lineEdit.setToolTip(_('Title for collected news clippings')) self.cfg_compilation_options_qgl.addWidget(self.cfg_news_clippings_lineEdit, current_row, 1) # ~~~~~~~~ End of construction zone ~~~~~~~~ self.resize(self.sizeHint()) # Restore state of controls, populate annotations combobox self.controls = inventory_controls(self, dump_controls=False) restore_state(self) self.populate_annotations() # Hook changes to annotations_destination_combobox # self.connect(self.cfg_annotations_destination_comboBox, # pyqtSignal('currentIndexChanged(const QString &)'), # self.annotations_destination_changed) self.cfg_annotations_destination_comboBox.currentIndexChanged.connect(self.annotations_destination_changed) # Hook changes to diagnostic checkboxes self.cfg_disable_caching_checkbox.stateChanged.connect(self.restart_required) self.cfg_libimobiledevice_debug_log_checkbox.stateChanged.connect(self.restart_required) self.cfg_plugin_debug_log_checkbox.stateChanged.connect(self.restart_required) # Hook changes to News clippings, initialize self.cfg_news_clippings_checkbox.stateChanged.connect(self.news_clippings_toggled) self.news_clippings_toggled(self.cfg_news_clippings_checkbox.checkState()) self.cfg_news_clippings_lineEdit.editingFinished.connect(self.news_clippings_destination_changed) # Launch the annotated_books_scanner field = get_cc_mapping('annotations', 'field', 'Comments') self.annotated_books_scanner = InventoryAnnotatedBooks(self.gui, field) self.annotated_books_scanner.signal.connect(self.inventory_complete) # self.connect(self.annotated_books_scanner, self.annotated_books_scanner.signal, # self.inventory_complete) QTimer.singleShot(1, self.start_inventory)
def resizeEvent(self, ev): QPlainTextEdit.resizeEvent(self, ev) cr = self.contentsRect() self.line_number_area.setGeometry( QRect(cr.left(), cr.top(), self.line_number_area_width(), cr.height()))
def dump(self, items, out_stream, pdf_metadata): opts = self.opts page_size = get_page_size(self.opts) xdpi, ydpi = self.view.logicalDpiX(), self.view.logicalDpiY() def margin(which): val = getattr(opts, 'pdf_page_margin_' + which) if val == 0.0: val = getattr(opts, 'margin_' + which) return val ml, mr, mt, mb = map(margin, 'left right top bottom'.split()) # We cannot set the side margins in the webview as there is no right # margin for the last page (the margins are implemented with # -webkit-column-gap) self.doc = PdfDevice(out_stream, page_size=page_size, left_margin=ml, top_margin=0, right_margin=mr, bottom_margin=0, xdpi=xdpi, ydpi=ydpi, errors=self.log.error, debug=self.log.debug, compress=not opts.uncompressed_pdf, opts=opts, mark_links=opts.pdf_mark_links, page_margins=(ml, mr, mt, mb)) self.footer = opts.pdf_footer_template if self.footer: self.footer = self.footer.strip() if not self.footer and opts.pdf_page_numbers: self.footer = '<p style="text-align:center; text-indent: 0">_PAGENUM_</p>' self.header = opts.pdf_header_template if self.header: self.header = self.header.strip() min_margin = 1.5 * opts._final_base_font_size if self.footer and mb < min_margin: self.log.warn('Bottom margin is too small for footer, increasing it to %.1fpts' % min_margin) mb = min_margin if self.header and mt < min_margin: self.log.warn('Top margin is too small for header, increasing it to %.1fpts' % min_margin) mt = min_margin self.page.setViewportSize(QSize(self.doc.width(), self.doc.height())) self.render_queue = items self.total_items = len(items) mt, mb = map(self.doc.to_px, (mt, mb)) self.margin_top, self.margin_bottom = map(lambda x:int(floor(x)), (mt, mb)) self.painter = QPainter(self.doc) try: self.book_language = pdf_metadata.mi.languages[0] except Exception: self.book_language = 'eng' self.doc.set_metadata(title=pdf_metadata.title, author=pdf_metadata.author, tags=pdf_metadata.tags, mi=pdf_metadata.mi) self.doc_title = pdf_metadata.title self.doc_author = pdf_metadata.author self.painter.save() try: if self.cover_data is not None: p = QPixmap() try: p.loadFromData(self.cover_data) except TypeError: self.log.warn('This ebook does not have a raster cover, cannot generate cover for PDF' '. Cover type: %s' % type(self.cover_data)) if not p.isNull(): self.doc.init_page() draw_image_page(QRect(*self.doc.full_page_rect), self.painter, p, preserve_aspect_ratio=self.opts.preserve_cover_aspect_ratio) self.doc.end_page() finally: self.painter.restore() QTimer.singleShot(0, self.render_book) if self.loop.exec_() == 1: raise Exception('PDF Output failed, see log for details') if self.toc is not None and len(self.toc) > 0: self.doc.add_outline(self.toc) self.painter.end() if self.doc.errors_occurred: raise Exception('PDF Output failed, see log for details')
def _take_screenshot(self, export_path): frame = state.get('current_slider_value') rect = QRect(0, 0, self._core.width(), self._core.height()) pixmap = self._core.grab(rect) pixmap.save(f'{export_path}/{frame:06d}.png')
def heightForWidth(self, width): return self.do_layout(QRect(0, 0, width, 0), apply_geometry=False)
def paintTab(self, painter, tabIndex): ''' @param: painter QPainter @param: tabIndex int ''' if not self.validIndex(tabIndex): print('Warning: invalid index %s' % tabIndex) return painter.save() rect = self.tabRect(tabIndex) selected = (tabIndex == self._currentIndex) if selected: # background painter.save() grad = QLinearGradient(rect.topLeft(), rect.topRight()) grad.setColorAt(0, QColor(255, 255, 255, 140)) grad.setColorAt(1, QColor(255, 255, 255, 210)) painter.fillRect(rect.adjusted(0, 0, 0, -1), grad) painter.restore() # shadows painter.setPen(QColor(0, 0, 0, 110)) painter.drawLine(rect.topLeft() + QPoint(1, -1), rect.topRight() - QPoint(0, 1)) painter.drawLine(rect.bottomLeft(), rect.bottomRight()) painter.setPen(QColor(0, 0, 0, 40)) painter.drawLine(rect.topLeft(), rect.bottomLeft()) # highlights painter.setPen(QColor(255, 255, 255, 50)) painter.drawLine(rect.topLeft() + QPoint(0, -2), rect.topRight() - QPoint(0, 2)) painter.drawLine(rect.bottomLeft() + QPoint(0, 1), rect.bottomRight() + QPoint(0, 1)) painter.setPen(QColor(255, 255, 255, 40)) painter.drawLine(rect.topLeft() + QPoint(0, 0), rect.topRight()) painter.drawLine(rect.topRight() + QPoint(0, 1), rect.bottomRight() - QPoint(0, 1)) painter.drawLine(rect.bottomLeft() + QPoint(0, -1), rect.bottomRight() - QPoint(0, 1)) # QString tabText(painter->fontMetrics().elidedText(this->tabText(tabIndex), Qt::ElideMiddle, width())); tabTextRect = self.tabRect(tabIndex) tabIconRect = QRect(tabTextRect) tabIconRect.adjust(+4, +4, -4, -4) tabTextRect.translate(0, -2) boldFont = QFont(painter.font()) boldFont.setPointSizeF(styleHelper.sidebarFontSize()) boldFont.setBold(True) painter.setFont(boldFont) painter.setPen(selected and QColor(255, 255, 255, 160) or QColor(0, 0, 0, 110)) # int textFlags = Qt::AlignCenter | Qt::AlignBottom # painter->drawText(tabTextRect, textFlags, tabText) painter.setPen(selected and QColor(60, 60, 60) or styleHelper.panelTextColor()) if not const.OS_MACOS: if not selected: painter.save() fader = int(self._tabs[tabIndex].fader) grad = QLinearGradient(rect.topLeft(), rect.topRight()) grad.setColorAt(0, Qt.transparent) grad.setColorAt(0.5, QColor(255, 255, 255, fader)) grad.setColorAt(1, Qt.transparent) # painter.fillRect(rect, grad) # painter.setPen(QPen(grad, 1.0)) painter.fillRect(rect, QColor(255, 255, 255, fader)) painter.setPen(QPen(QColor(255, 255, 255, fader), 1.0)) painter.drawLine(rect.topLeft(), rect.topRight()) painter.drawLine(rect.bottomLeft(), rect.bottomRight()) painter.restore() # const int textHeight = painter->fontMetrics().height(); tabIconRect.adjust(0, 6, 0, -6) if selected: iconMode = QIcon.Selected else: iconMode = QIcon.Normal styleHelper.drawIconWithShadow(self.tabIcon(tabIndex), tabIconRect, painter, iconMode) painter.translate(0, -1) # painter->drawText(tabTextRect, textFlags, tabText) painter.restore()
def __init__(self, opts): self.matched_ids = set() self.opts = opts self.prefs = opts.prefs super(FindAnnotationsDialog, self).__init__(self.opts.gui, 'find_annotations_dialog') self.setWindowTitle(_('Find Annotations')) self.setWindowIcon(self.opts.icon) self.l = QVBoxLayout(self) self.setLayout(self.l) self.search_criteria_gb = QGroupBox(self) self.search_criteria_gb.setTitle(_("Search criteria")) self.scgl = QGridLayout(self.search_criteria_gb) self.l.addWidget(self.search_criteria_gb) # addWidget(widget, row, col, rowspan, colspan) row = 0 # ~~~~~~~~ Create the Readers comboBox ~~~~~~~~ self.reader_label = QLabel(_('Reader')) self.reader_label.setAlignment(Qt.AlignRight|Qt.AlignVCenter) self.scgl.addWidget(self.reader_label, row, 0, 1, 1) self.find_annotations_reader_comboBox = QComboBox() self.find_annotations_reader_comboBox.setObjectName('find_annotations_reader_comboBox') self.find_annotations_reader_comboBox.setToolTip(_('Reader annotations to search for')) self.find_annotations_reader_comboBox.addItem(self.GENERIC_READER) racs = ReaderApp.get_reader_app_classes() for ra in sorted(racs.keys()): self.find_annotations_reader_comboBox.addItem(ra) self.scgl.addWidget(self.find_annotations_reader_comboBox, row, 1, 1, 4) row += 1 # ~~~~~~~~ Create the Styles comboBox ~~~~~~~~ self.style_label = QLabel(_('Style')) self.style_label.setAlignment(Qt.AlignRight|Qt.AlignVCenter) self.scgl.addWidget(self.style_label, row, 0, 1, 1) self.find_annotations_color_comboBox = QComboBox() self.find_annotations_color_comboBox.setObjectName('find_annotations_color_comboBox') self.find_annotations_color_comboBox.setToolTip(_('Annotation style to search for')) self.find_annotations_color_comboBox.addItem(self.GENERIC_STYLE) all_colors = COLOR_MAP.keys() all_colors.remove('Default') for color in sorted(all_colors): self.find_annotations_color_comboBox.addItem(color) self.scgl.addWidget(self.find_annotations_color_comboBox, row, 1, 1, 4) row += 1 # ~~~~~~~~ Create the Text LineEdit control ~~~~~~~~ self.text_label = QLabel(_('Text')) self.text_label.setAlignment(Qt.AlignRight|Qt.AlignVCenter) self.scgl.addWidget(self.text_label, row, 0, 1, 1) self.find_annotations_text_lineEdit = MyLineEdit() self.find_annotations_text_lineEdit.setObjectName('find_annotations_text_lineEdit') self.scgl.addWidget(self.find_annotations_text_lineEdit, row, 1, 1, 3) self.reset_text_tb = QToolButton() self.reset_text_tb.setObjectName('reset_text_tb') self.reset_text_tb.setToolTip(_('Clear search criteria')) self.reset_text_tb.setIcon(QIcon(I('trash.png'))) self.reset_text_tb.clicked.connect(self.clear_text_field) self.scgl.addWidget(self.reset_text_tb, row, 4, 1, 1) row += 1 # ~~~~~~~~ Create the Note LineEdit control ~~~~~~~~ self.note_label = QLabel(_('Note')) self.note_label.setAlignment(Qt.AlignRight|Qt.AlignVCenter) self.scgl.addWidget(self.note_label, row, 0, 1, 1) self.find_annotations_note_lineEdit = MyLineEdit() self.find_annotations_note_lineEdit.setObjectName('find_annotations_note_lineEdit') self.scgl.addWidget(self.find_annotations_note_lineEdit, row, 1, 1, 3) self.reset_note_tb = QToolButton() self.reset_note_tb.setObjectName('reset_note_tb') self.reset_note_tb.setToolTip(_('Clear search criteria')) self.reset_note_tb.setIcon(QIcon(I('trash.png'))) self.reset_note_tb.clicked.connect(self.clear_note_field) self.scgl.addWidget(self.reset_note_tb, row, 4, 1, 1) row += 1 # ~~~~~~~~ Create the Date range controls ~~~~~~~~ self.date_range_label = QLabel(_('Date range')) self.date_range_label.setAlignment(Qt.AlignRight|Qt.AlignVCenter) self.scgl.addWidget(self.date_range_label, row, 0, 1, 1) # Date 'From' self.find_annotations_date_from_dateEdit = MyDateEdit(self, datetime(1970,1,1)) self.find_annotations_date_from_dateEdit.setObjectName('find_annotations_date_from_dateEdit') #self.find_annotations_date_from_dateEdit.current_val = datetime(1970,1,1) self.find_annotations_date_from_dateEdit.clear_button.clicked.connect(self.find_annotations_date_from_dateEdit.reset_from_date) self.scgl.addWidget(self.find_annotations_date_from_dateEdit, row, 1, 1, 1) self.scgl.addWidget(self.find_annotations_date_from_dateEdit.clear_button, row, 2, 1, 1) # Date 'To' self.find_annotations_date_to_dateEdit = MyDateEdit(self, datetime.today()) self.find_annotations_date_to_dateEdit.setObjectName('find_annotations_date_to_dateEdit') #self.find_annotations_date_to_dateEdit.current_val = datetime.today() self.find_annotations_date_to_dateEdit.clear_button.clicked.connect(self.find_annotations_date_to_dateEdit.reset_to_date) self.scgl.addWidget(self.find_annotations_date_to_dateEdit, row, 3, 1, 1) self.scgl.addWidget(self.find_annotations_date_to_dateEdit.clear_button, row, 4, 1, 1) row += 1 # ~~~~~~~~ Create a horizontal line ~~~~~~~~ self.hl = QFrame(self) self.hl.setGeometry(QRect(0, 0, 1, 3)) self.hl.setFrameShape(QFrame.HLine) self.hl.setFrameShadow(QFrame.Raised) self.scgl.addWidget(self.hl, row, 0, 1, 5) row += 1 # ~~~~~~~~ Create the results label field ~~~~~~~~ self.result_label = QLabel('<p style="color:red">{0}</p>'.format(_('scanning…'))) self.result_label.setAlignment(Qt.AlignCenter) self.result_label.setWordWrap(False) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Maximum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.result_label.sizePolicy().hasHeightForWidth()) self.result_label.setSizePolicy(sizePolicy) self.result_label.setMinimumSize(QtCore.QSize(250, 0)) self.scgl.addWidget(self.result_label, row, 0, 1, 5) row += 1 # ~~~~~~~~ Create the ButtonBox ~~~~~~~~ self.dialogButtonBox = QDialogButtonBox(self) self.dialogButtonBox.setOrientation(Qt.Horizontal) if False: self.update_button = QPushButton(_('Update results')) self.update_button.setDefault(True) self.update_button.setVisible(False) self.dialogButtonBox.addButton(self.update_button, QDialogButtonBox.ActionRole) self.cancel_button = self.dialogButtonBox.addButton(self.dialogButtonBox.Cancel) self.find_button = self.dialogButtonBox.addButton(self.dialogButtonBox.Ok) self.find_button.setText(_('Find Matching Books')) self.l.addWidget(self.dialogButtonBox) self.dialogButtonBox.clicked.connect(self.find_annotations_dialog_clicked) # ~~~~~~~~ Add a spacer ~~~~~~~~ self.spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.l.addItem(self.spacerItem) # ~~~~~~~~ Restore previously saved settings ~~~~~~~~ self.restore_settings() # ~~~~~~~~ Declare sizing ~~~~~~~~ sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth()) self.setSizePolicy(sizePolicy) self.resize_dialog() # ~~~~~~~~ Connect all signals ~~~~~~~~ self.find_annotations_reader_comboBox.currentIndexChanged.connect(partial(self.update_results, 'reader')) self.find_annotations_color_comboBox.currentIndexChanged.connect(partial(self.update_results, 'color')) self.find_annotations_text_lineEdit.editingFinished.connect(partial(self.update_results, 'text')) self.find_annotations_note_lineEdit.editingFinished.connect(partial(self.update_results, 'note')) # self.connect(self.find_annotations_text_lineEdit, pyqtSignal("return_pressed"), self.return_pressed) self.find_annotations_text_lineEdit.return_pressed.connect(self.return_pressed) # self.connect(self.find_annotations_note_lineEdit, pyqtSignal("return_pressed"), self.return_pressed) self.find_annotations_note_lineEdit.return_pressed.connect(self.return_pressed) # Date range signals connected in inventory_available() # ~~~~~~~~ Allow dialog to render before doing inventory ~~~~~~~~ #field = self.prefs.get('cfg_annotations_destination_field', None) field = get_cc_mapping('annotations', 'field', None) self.annotated_books_scanner = InventoryAnnotatedBooks(self.opts.gui, field, get_date_range=True) self.annotated_books_scanner.signal.connect(self.inventory_available) QTimer.singleShot(1, self.start_inventory_scan)
def paintEvent(self, event): ''' @param: event QPaintEvent ''' p = QPainter(self) # Just draw separator if self._bookmark.isSeparator(): opt = QStyleOption() opt.initFrom(self) opt.state |= QStyle.State_Horizontal self.style().drawPrimitive(QStyle.PE_IndicatorToolBarSeparator, opt, p) return option = QStyleOptionButton() self.initStyleOption(option) # We are manually drawing the arrow option.features &= ~QStyleOptionButton.HasMenu # Draw button base (only under mouse, this is autoraise button) if self.isDown() or self.hitButton(self.mapFromGlobal(QCursor.pos())): option.state |= QStyle.State_AutoRaise | QStyle.State_Raised self.style().drawPrimitive(QStyle.PE_PanelButtonTool, option, p, self) if self.isDown(): shiftX = self.style().pixelMetric(QStyle.PM_ButtonShiftHorizontal, option, self) shiftY = self.style().pixelMetric(QStyle.PM_ButtonShiftVertical, option, self) else: shiftX = 0 shiftY = 0 height = option.rect.height() center = height / 2 + option.rect.top() + shiftY iconSize = 16 iconYPos = center - iconSize / 2 leftPosition = self.PADDING + shiftX rightPosition = option.rect.right() - self.PADDING # Draw icon if not self._showOnlyText: iconRect = QRect(leftPosition, iconYPos, iconSize, iconSize) p.drawPixmap( QStyle.visualRect(option.direction, option.rect, iconRect), self._bookmark.icon().pixmap(iconSize)) leftPosition = iconRect.right() + self.PADDING # Draw menu arrow if not self._showOnlyIcon and self.menu(): arrowSize = 8 opt = QStyleOption() opt.initFrom(self) rect = QRect(rightPosition - 8, center - arrowSize / 2, arrowSize, arrowSize) opt.rect = QStyle.visualRect(option.direction, option.rect, rect) opt.state &= ~QStyle.State_MouseOver self.style().drawPrimitive(QStyle.PE_IndicatorArrowDown, opt, p, self) rightPosition = rect.left() - self.PADDING # Draw text if not self._showOnlyIcon: textWidth = rightPosition - leftPosition textYPos = center - self.fontMetrics().height() / 2 txt = self.fontMetrics().elidedText(self._bookmark.title(), Qt.ElideRight, textWidth) textRect = QRect(leftPosition, textYPos, textWidth, self.fontMetrics().height()) self.style().drawItemText( p, QStyle.visualRect(option.direction, option.rect, textRect), Qt.TextSingleLine | Qt.AlignCenter, option.palette, True, txt)
def paintEvent(self, event): """ overload of paintEvent Qt function. Draw every stacked images with their proprieties (i.e.: opacity). Stack still has the same size after operation. Image are scaled during the process. QLabel's size is equals to maximum width & height found while reading images. Arguments: ev {QPaintEvent} -- A paint event which trigger display. """ if not self.images: return # new label size area_w = 0 area_h = 0 # Zoom zoom = self.zoom() # Init QPainter. painter = QPainter(self) # Draw every stacked images. # From the bottom of the stack to the top. for i in range(0, len(self.images)): # Opacity painter.setOpacity(self.opacities[i]) # Scale and Draw image = self.images[i] _w = image.width() * zoom _h = image.height() * zoom if _w > area_w: area_w = _w if _h > area_h: area_h = _h painter.drawImage( self.xx[i] * zoom, self.yy[i] * zoom, image.scaled( _w, _h, Qt.KeepAspectRatio, Qt.SmoothTransformation ) ) if self.draw_rect is True: painter.setPen(QPen(self.rect_color)) painter.drawRect(QRect(self.l_pos, self.r_pos)) self.setFixedSize(area_w, area_h)
def paint(self, painter, option, index): QStyledItemDelegate.paint(self, painter, option, index) hovering = index.data(HOVER_ROLE) is True painter.save() rect = option.rect is_current = index.data(Qt.FontRole) is not None if not hovering and is_current: qpp = QPainterPath() qpp.addRoundedRect(QRectF(rect), 6, 6) painter.fillPath(qpp, self.current_background) icon_rect = QRect(rect.left() + self.MARGIN, rect.top() + self.MARGIN, ICON_SIZE, ICON_SIZE) left = icon_rect.right() + 2 * self.MARGIN text_rect = QRect(left, icon_rect.top(), rect.width() - left + rect.left(), icon_rect.height()) mark = index.data(MARK_ROLE) if hovering or mark: text_rect.adjust(0, 0, -text_rect.height(), 0) text = index.data(DISPLAY_ROLE) or '' font = index.data(Qt.FontRole) if font: painter.setFont(font) text_flags = Qt.AlignVCenter | Qt.AlignLeft | Qt.TextSingleLine text = elided_text(text, font, text_rect.width(), 'right') if option.state & QStyle.State_Selected: painter.setPen(QPen(self.highlighted_text)) painter.drawText(text_rect, text_flags, text) if mark: hrect = QRect(text_rect.right(), text_rect.top(), text_rect.height(), text_rect.height()) painter.fillRect(hrect, QColor('#ffffaa')) painter.drawText(hrect, Qt.AlignCenter, mark) elif hovering: hrect = QRect(text_rect.right(), text_rect.top(), text_rect.height(), text_rect.height()) close_hover = index.data(CLOSE_HOVER_ROLE) is True if close_hover: pen = painter.pen() pen.setColor(QColor('red')) painter.setPen(pen) painter.drawText(hrect, Qt.AlignCenter, '✖ ') if index.data(LOADING_ROLE): if not self.errored_out: angle = index.data(ANGLE_ROLE) try: draw_snake_spinner(painter, icon_rect, angle, self.light, self.dark) except Exception: import traceback traceback.print_exc() self.errored_out = True else: icurl = index.data(URL_ROLE) if icurl == WELCOME_URL: icon = welcome_icon() elif icurl == DOWNLOADS_URL: icon = downloads_icon() else: icon = index.data(DECORATION_ROLE) icon.paint(painter, icon_rect) painter.restore()
def drawIconWithShadow(self, icon, rect, painter, iconMode, radius=3, color=QColor(0, 0, 0, 130), offset=QPoint(1, -2)): ''' @brief: Draw a cached pixmap with shadow @param: icon QIcon @param: rect QRect @param: painter QPainter @param: iconMode QIcon.Mode @param: radius int @param: color QColor @param: offset QPoint ''' cache = QPixmap() pixmapName = 'icon %s %s %s' % (icon.cacheKey(), iconMode, rect.height()) cache = QPixmapCache.find(pixmapName) if not cache: px = icon.pixmap(rect.size(), iconMode) px.setDevicePixelRatio(gVar.app.devicePixelRatio()) cache = QPixmap(px.size() + QSize(radius * 2, radius * 2)) cache.setDevicePixelRatio(px.devicePixelRatioF()) cache.fill(Qt.transparent) cachePainter = QPainter(cache) # Draw shadow tmp = QImage(px.size() + QSize(radius * 2, radius * 2 + 1), QImage.Format_ARGB32_Premultiplied) tmp.setDevicePixelRatio(px.devicePixelRatioF()) tmp.fill(Qt.transparent) tmpPainter = QPainter(tmp) tmpPainter.setCompositionMode(QPainter.CompositionMode_Source) tmpPainter.drawPixmap(QPoint(radius, radius), px) tmpPainter.end() # blur the alpha channel blurred = QImage(tmp.size(), QImage.Format_ARGB32_Premultiplied) blurred.fill(Qt.transparent) blurPainter = QPainter(blurred) # TODO: #qt_blurImage(blurPainter, tmp, radius, False, True) blurPainter.end() tmp = blurred # blacken the image... tmpPainter.begin(tmp) tmpPainter.setCompositionMode(QPainter.CompositionMode_SourceIn) tmpPainter.fillRect(tmp.rect(), color) tmpPainter.end() tmpPainter.begin(tmp) tmpPainter.setCompositionMode(QPainter.CompositionMode_SourceIn) tmpPainter.fillRect(tmp.rect(), color) tmpPainter.end() # draw the blurred drop shadow... cachePainter.drawImage( QRect(0, 0, cache.rect().width() / cache.devicePixelRatioF(), cache.rect().height() / cache.devicePixelRatioF()), tmp) # Draw the actual pixmap... cachePainter.drawPixmap(QPoint(radius, radius) + offset, px) if self.usePixmapCache(): QPixmapCache.insert(pixmapName, cache) sip.delete(cachePainter) sip.delete(tmpPainter) sip.delete(blurPainter) targetRect = QRect(cache.rect()) targetRect.setWidth(cache.rect().width() / cache.devicePixelRatioF()) targetRect.setHeight(cache.rect().height() / cache.devicePixelRatioF()) targetRect.moveCenter(rect.center()) painter.drawPixmap(targetRect.topLeft() - offset, cache)
def add_roca(self, position): y, x = position rect = QRect(1 + SIZE_TILE * x, 1 + SIZE_TILE * y, SIZE_TILE, SIZE_TILE) self.columns[y][x] = (rect, 'roca')
def mouseMoveInLabel(self, event): if not self.pt1.isNull(): pt = self.img_lbl.mapTo(self,event.pos()) self.rubberBand.setGeometry(QRect(self.pt1_rect, pt).normalized())
def _setupUi(self): settings = Settings() settings.beginGroup('Browser-View-Settings') windowGeometry = settings.value('WindowGeometry', b'') keys = [ ('LocationBarWidth', int), ('WebSearchBarWidth', int), ('SideBarWidth', int), ('WebViewWidth', int), ('SideBar', str), ] uiState = {} for key, typ in keys: if settings.contains(key): uiState[key] = typ(settings.value(key)) settings.endGroup() widget = QWidget(self) widget.setCursor(Qt.ArrowCursor) self.setCentralWidget(widget) self._mainLayout = QVBoxLayout(widget) self._mainLayout.setContentsMargins(0, 0, 0, 0) self._mainLayout.setSpacing(0) self._mainSplitter = QSplitter(self) self._mainSplitter.setObjectName('sidebar-splitter') self._tabWidget = TabWidget(self) self._superMenu = QMenu(self) self._navigationToolbar = NavigationBar(self) self._bookmarksToolbar = BookmarksToolbar(self) self._tabModel = TabModel(self, self) self._tabMruModel = TabMruModel(self, self) self._tabMruModel.setSourceModel(self._tabModel) self._navigationContainer = NavigationContainer(self) self._navigationContainer.addWidget(self._navigationToolbar) self._navigationContainer.addWidget(self._bookmarksToolbar) self._navigationContainer.setTabBar(self._tabWidget.tabBar()) self._mainSplitter.addWidget(self._tabWidget) self._mainSplitter.setCollapsible(0, False) self._mainLayout.addWidget(self._navigationContainer) self._mainLayout.addWidget(self._mainSplitter) self._statusBar = StatusBar(self) self._statusBar.setObjectName('mainwindow-statusbar') self._statusBar.setCursor(Qt.ArrowCursor) self.setStatusBar(self._statusBar) self._progressBar = ProgressBar(self._statusBar) self._ipLabel = QLabel(self) self._ipLabel.setObjectName('statusbar-ip-label') self._ipLabel.setToolTip('IP Address of current page') self._statusBar.addPermanentWidget(self._progressBar) self._statusBar.addPermanentWidget(self.ipLabel()) downloadsButton = DownloadsButton(self) self._statusBar.addButton(downloadsButton) self._navigationToolbar.addToolButton(downloadsButton) desktop = gVar.app.desktop() windowWidth = desktop.availableGeometry().width() / 1.3 windowHeight = desktop.availableGeometry().height() / 1.3 # Let the WM decides where to put new browser window if self._windowType not in (const.BW_FirstAppWindow, const.BW_MacFirstWindow) and \ gVar.app.getWindow(): if const.OS_WIN: # Windows WM places every new window in the middle of screen .. for some reason p = gVar.app.getWindow().geometry().topLeft() p.setX(p.x() + 30) p.setY(p.y() + 30) if not desktop.availableGeometry( gVar.app.getWindow()).contains(p): p.setX( desktop.availableGeometry(gVar.app.getWindow()).x() + 30) p.setY( desktop.availableGeometry(gVar.app.getWindow()).y() + 30) self.setGeometry(QRect(p, gVar.app.getWindow().size())) else: self.resize(gVar.app.getWindow().size()) elif not self.restoreGeometry(windowGeometry): if const.OS_WIN: self.setGeometry( QRect( desktop.availableGeometry(gVar.app.getWindow()).x() + 30, desktop.availableGeometry(gVar.app.getWindow()).y() + 30, windowWidth, windowHeight)) else: self.resize(windowWidth, windowHeight) self._restoreUiState(uiState) # Set some sane minimum width self.setMinimumWidth(300)
def __init__(self, parent, old, new): super(QDialog, self).__init__(parent.gui) self.db = parent.gui.current_db self.gui = parent.gui self._log_location() layout = QVBoxLayout() self.setLayout(layout) header = QLabel(_("Move annotations or change destination?")) header.setAlignment(Qt.AlignCenter) header_font = QFont() header_font.setPointSize(16) header.setFont(header_font) layout.addWidget(header) change_group = QGroupBox("", self) layout.addWidget(change_group) self.gl = QGridLayout() change_group.setLayout(self.gl) horizontal_line = QFrame(self) horizontal_line.setGeometry(QRect(0, 0, 1, 3)) horizontal_line.setFrameShape(QFrame.HLine) horizontal_line.setFrameShadow(QFrame.Raised) self.gl.addWidget(horizontal_line, 1, 0, 1, 2) self.move_button = QPushButton(_("Move")) self.gl.addWidget(self.move_button, 3, 0, 1, 1) self.move_label = QLabel( _('<html><head/><body><p>• Move existing annotations from <span style=" font-weight:600;">{old}</span> to <span style=" font-weight:600;">{new}</span>.<br/>• Existing annotations will be removed from <span style=" font-weight:600;">{old}</span>.<br/>• Newly imported annotations will be added to <span style=" font-weight:600;">{new}</span>.</p></body></html>' )) self.move_label.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) self.gl.addWidget(self.move_label, 3, 1) self.gl.addWidget(horizontal_line, 4, 1) self.change_button = QPushButton(_("Change")) self.gl.addWidget(self.change_button, 5, 0, 1, 1) self.change_label = QLabel( _('<html><head/><body><p>• Change annotations storage from <span style=" font-weight:600;">{old}</span> to <span style=" font-weight:600;">{new}</span>.<br/>• Existing annotations will remain in <span style=" font-weight:600;">{old}</span>.<br/>• Newly imported annotations will be added to <span style=" font-weight:600;">{new}</span>.</p></body></html>' )) self.change_label.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) self.gl.addWidget(self.change_label, 5, 1, 1, 1) self.bb = QDialogButtonBox(QDialogButtonBox.Cancel) layout.addWidget(self.bb) # Hook the button events self.bb.clicked.connect(partial(self.button_clicked, 'cancel')) self.move_button.clicked.connect(partial(self.button_clicked, 'move')) self.change_button.clicked.connect( partial(self.button_clicked, 'change')) # Customize the dialog text self.move_label.setText( str(self.move_label.text()).format(old=old, new=new)) self.change_label.setText( str(self.change_label.text()).format(old=old, new=new)) self.command = 'cancel' self.do_resize()
def save(self, filename: str, do_crop: bool=False): """Save a RenderIrea as one image on disk. Arguments: filename {str} -- The filename of the new image. """ if not self.images: return # new label size dst_w = 0 dst_h = 0 # Zoom zoom = self.zoom() # Current number of images into the stack. nbimg = len(self.images) # Find the current size of the output image. images = [] for i in range(0, nbimg): image = self.images[i] _w = image.width() * zoom _h = image.height() * zoom if _w > dst_w: dst_w = _w if _h > dst_h: dst_h = _h # Scale now images.append( image.scaled( _w, _h, Qt.KeepAspectRatio, Qt.SmoothTransformation )) # Output image # ARGB since we can have all types of images (colors/grayscale/alpha channel) dst = QImage(dst_w, dst_h, QImage.Format_ARGB32) dst.fill(0) # black pixels everywhere # Init QPainter. painter = QPainter() painter.begin(dst) # Begin to draw inside the `dst` Image # Draw every stacked images. # From the bottom of the stack to the top. for i in range(0, nbimg): # Opacity painter.setOpacity(self.opacities[i]) painter.drawImage( self.xx[i] * zoom, self.yy[i] * zoom, images[i] ) painter.end() # Crop or not to crop? if do_crop and self.draw_rect: rect = QRect(self.l_pos, self.r_pos) dst = dst.copy(rect) # Save image, max quality dst.save(filename, None, 100)
def resizeEvent(self, event): super().resizeEvent(event) cr = self.contentsRect() self.line_number_area.setGeometry(QRect(cr.left(), cr.top(), self.lineNumberAreaWidth(), cr.height()))
@pytest.fixture def init_paths(scope="module"): importExportUtils.DEFAULT_CONFIG_PATH = join(dirname(abspath(__file__)), "config_test.cfg") importExportUtils.ALERT_DB_PATH = join(dirname(abspath(__file__)), "alertsDB_test.json") sound_path = join(dirname(dirname(abspath(__file__))), 'resources', 'sounds', 'floop.wav') im_path = join(dirname(dirname(abspath(__file__))), 'resources', 'images', 'notification_clock.png') notification = Notification("Test", "000000", "Times", 12, sound_path) rect = QRect(0, 0, 1024, 768) # A QApplication is needed to create widgets app = QApplication([]) @pytest.mark.test def test_constructor(init_paths): """Test :class:~_clockalarm.UI.NotificationWidget constructor.""" global notification global rect nw = NotificationWidget(rect, notification) assert nw.notification.message == "Test" assert nw.height() == rect.height()
def drawControl(self, element, option, painter, widget): ''' @param: element ControlElement @param: option QStyleOption @param: painter QPainter @param: widget QWidget ''' v_opt = option if element != self.CE_TabBarTab or not isinstance( v_opt, QStyleOptionTab): QProxyStyle.drawControl(element, option, painter, widget) return rect = v_opt.rect selected = v_opt.state & self.State_Selected vertical_tabs = v_opt.shape == QTabBar.RoundedWest text = v_opt.text if selected: # background painter.save() grad = QLinearGradient(rect.topLeft(), rect.topRight()) grad.setColorAt(0, QColor(255, 255, 255, 140)) grad.setColorAt(0, QColor(255, 255, 255, 210)) painter.fillRect(rect.adjusted(0, 0, 0, -1), grad) painter.restore() # shadows painter.setPen(QColor(0, 0, 0, 110)) painter.drawLine(rect.topLeft() + QPoint(1, -1), rect.topRight() - QPoint(0, 1)) painter.drawLine(rect.bottomLeft(), rect.bottomRight()) painter.setPen(QColor(0, 0, 0, 40)) painter.drawLine(rect.topLeft(), rect.bottomLeft()) # highlights painter.setPen(QColor(255, 255, 255, 50)) painter.drawLine(rect.topLeft() + QPoint(0, -2), rect.topRight() - QPoint(0, 2)) painter.drawLine(rect.bottomLeft() + QPoint(0, 1), rect.bottomRight() + QPoint(0, 1)) painter.setPen(QColor(255, 255, 255, 40)) painter.drawLine(rect.topLeft() + QPoint(0, 0), rect.topRight()) painter.drawLine(rect.topRight() + QPoint(0, 1), rect.bottomRight() - QPoint(0, 1)) painter.drawLine(rect.bottomLeft() + QPoint(0, -1), rect.bottomRight() - QPoint(0, 1)) m = QTransform() if vertical_tabs: m = QTransform.fromTranslate(rect.left(), rect.bottom()) m.rotate(-90) else: m = QTransform.fromTranslate(rect.left(), rect.top()) draw_rect = QRect(QPoint(0, 0), m.mapRect(rect).size()) painter.save() painter.setTransform(m) icon_rect = QRect(QPoint(8, 0), v_opt.iconSize) text_rect = QRect(icon_rect.topRight() + QPoint(4, 0), draw_rect.size()) text_rect.setRight(draw_rect.width()) icon_rect.translate(0, (draw_rect.height() - icon_rect.height()) / 2) boldFont = QFont(painter.font()) boldFont.setPointSizeF(styleHelper.sidebarFontSize()) boldFont.setBold(True) painter.setFont(boldFont) painter.setPen(selected and QColor(255, 255, 255, 160) or QColor(0, 0, 0, 110)) textFlags = Qt.AlignHCenter | Qt.AlignVCenter painter.drawText(text_rect, textFlags, text) painter.setPen(selected and QColor(60, 60, 60) or styleHelper.panelTextColor()) if widget: fader_key = 'tab_' + text + '_fader' animation_key = 'tab_' + text + '_animation' tab_hover = widget.property('tab_hover') # int fader = widget.property(fader_key) # QPropertyAnimation animation = widget.property(animation_key) if not animation: mut_widget = widget fader = 0 mut_widget.setProperty(fader_key, fader) animation = QPropertyAnimation(mut_widget, fader_key, mut_widget) animation.valueChanged.connect(mut_widget.update) mut_widget.setProperty(animation_key, animation) if text == tab_hover: if animation.state( ) != QAbstractAnimation.Running and fader != 40: animation.stop() animation.setDuration(80) animation.setEndValue(40) animation.start() else: if animation.state( ) != QAbstractAnimation.Running and fader != 0: animation.stop() animation.setDuration(160) animation.setEndValue(0) animation.start() if not selected: painter.save() painter.fillRect(draw_rect, QColor(255, 255, 255, fader)) painter.setPen(QPen(QColor(255, 255, 255, fader), 1.0)) painter.drawLine( draw_rect.topLeft(), vertical_tabs and draw_rect.bottomLeft() or draw_rect.topRight()) painter.drawLine( draw_rect.bottomRight(), vertical_tabs and draw_rect.topRight() or draw_rect.bottomLeft()) painter.restore() if selected: iconMode = QIcon.Selected else: iconMode = QIcon.Normal styleHelper.drawIconWithShadow(v_opt.icon, icon_rect, painter, iconMode) painter.drawText(text_rect.translated(0, -1), textFlags, text) painter.restore()
def is_in_paint_box(self, pos): return QPolygon(QRect(220, 10, 600, 620)).containsPoint(pos, QtCore.Qt.OddEvenFill)
def paintEvent(self, event): w = self.viewport().rect().width() painter = QPainter(self.viewport()) painter.setClipRect(event.rect()) painter.setRenderHint(QPainter.SmoothPixmapTransform, True) floor = event.rect().bottom() ceiling = event.rect().top() fv = self.firstVisibleBlock().blockNumber() origin = self.contentOffset() doc = self.document() lines = [] for num, text in self.headers: top, bot = num, num + 3 if bot < fv: continue y_top = self.blockBoundingGeometry( doc.findBlockByNumber(top)).translated(origin).y() y_bot = self.blockBoundingGeometry( doc.findBlockByNumber(bot)).translated(origin).y() if max(y_top, y_bot) < ceiling: continue if min(y_top, y_bot) > floor: break painter.setFont(self.heading_font) br = painter.drawText(3, y_top, w, y_bot - y_top - 5, Qt.TextSingleLine, text) painter.setPen(QPen(self.palette().text(), 2)) painter.drawLine(0, br.bottom() + 3, w, br.bottom() + 3) for top, bot, kind in self.changes: if bot < fv: continue y_top = self.blockBoundingGeometry( doc.findBlockByNumber(top)).translated(origin).y() y_bot = self.blockBoundingGeometry( doc.findBlockByNumber(bot)).translated(origin).y() if max(y_top, y_bot) < ceiling: continue if min(y_top, y_bot) > floor: break if y_top != y_bot: painter.fillRect(0, y_top, w, y_bot - y_top, self.diff_backgrounds[kind]) lines.append((y_top, y_bot, kind)) if top in self.images: img, maxw = self.images[top][:2] if bot > top + 1 and not img.isNull(): y_top = self.blockBoundingGeometry( doc.findBlockByNumber(top + 1)).translated(origin).y() + 3 y_bot -= 3 scaled, imgw, imgh = fit_image( int(img.width() / img.devicePixelRatio()), int(img.height() / img.devicePixelRatio()), w - 3, y_bot - y_top) painter.drawPixmap(QRect(3, y_top, imgw, imgh), img) painter.end() PlainTextEdit.paintEvent(self, event) painter = QPainter(self.viewport()) painter.setClipRect(event.rect()) for top, bottom, kind in sorted( lines, key=lambda t_b_k: {'replace': 0}.get(t_b_k[2], 1)): painter.setPen(QPen(self.diff_foregrounds[kind], 1)) painter.drawLine(0, top, w, top) painter.drawLine(0, bottom - 1, w, bottom - 1)
def draw_char(pos, pen_color): pix_paint.setPen(QPen(pen_color)) rect = QRect(i * w + i, 1, w, h) pix_paint.drawRect(rect) pix_paint.fillRect(rect, pen_color)
def setupUi(self): self.setObjectName("Dialog") self.resize(1024, 700) self.setWindowIcon(QIcon(I('convert.png'))) self.gridLayout = QGridLayout(self) self.gridLayout.setObjectName("gridLayout") self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.input_label = QLabel(self) self.input_label.setObjectName("input_label") self.horizontalLayout.addWidget(self.input_label) self.input_formats = QComboBox(self) self.input_formats.setSizeAdjustPolicy( QComboBox.AdjustToMinimumContentsLengthWithIcon) self.input_formats.setMinimumContentsLength(5) self.input_formats.setObjectName("input_formats") self.horizontalLayout.addWidget(self.input_formats) self.opt_individual_saved_settings = QCheckBox(self) self.opt_individual_saved_settings.setObjectName( "opt_individual_saved_settings") self.horizontalLayout.addWidget(self.opt_individual_saved_settings) spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem) self.label_2 = QLabel(self) self.label_2.setObjectName("label_2") self.horizontalLayout.addWidget(self.label_2) self.output_formats = QComboBox(self) self.output_formats.setSizeAdjustPolicy( QComboBox.AdjustToMinimumContentsLengthWithIcon) self.output_formats.setMinimumContentsLength(5) self.output_formats.setObjectName("output_formats") self.horizontalLayout.addWidget(self.output_formats) self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 2) self.groups = QListView(self) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(1) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.groups.sizePolicy().hasHeightForWidth()) self.groups.setSizePolicy(sizePolicy) self.groups.setTabKeyNavigation(True) self.groups.setIconSize(QSize(48, 48)) self.groups.setWordWrap(True) self.groups.setObjectName("groups") self.gridLayout.addWidget(self.groups, 1, 0, 3, 1) self.scrollArea = QScrollArea(self) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(4) sizePolicy.setVerticalStretch(10) sizePolicy.setHeightForWidth( self.scrollArea.sizePolicy().hasHeightForWidth()) self.scrollArea.setSizePolicy(sizePolicy) self.scrollArea.setFrameShape(QFrame.NoFrame) self.scrollArea.setLineWidth(0) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName("scrollArea") self.scrollAreaWidgetContents = QWidget() self.scrollAreaWidgetContents.setGeometry(QRect(0, 0, 810, 494)) self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents") self.verticalLayout_3 = QVBoxLayout(self.scrollAreaWidgetContents) self.verticalLayout_3.setContentsMargins(0, 0, 0, 0) self.verticalLayout_3.setObjectName("verticalLayout_3") self.stack = QStackedWidget(self.scrollAreaWidgetContents) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.stack.sizePolicy().hasHeightForWidth()) self.stack.setSizePolicy(sizePolicy) self.stack.setObjectName("stack") self.page = QWidget() self.page.setObjectName("page") self.stack.addWidget(self.page) self.page_2 = QWidget() self.page_2.setObjectName("page_2") self.stack.addWidget(self.page_2) self.verticalLayout_3.addWidget(self.stack) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.gridLayout.addWidget(self.scrollArea, 1, 1, 1, 1) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok | QDialogButtonBox.RestoreDefaults) self.buttonBox.setObjectName("buttonBox") self.gridLayout.addWidget(self.buttonBox, 3, 1, 1, 1) self.help = QTextEdit(self) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.help.sizePolicy().hasHeightForWidth()) self.help.setSizePolicy(sizePolicy) self.help.setMaximumSize(QSize(16777215, 130)) self.help.setObjectName("help") self.gridLayout.addWidget(self.help, 2, 1, 1, 1) self.input_label.setBuddy(self.input_formats) self.label_2.setBuddy(self.output_formats) self.input_label.setText(_("&Input format:")) self.opt_individual_saved_settings.setText( _("Use &saved conversion settings for individual books")) self.label_2.setText(_("&Output format:")) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject)
def __init__(self): super().__init__() self.flag_wb = True # 전역변수 self.flag_ing = True self.setupUi(self) self.pb_reset.clicked.connect(self.pbBtnClick) self.arr2D = [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ] self.arr_seq = [{ 'i': 0, 'j': 0 }, { 'i': 0, 'j': 1 }, { 'i': 0, 'j': 2 }, { 'i': 0, 'j': 3 }, { 'i': 0, 'j': 4 }] self.arr_idx = 0 self.pb2D = [] for i in range(20): pb_line = [] for j in range(20): tmp = QPushButton(self) tmp.setToolTip(str(i) + "," + str(j)) tmp.setIconSize(QSize(40, 40)) tmp.setGeometry(QRect(j * 40, i * 40, 40, 40)) tmp.setIcon(QtGui.QIcon("0.jpg")) tmp.clicked.connect(self.btnClick) pb_line.append(tmp) self.pb2D.append(pb_line) self.myrender()
def rect_at(self, frac): return QRect(self.point_at(frac), self.size())
def on_printAction3_triggered(self): printer = QPrinter() image = QPixmap() image.load("0.png") font = QFont() font.setBold(True) font.setPixelSize(50) textsize = QSize() # textsize.setHeight() pen = QPen() pen.setColor(Qt.black) pagesize = QSizeF() print(image.width()) print(image.height()) pagesize.setWidth(60) pagesize.setHeight(40) printer.setPaperSize(pagesize, QPrinter.Millimeter) print(printer.pageSize()) printDialog = QPrintDialog(printer, self) printDialog.setWindowTitle("打印二维码") if printDialog.exec_() == QDialog.Accepted: painter = QPainter(printer) painter.setPen(pen) painter.setFont(font) painter.begin(printer) picsize = image.size() size = QSize() # size.setHeight(picsize.height()) # size.setWidth(picsize.width()) # size.setWidth(60) # size.setHeight(40) # # # # image = image.scaled(size, Qt.KeepAspectRatio) rectdest = QRect() rectdest.setX(25) rectdest.setY(0) rectdest.setWidth(175) rectdest.setHeight(150) print(image.rect()) # rectsrc = QRect() # image.rect() # rectsrc.setX(0) # rectsrc.setY(0) # rectsrc.setX(image.width()) # rectsrc.setY(image.height()) painter.drawPixmap(rectdest, image, image.rect()) # rect.setX(10 + picsize.width()/10) # rect.setY(12 + picsize.height()/2.5) # painter.drawText(50, 120, "10001491274") # preview = QPrintPreviewDialog() # preview.paintRequested(printer) # preview.exec() painter.end()
def paint(self, painter, option, index): QStyledItemDelegate.paint( self, painter, option, empty_index) # draw the hover and selection highlights m = index.model() db = m.db try: book_id = db.id(index.row()) except (ValueError, IndexError, KeyError): return if book_id in m.ids_to_highlight_set: painter.save() try: painter.setPen(self.highlight_color) painter.setRenderHint(QPainter.Antialiasing, True) painter.drawRoundedRect(option.rect, 10, 10, Qt.RelativeSize) finally: painter.restore() marked = db.data.get_marked(book_id) db = db.new_api cdata = self.cover_cache[book_id] device_connected = self.parent().gui.device_connected is not None on_device = device_connected and db.field_for('ondevice', book_id) emblem_rules = db.pref('cover_grid_icon_rules', default=()) emblems = [] if self.emblem_size > 0: mi = None for i, (kind, column, rule) in enumerate(emblem_rules): icon_name, mi = self.render_emblem(book_id, rule, i, m.cover_grid_emblem_cache, mi, db, m.formatter, m.cover_grid_template_cache) if icon_name is not None: pixmap = self.cached_emblem(m.cover_grid_bitmap_cache, icon_name) if pixmap is not None: emblems.append(pixmap) if marked: emblems.insert( 0, self.cached_emblem(m.cover_grid_bitmap_cache, ':marked', m.marked_icon)) if on_device: emblems.insert( 0, self.cached_emblem(m.cover_grid_bitmap_cache, ':ondevice')) painter.save() right_adjust = 0 try: rect = option.rect rect.adjust(self.MARGIN, self.MARGIN, -self.MARGIN, -self.MARGIN) if self.emblem_size > 0: self.paint_emblems(painter, rect, emblems) orect = QRect(rect) if cdata is None or cdata is False: title = db.field_for('title', book_id, default_value='') authors = ' & '.join( db.field_for('authors', book_id, default_value=())) painter.setRenderHint(QPainter.TextAntialiasing, True) painter.drawText(rect, Qt.AlignCenter | Qt.TextWordWrap, '%s\n\n%s' % (title, authors)) if cdata is False: self.render_queue.put(book_id) else: if self.title_height != 0: trect = QRect(rect) rect.setBottom(rect.bottom() - self.title_height) if self.animating is not None and self.animating.row( ) == index.row(): cdata = cdata.scaled(cdata.size() * self._animated_size) dpr = cdata.devicePixelRatio() cw, ch = int(cdata.width() / dpr), int(cdata.height() / dpr) dx = max(0, int((rect.width() - cw) / 2.0)) dy = max(0, rect.height() - ch) right_adjust = dx rect.adjust(dx, dy, -dx, 0) painter.drawPixmap(rect, cdata) if self.title_height != 0: rect = trect rect.setTop(rect.bottom() - self.title_height + 5) painter.setRenderHint(QPainter.TextAntialiasing, True) title, is_stars = self.render_field(db, book_id) if is_stars: painter.setFont(self.rating_font) metrics = painter.fontMetrics() painter.setPen(self.highlight_color) painter.drawText( rect, Qt.AlignCenter | Qt.TextSingleLine, metrics.elidedText(title, Qt.ElideRight, rect.width())) if self.emblem_size > 0: return # We dont draw embossed emblems as the ondevice/marked emblems are drawn in the gutter if marked: try: p = self.marked_emblem except AttributeError: p = self.marked_emblem = m.marked_icon.pixmap(48, 48) self.paint_embossed_emblem(p, painter, orect, right_adjust) if on_device: try: p = self.on_device_emblem except AttributeError: p = self.on_device_emblem = QIcon(I('ok.png')).pixmap( 48, 48) self.paint_embossed_emblem(p, painter, orect, right_adjust, left=False) finally: painter.restore()
def geometry(self): return QRect()
def decoration_for_style(palette, style, icon_size, device_pixel_ratio, is_dark): style_key = (is_dark, icon_size, device_pixel_ratio, tuple((k, style[k]) for k in sorted(style))) sentinel = object() ans = decoration_cache.get(style_key, sentinel) if ans is not sentinel: return ans ans = None kind = style.get('kind') if kind == 'color': key = 'dark' if is_dark else 'light' val = style.get(key) if val is None: which = style.get('which') val = (builtin_colors_dark if is_dark else builtin_colors_light).get(which) if val is None: val = style.get('background-color') if val is not None: ans = QColor(val) elif kind == 'decoration': which = style.get('which') if which is not None: q = builtin_decorations.get(which) if q is not None: style = q sz = int(math.ceil(icon_size * device_pixel_ratio)) canvas = QImage(sz, sz, QImage.Format.Format_ARGB32) canvas.fill(Qt.GlobalColor.transparent) canvas.setDevicePixelRatio(device_pixel_ratio) p = QPainter(canvas) p.setRenderHint(QPainter.RenderHint.Antialiasing, True) p.setPen(palette.color(QPalette.ColorRole.WindowText)) irect = QRect(0, 0, icon_size, icon_size) adjust = -2 text_rect = p.drawText( irect.adjusted(0, adjust, 0, adjust), Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop, 'a') p.drawRect(irect) fm = p.fontMetrics() pen = p.pen() if 'text-decoration-color' in style: pen.setColor(QColor(style['text-decoration-color'])) lstyle = style.get('text-decoration-style') or 'solid' q = { 'dotted': Qt.PenStyle.DotLine, 'dashed': Qt.PenStyle.DashLine, }.get(lstyle) if q is not None: pen.setStyle(q) lw = fm.lineWidth() if lstyle == 'double': lw * 2 pen.setWidth(fm.lineWidth()) q = style.get('text-decoration-line') or 'underline' pos = text_rect.bottom() height = irect.bottom() - pos if q == 'overline': pos = height elif q == 'line-through': pos = text_rect.center().y() - adjust - lw // 2 p.setPen(pen) if lstyle == 'wavy': p.drawPath(wavy_path(icon_size, height, pos)) else: p.drawLine(0, pos, irect.right(), pos) p.end() ans = QPixmap.fromImage(canvas) elif 'background-color' in style: ans = QColor(style['background-color']) decoration_cache[style_key] = ans return ans
def resizeEvent(self, event): QPlainTextEdit.resizeEvent(self, event) contents_rect = self.contentsRect() self._line_number_area.setGeometry(QRect(contents_rect.left(), contents_rect.top(), self.lineNumberAreaWidth(), contents_rect.height()))