def files_dropped_on_book(self, event, paths, cid=None): accept = False if self.gui.current_view() is not self.gui.library_view: return db = self.gui.library_view.model().db cover_changed = False current_idx = self.gui.library_view.currentIndex() if cid is None: if not current_idx.isValid(): return cid = db.id(current_idx.row()) if cid is None else cid for path in paths: ext = os.path.splitext(path)[1].lower() if ext: ext = ext[1:] if ext in IMAGE_EXTENSIONS: pmap = QPixmap() pmap.load(path) if not pmap.isNull(): accept = True db.set_cover(cid, pmap) cover_changed = True elif ext in BOOK_EXTENSIONS: db.add_format_with_hooks(cid, ext, path, index_is_id=True) accept = True if accept and event is not None: event.accept() if current_idx.isValid(): self.gui.library_view.model().current_changed(current_idx, current_idx) if cover_changed: if self.gui.cover_flow: self.gui.cover_flow.dataChanged()
def initialize_metadata_options(self): self.initialize_combos() self.author.editTextChanged.connect(self.deduce_author_sort) mi = self.db.get_metadata(self.book_id, index_is_id=True) self.title.setText(mi.title) self.publisher.show_initial_value(mi.publisher if mi.publisher else '') self.author_sort.setText(mi.author_sort if mi.author_sort else '') self.tags.setText(', '.join(mi.tags if mi.tags else [])) self.tags.update_items_cache(self.db.all_tags()) self.comment.html = comments_to_html(mi.comments) if mi.comments else '' self.series.show_initial_value(mi.series if mi.series else '') if mi.series_index is not None: try: self.series_index.setValue(mi.series_index) except: self.series_index.setValue(1.0) cover = self.db.cover(self.book_id, index_is_id=True) if cover: pm = QPixmap() pm.loadFromData(cover) if not pm.isNull(): self.cover.setPixmap(pm) self.cover_data = cover self.set_cover_tooltip(pm) else: self.cover.setPixmap(QPixmap(I('default_cover.png'))) self.cover.setToolTip(_('This book has no cover')) for x in ('author', 'series', 'publisher'): x = getattr(self, x) x.lineEdit().deselect()
def __init__(self, parent=None): QWidget.__init__(self, parent) self._pixmap = QPixmap(self) self.setMinimumSize(QSize(150, 200)) ImageDropMixin.__init__(self) self.draw_border = True self.show_size = False
def data(self, index, role): target = self.targets[index.row()] if index.isValid() and (0 <= index.row() < len(self.targets)) and target: column = index.column() if role == Qt.DecorationRole: if column == 1: picturePath = os.path.join(os.getcwdu(), 'temp', target['targetPicture']) if picturePath and os.path.exists(picturePath): pixmap = QPixmap(picturePath) return QIcon(pixmap.scaled(30, 30, Qt.IgnoreAspectRatio, Qt.FastTransformation)) else: pixmap = QPixmap(os.path.join(os.getcwdu(), 'include', 'generic_user.png')) pixmap.scaled(20, 20, Qt.IgnoreAspectRatio) return QIcon(pixmap) if role == Qt.DisplayRole: if column == 0: return QVariant(target['pluginName']) elif column == 1: return QVariant() elif column == 2: return QVariant(target['targetUsername']) elif column == 3: return QVariant(target['targetFullname']) elif column == 4: return QVariant(target['targetUserid']) else: return QVariant()
def get_icons(zfp, name_or_list_of_names): ''' Load icons from the plugin zip file :param name_or_list_of_names: List of paths to resources in the zip file using / as separator, or a single path :return: A dictionary of the form ``{name : QIcon}``. Any names that were not found in the zip file will be null QIcons. If a single path is passed in the return value will be A QIcon. ''' from PyQt4.Qt import QIcon, QPixmap names = name_or_list_of_names ans = get_resources(zfp, names) if isinstance(names, basestring): names = [names] if ans is None: ans = {} if isinstance(ans, basestring): ans = dict([(names[0], ans)]) ians = {} for name in names: p = QPixmap() raw = ans.get(name, None) if raw: p.loadFromData(raw) ians[name] = QIcon(p) if len(names) == 1: ians = ians.pop(names[0]) return ians
def _addToTab(self, submission, submissionURL, lst): """ Add a submission and its representative image to the lst under its tab. :type submission: praw.objects.Submission :type submissionURL: str :type lst: QListWidget """ imagePath = submission.representativeImage if imagePath is not None and imagePath.exists(): item = QListWidgetItem(submissionURL, lst) item.setTextColor(Qt.transparent) labelWidget = QLabel() labelWidget.setOpenExternalLinks(True) labelWidget.setTextFormat(Qt.RichText) size = QSize(128, 158) item.setSizeHint(size) size = QSize(128, 128) if imagePath.suffix == ".webm": imagePath = pathlib.Path("RedditDataExtractor", "images", "videoImage.png").resolve() pixmap = QPixmap(str(imagePath)) pixmap = pixmap.scaled(size, Qt.KeepAspectRatio) height = pixmap.height() width = pixmap.width() submissionTitle = submissionURL[submissionURL[0:-1].rfind("/") + 1:-1] labelWidget.setText( '<a href="' + submissionURL + '"><img src="' + str(imagePath) + '" height="' + str( height) + '" width="' + str(width) + '"><p>' + submissionTitle) lst.setItemWidget(item, labelWidget)
def __init__(self, parent): QWizard.__init__(self, parent) self.setWindowTitle(__appname__+' '+_('welcome wizard')) p = QPixmap() p.loadFromData(open(P('content_server/calibre.png'), 'rb').read()) self.setPixmap(self.LogoPixmap, p.scaledToHeight(80, Qt.SmoothTransformation)) self.setPixmap(self.WatermarkPixmap, QPixmap(I('welcome_wizard.png'))) self.setPixmap(self.BackgroundPixmap, QPixmap(I('wizard.png'))) self.device_page = DevicePage() self.library_page = LibraryPage() self.library_page.retranslate.connect(self.retranslate) self.finish_page = FinishPage() self.set_finish_text() self.kindle_page = KindlePage() self.stanza_page = StanzaPage() self.setPage(self.library_page.ID, self.library_page) self.setPage(self.device_page.ID, self.device_page) self.setPage(self.finish_page.ID, self.finish_page) self.setPage(self.kindle_page.ID, self.kindle_page) self.setPage(self.stanza_page.ID, self.stanza_page) self.device_extra_page = None nh, nw = min_available_height()-75, available_width()-30 if nh < 0: nh = 580 if nw < 0: nw = 400 nh = min(400, nh) nw = min(580, nw) self.resize(nw, nh) self.set_button_texts()
def __init__(self, cover_thread_count=2, detail_thread_count=4): QAbstractItemModel.__init__(self) self.DRM_LOCKED_ICON = QPixmap(I('drm-locked.png')).scaledToHeight( 64, Qt.SmoothTransformation) self.DRM_UNLOCKED_ICON = QPixmap(I('drm-unlocked.png')).scaledToHeight( 64, Qt.SmoothTransformation) self.DRM_UNKNOWN_ICON = QPixmap( I('dialog_question.png')).scaledToHeight(64, Qt.SmoothTransformation) self.DONATE_ICON = QPixmap(I('donate.png')).scaledToHeight( 16, Qt.SmoothTransformation) self.DOWNLOAD_ICON = QPixmap(I('arrow-down.png')).scaledToHeight( 16, Qt.SmoothTransformation) # All matches. Used to determine the order to display # self.matches because the SearchFilter returns # matches unordered. self.all_matches = [] # Only the showing matches. self.matches = [] self.query = '' self.filterable_query = False self.search_filter = SearchFilter() self.cover_pool = CoverThreadPool(cover_thread_count) self.details_pool = DetailsThreadPool(detail_thread_count) self.filter_results_dispatcher = FunctionDispatcher( self.filter_results) self.got_result_details_dispatcher = FunctionDispatcher( self.got_result_details) self.sort_col = 2 self.sort_order = Qt.AscendingOrder
def render_emblems(item, emblems): emblems = tuple(emblems) if not emblems: return icon = self.rendered_emblem_cache.get(emblems, None) if icon is None: pixmaps = [] for emblem in emblems: pm = self.emblem_cache.get(emblem, None) if pm is None: pm = self.emblem_cache[emblem] = QPixmap( I(emblem)).scaled(self.iconSize(), transformMode=Qt.SmoothTransformation) pixmaps.append(pm) num = len(pixmaps) w, h = pixmaps[0].width(), pixmaps[0].height() if num == 1: icon = self.rendered_emblem_cache[emblems] = QIcon(pixmaps[0]) else: canvas = QPixmap((num * w) + ((num-1)*2), h) canvas.fill(Qt.transparent) painter = QPainter(canvas) for i, pm in enumerate(pixmaps): painter.drawPixmap(i * (w + 2), 0, pm) painter.end() icon = self.rendered_emblem_cache[emblems] = canvas item.setData(0, Qt.DecorationRole, icon)
def toggleCursor(self): if self.cursor().shape() == QCursor(Qt.ArrowCursor).shape(): raw = QPixmap(":/gui/pics/pardusman-icon.png") raw.setMask(raw.mask()) self.setCursor(QCursor(raw, 2, 2)) else: self.unsetCursor()
def render_emblems(item, emblems): emblems = tuple(emblems) if not emblems: return icon = self.rendered_emblem_cache.get(emblems, None) if icon is None: pixmaps = [] for emblem in emblems: pm = self.emblem_cache.get(emblem, None) if pm is None: pm = self.emblem_cache[emblem] = QPixmap( I(emblem)).scaled( self.iconSize(), transformMode=Qt.SmoothTransformation) pixmaps.append(pm) num = len(pixmaps) w, h = pixmaps[0].width(), pixmaps[0].height() if num == 1: icon = self.rendered_emblem_cache[emblems] = QIcon( pixmaps[0]) else: canvas = QPixmap((num * w) + ((num - 1) * 2), h) canvas.fill(Qt.transparent) painter = QPainter(canvas) for i, pm in enumerate(pixmaps): painter.drawPixmap(i * (w + 2), 0, pm) painter.end() icon = self.rendered_emblem_cache[emblems] = canvas item.setData(0, Qt.DecorationRole, icon)
def _exportImageToPNG(self, filename=None): if not filename: if not self._export_png_dialog: dialog = self._export_png_dialog = QFileDialog(self, "Export image to PNG", ".", "*.png") dialog.setDefaultSuffix("png") dialog.setFileMode(QFileDialog.AnyFile) dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.setModal(True) QObject.connect(dialog, SIGNAL("filesSelected(const QStringList &)"), self._exportImageToPNG) return self._export_png_dialog.exec_() == QDialog.Accepted busy = BusyIndicator() if isinstance(filename, QStringList): filename = filename[0] filename = str(filename) # make QPixmap nx, ny = self.image.imageDims() (l0, l1), (m0, m1) = self.image.getExtents() pixmap = QPixmap(nx, ny) painter = QPainter(pixmap) # use QwtPlot implementation of draw canvas, since we want to avoid caching xmap = QwtScaleMap() xmap.setPaintInterval(0, nx) xmap.setScaleInterval(l1, l0) ymap = QwtScaleMap() ymap.setPaintInterval(ny, 0) ymap.setScaleInterval(m0, m1) self.image.draw(painter, xmap, ymap, pixmap.rect()) painter.end() # save to file try: pixmap.save(filename, "PNG") except Exception as exc: self.emit(SIGNAL("showErrorMessage"), "Error writing %s: %s" % (filename, str(exc))) return self.emit(SIGNAL("showMessage"), "Exported image to file %s" % filename)
def _addToTab(self, submission, submissionURL, lst): """ Add a submission and its representative image to the lst under its tab. :type submission: praw.objects.Submission :type submissionURL: str :type lst: QListWidget """ imagePath = submission.representativeImage if imagePath is not None and imagePath.exists(): item = QListWidgetItem(submissionURL, lst) item.setTextColor(Qt.transparent) labelWidget = QLabel() labelWidget.setOpenExternalLinks(True) labelWidget.setTextFormat(Qt.RichText) size = QSize(128, 158) item.setSizeHint(size) size = QSize(128, 128) if imagePath.suffix == ".webm": imagePath = pathlib.Path("RedditDataExtractor", "images", "videoImage.png").resolve() pixmap = QPixmap(str(imagePath)) pixmap = pixmap.scaled(size, Qt.KeepAspectRatio) height = pixmap.height() width = pixmap.width() submissionTitle = submissionURL[submissionURL[0:-1].rfind("/") + 1:-1] labelWidget.setText('<a href="' + submissionURL + '"><img src="' + str(imagePath) + '" height="' + str(height) + '" width="' + str(width) + '"><p>' + submissionTitle) lst.setItemWidget(item, labelWidget)
def files_dropped_on_book(self, event, paths, cid=None): accept = False if self.gui.current_view() is not self.gui.library_view: return db = self.gui.library_view.model().db cover_changed = False current_idx = self.gui.library_view.currentIndex() if cid is None: if not current_idx.isValid(): return cid = db.id(current_idx.row()) if cid is None else cid for path in paths: ext = os.path.splitext(path)[1].lower() if ext: ext = ext[1:] if ext in IMAGE_EXTENSIONS: pmap = QPixmap() pmap.load(path) if not pmap.isNull(): accept = True db.set_cover(cid, pmap) cover_changed = True elif ext in BOOK_EXTENSIONS: db.add_format_with_hooks(cid, ext, path, index_is_id=True) accept = True if accept and event is not None: event.accept() if current_idx.isValid(): self.gui.library_view.model().current_changed( current_idx, current_idx) if cover_changed: if self.gui.cover_flow: self.gui.cover_flow.dataChanged()
def select_cover(self): files = choose_images(self, 'change cover dialog', _('Choose cover for ') + unicode(self.title.text())) if not files: return _file = files[0] if _file: _file = os.path.abspath(_file) if not os.access(_file, os.R_OK): d = error_dialog(self.parent(), _('Cannot read'), _('You do not have permission to read the file: ') + _file) d.exec_() return cf, cover = None, None try: cf = open(_file, "rb") cover = cf.read() except IOError as e: d = error_dialog(self.parent(), _('Error reading file'), _("<p>There was an error reading from file: <br /><b>") + _file + "</b></p><br />"+str(e)) d.exec_() if cover: pix = QPixmap() pix.loadFromData(cover) if pix.isNull(): d = error_dialog(self.parent(), _('Error reading file'), _file + _(" is not a valid picture")) d.exec_() else: self.cover_path.setText(_file) self.set_cover_tooltip(pix) self.cover.setPixmap(pix) self.cover_changed = True self.cpixmap = pix self.cover_data = cover
def update(self, message, type=None, spinner=False): fontMetric = self.label.fontMetrics() textWidth = fontMetric.width(message) if type: self.icon.show() if type == "error": self.icon.setPixmap(QPixmap(":/gui/pics/dialog-error.png")) self.setStyleSheet( " QFrame#frame {background-color: rgba(255,0,0,100);} ") elif type == "warning": self.icon.setPixmap(QPixmap(":/gui/pics/dialog-warning.png")) self.setStyleSheet( " QFrame#frame {background-color: rgba(0,0,0,100);} ") self.setFixedWidth(textWidth + self.icon.width() + 50) self.label.setText(message) else: self.icon.hide() self.setStyleSheet( " QFrame#frame {background-color: rgba(0,0,0,100);} ") self.setFixedWidth(textWidth + self.icon.width() + 100) self.label.setText(message) self.spinner.setVisible(spinner) self.move(ctx.mainScreen.width() / 2 - self.width() / 2, ctx.mainScreen.height() - self.height() / 2 - 50) self.show()
def dnd_get_image(md, image_exts=IMAGE_EXTENSIONS): ''' Get the image in the QMimeData object md. :return: None, None if no image is found QPixmap, None if an image is found, the pixmap is guaranteed not null url, filename if a URL that points to an image is found ''' if dnd_has_image(md): for x in md.formats(): x = unicode(x) if x.startswith('image/'): cdata = bytes(md.data(x)) pmap = QPixmap() pmap.loadFromData(cdata) if not pmap.isNull(): return pmap, None break # No image, look for a URL pointing to an image if md.hasUrls(): urls = [unicode(u.toString()) for u in md.urls()] purls = [urlparse(u) for u in urls] # First look for a local file images = [u2p(xu) for xu in purls if xu.scheme in ('', 'file')] images = [ xi for xi in images if posixpath.splitext(urllib.unquote(xi))[1] [1:].lower() in image_exts ] images = [xi for xi in images if os.path.exists(xi)] p = QPixmap() for path in images: try: with open(path, 'rb') as f: p.loadFromData(f.read()) except: continue if not p.isNull(): return p, None # No local images, look for remote ones # First, see if this is from Firefox rurl, fname = get_firefox_rurl(md, image_exts) if rurl and fname: return rurl, fname # Look through all remaining URLs remote_urls = [ xu for xu in purls if xu.scheme in ('http', 'https', 'ftp') and posixpath.splitext(xu.path)[1][1:].lower() in image_exts ] if remote_urls: rurl = remote_urls[0] fname = posixpath.basename(urllib.unquote(rurl.path)) return urlunparse(rurl), fname return None, None
def show_splash_screen(self): self.splash_pixmap = QPixmap() self.splash_pixmap.load(I('library.png')) self.splash_screen = QSplashScreen(self.splash_pixmap) self.splash_screen.showMessage( _('Starting %s: Loading books...') % __appname__) self.splash_screen.show() QApplication.instance().processEvents()
def updateCustomColorItemIcon(self, qcolor): """ Update the custom color item icon in the background color combobox with I{qcolor}. """ pixmap = QPixmap(16, 16) pixmap.fill(qcolor) self.backgroundColorComboBox.setItemIcon(bg_CUSTOM, QIcon(pixmap)) return
def __init__(self, current_cover, parent=None): QAbstractListModel.__init__(self, parent) if current_cover is None: current_cover = QPixmap(I('default_cover.png')) self.blank = QPixmap(I('blank.png')).scaled(150, 200) self.cc = current_cover self.reset_covers(do_reset=False)
def data(self, index, role): row, col = index.row(), index.column() if row >= len(self.matches): return NONE result = self.matches[row] if role == Qt.DisplayRole: if col == 1: t = result.title if result.title else _('Unknown') a = result.author if result.author else '' return QVariant('<b>%s</b><br><i>%s</i>' % (t, a)) elif col == 2: return QVariant(result.price) elif col == 4: return QVariant('%s<br>%s' % (result.store_name, result.formats)) return NONE elif role == Qt.DecorationRole: if col == 0 and result.cover_data: p = QPixmap() p.loadFromData(result.cover_data) return QVariant(p) if col == 3: if result.drm == SearchResult.DRM_LOCKED: return QVariant(self.DRM_LOCKED_ICON) elif result.drm == SearchResult.DRM_UNLOCKED: return QVariant(self.DRM_UNLOCKED_ICON) elif result.drm == SearchResult.DRM_UNKNOWN: return QVariant(self.DRM_UNKNOWN_ICON) if col == 5: if result.downloads: return QVariant(self.DOWNLOAD_ICON) if col == 6: if result.affiliate: return QVariant(self.DONATE_ICON) elif role == Qt.ToolTipRole: if col == 1: return QVariant('<p>%s</p>' % result.title) elif col == 2: return QVariant('<p>' + _('Detected price as: %s. Check with the store before making a purchase to verify this price is correct. This price often does not include promotions the store may be running.') % result.price + '</p>') # noqa elif col == 3: if result.drm == SearchResult.DRM_LOCKED: return QVariant('<p>' + _('This book as been detected as having DRM restrictions. This book may not work with your reader and you will have limitations placed upon you as to what you can do with this book. Check with the store before making any purchases to ensure you can actually read this book.') + '</p>') # noqa elif result.drm == SearchResult.DRM_UNLOCKED: return QVariant('<p>' + _('This book has been detected as being DRM Free. You should be able to use this book on any device provided it is in a format calibre supports for conversion. However, before making a purchase double check the DRM status with the store. The store may not be disclosing the use of DRM.') + '</p>') # noqa else: return QVariant('<p>' + _('The DRM status of this book could not be determined. There is a very high likelihood that this book is actually DRM restricted.') + '</p>') # noqa elif col == 4: return QVariant('<p>%s</p>' % result.formats) elif col == 5: if result.downloads: return QVariant('<p>' + _('The following formats can be downloaded directly: %s.') % ', '.join(result.downloads.keys()) + '</p>') elif col == 6: if result.affiliate: return QVariant('<p>' + _('Buying from this store supports the calibre developer: %s.') % result.plugin_author + '</p>') elif role == Qt.SizeHintRole: return QSize(64, 64) return NONE
def data(self, index, role): row, col = index.row(), index.column() if row >= len(self.matches): return NONE result = self.matches[row] if role == Qt.DisplayRole: if col == 1: t = result.title if result.title else _('Unknown') a = result.author if result.author else '' return QVariant('<b>%s</b><br><i>%s</i>' % (t, a)) elif col == 2: return QVariant(result.price) elif col == 4: return QVariant('%s<br>%s' % (result.store_name, result.formats)) return NONE elif role == Qt.DecorationRole: if col == 0 and result.cover_data: p = QPixmap() p.loadFromData(result.cover_data) return QVariant(p) if col == 3: if result.drm == SearchResult.DRM_LOCKED: return QVariant(self.DRM_LOCKED_ICON) elif result.drm == SearchResult.DRM_UNLOCKED: return QVariant(self.DRM_UNLOCKED_ICON) elif result.drm == SearchResult.DRM_UNKNOWN: return QVariant(self.DRM_UNKNOWN_ICON) if col == 5: if result.downloads: return QVariant(self.DOWNLOAD_ICON) if col == 6: if result.affiliate: return QVariant(self.DONATE_ICON) elif role == Qt.ToolTipRole: if col == 1: return QVariant('<p>%s</p>' % result.title) elif col == 2: return QVariant('<p>' + _('Detected price as: %s. Check with the store before making a purchase to verify this price is correct. This price often does not include promotions the store may be running.') % result.price + '</p>') elif col == 3: if result.drm == SearchResult.DRM_LOCKED: return QVariant('<p>' + _('This book as been detected as having DRM restrictions. This book may not work with your reader and you will have limitations placed upon you as to what you can do with this book. Check with the store before making any purchases to ensure you can actually read this book.') + '</p>') elif result.drm == SearchResult.DRM_UNLOCKED: return QVariant('<p>' + _('This book has been detected as being DRM Free. You should be able to use this book on any device provided it is in a format calibre supports for conversion. However, before making a purchase double check the DRM status with the store. The store may not be disclosing the use of DRM.') + '</p>') else: return QVariant('<p>' + _('The DRM status of this book could not be determined. There is a very high likelihood that this book is actually DRM restricted.') + '</p>') elif col == 4: return QVariant('<p>%s</p>' % result.formats) elif col == 5: if result.downloads: return QVariant('<p>' + _('The following formats can be downloaded directly: %s.') % ', '.join(result.downloads.keys()) + '</p>') elif col == 6: if result.affiliate: return QVariant('<p>' + _('Buying from this store supports the calibre developer: %s.') % result.plugin_author + '</p>') elif role == Qt.SizeHintRole: return QSize(64, 64) return NONE
def __init__(self, parent=None, show_size_pref_name=None, default_show_size=False): QWidget.__init__(self, parent) self.show_size_pref_name = ('show_size_on_cover_' + show_size_pref_name) if show_size_pref_name else None self._pixmap = QPixmap(self) self.setMinimumSize(QSize(150, 200)) ImageDropMixin.__init__(self) self.draw_border = True self.show_size = False if self.show_size_pref_name: self.show_size = gprefs.get(self.show_size_pref_name, default_show_size)
def get_pixmap(icon_name): ''' Retrieve a QPixmap for the named image Any icons belonging to the plugin must be prefixed with 'images/' ''' global plugin_icon_resources, plugin_name if not icon_name.startswith('images/'): # We know this is definitely not an icon belonging to this plugin pixmap = QPixmap() pixmap.load(I(icon_name)) return pixmap # Check to see whether the icon exists as a Calibre resource # This will enable skinning if the user stores icons within a folder like: # ...\AppData\Roaming\calibre\resources\images\Plugin Name\ if plugin_name: local_images_dir = get_local_images_dir(plugin_name) local_image_path = os.path.join(local_images_dir, icon_name.replace('images/', '')) if os.path.exists(local_image_path): pixmap = QPixmap() pixmap.load(local_image_path) return pixmap # As we did not find an icon elsewhere, look within our zip resources if icon_name in plugin_icon_resources: pixmap = QPixmap() pixmap.loadFromData(plugin_icon_resources[icon_name]) return pixmap return None
def add_tab(self, name, widget, removeable = True): if name is None: name = widget.get_name() if widget is None: raise ProjectTabManagerException("Error Widget is None!") pm = QPixmap(QSize(16, 16)) pm.fill() icon = QIcon(pm) self.tab_view.addTab(widget, icon, name) self.tabs.append([name, widget])
def pixmap_from_color_and_size(color, size): """ #doc; size can be int or (int,int) """ if type(size) == type(1): size = size, size w,h = size qcolor = qcolor_from_anything(color) from PyQt4.Qt import QPixmap qp = QPixmap(w,h) qp.fill(qcolor) return qp
def pixmap_from_color_and_size(color, size): """ #doc; size can be int or (int,int) """ if type(size) == type(1): size = size, size w, h = size qcolor = qcolor_from_anything(color) from PyQt4.Qt import QPixmap qp = QPixmap(w, h) qp.fill(qcolor) return qp
def __init__(self, parent, collection, item): QWidget.__init__(self, parent) self.setupUi(self) self.parent = parent self.item = item self.collection = collection self.header.setText(collection.title) self.description.setText(collection.description) icon = QPixmap(":/gui/pics/%s" % collection.icon) if icon.isNull(): icon = QPixmap(":/gui/pics/systemsettings.png") self.icon.setPixmap(icon)
class ImageView(QWidget, ImageDropMixin): # {{{ BORDER_WIDTH = 1 cover_changed = pyqtSignal(object) def __init__(self, parent=None): QWidget.__init__(self, parent) self._pixmap = QPixmap(self) self.setMinimumSize(QSize(150, 200)) ImageDropMixin.__init__(self) self.draw_border = True def setPixmap(self, pixmap): if not isinstance(pixmap, QPixmap): raise TypeError('Must use a QPixmap') self._pixmap = pixmap self.updateGeometry() self.update() def pixmap(self): return self._pixmap def sizeHint(self): if self._pixmap.isNull(): return self.minimumSize() return self._pixmap.size() def paintEvent(self, event): QWidget.paintEvent(self, event) pmap = self._pixmap if pmap.isNull(): return w, h = pmap.width(), pmap.height() cw, ch = self.rect().width(), self.rect().height() scaled, nw, nh = fit_image(w, h, cw, ch) if scaled: pmap = pmap.scaled(nw, nh, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) w, h = pmap.width(), pmap.height() x = int(abs(cw - w) / 2.) y = int(abs(ch - h) / 2.) target = QRect(x, y, w, h) p = QPainter(self) p.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform) p.drawPixmap(target, pmap) pen = QPen() pen.setWidth(self.BORDER_WIDTH) p.setPen(pen) if self.draw_border: p.drawRect(target) #p.drawRect(self.rect()) p.end()
def addsomething(self, what): if what == "Chunk": icon = QPixmap('../images/moldefault.png') icon_h = QPixmap('../images/moldefault-hide.png') else: icon = QPixmap('../images/measuredistance.png') icon_h = QPixmap('../images/measuredistance-hide.png') chunk = TestNode("%s-%d" % (what, self.chunkNum), self.treemodel.untitledNode, icon, icon_h) self.chunkNum += 1 self.view.mt_update()
class ImageView(QWidget, ImageDropMixin): # {{{ BORDER_WIDTH = 1 cover_changed = pyqtSignal(object) def __init__(self, parent=None): QWidget.__init__(self, parent) self._pixmap = QPixmap(self) self.setMinimumSize(QSize(150, 200)) ImageDropMixin.__init__(self) self.draw_border = True def setPixmap(self, pixmap): if not isinstance(pixmap, QPixmap): raise TypeError('Must use a QPixmap') self._pixmap = pixmap self.updateGeometry() self.update() def pixmap(self): return self._pixmap def sizeHint(self): if self._pixmap.isNull(): return self.minimumSize() return self._pixmap.size() def paintEvent(self, event): QWidget.paintEvent(self, event) pmap = self._pixmap if pmap.isNull(): return w, h = pmap.width(), pmap.height() cw, ch = self.rect().width(), self.rect().height() scaled, nw, nh = fit_image(w, h, cw, ch) if scaled: pmap = pmap.scaled(nw, nh, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) w, h = pmap.width(), pmap.height() x = int(abs(cw - w)/2.) y = int(abs(ch - h)/2.) target = QRect(x, y, w, h) p = QPainter(self) p.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform) p.drawPixmap(target, pmap) pen = QPen() pen.setWidth(self.BORDER_WIDTH) p.setPen(pen) if self.draw_border: p.drawRect(target) #p.drawRect(self.rect()) p.end()
def _setLangIcons(self): itemcount = self.window.cmbx_lang.count() for i in range(0, itemcount + 1): if self.window.cmbx_lang.itemText(i) == u'English': path = './Resources/FlagsIcons/USA.png' elif self.window.cmbx_lang.itemText(i) == u'Русский': path = './Resources/FlagsIcons/Russia.png' elif self.window.cmbx_lang.itemText(i) == u'Română': path = './Resources/FlagsIcons/Moldova.png' img = QPixmap() img.load(path) icon = QIcon(img) self.window.cmbx_lang.setItemIcon(i, icon)
def cover_changed(self, data): if self.current_row is not None: id_ = self.view.model().id(self.current_row) self.view.model().db.set_cover(id_, data) if self.gui.cover_flow: self.gui.cover_flow.dataChanged() ci = self.view.currentIndex() if ci.isValid(): self.view.model().current_changed(ci, ci) self.cover_pixmap = QPixmap() self.cover_pixmap.loadFromData(data) if self.fit_cover.isChecked(): self.resize_cover()
def full(p, xmax, ymax): p.drawRect(0, 0, xmax, ymax) p.drawPolyline(QPoint(0, 0), QPoint(xmax, 0), QPoint(xmax, ymax), QPoint(0, ymax), QPoint(0, 0)) pp = QPainterPath() pp.addRect(0, 0, xmax, ymax) p.drawPath(pp) p.save() for i in xrange(3): col = [0, 0, 0, 200] col[i] = 255 p.setOpacity(0.3) p.fillRect(0, 0, xmax / 10, xmax / 10, QBrush(QColor(*col))) p.setOpacity(1) p.drawRect(0, 0, xmax / 10, xmax / 10) p.translate(xmax / 10, xmax / 10) p.scale(1, 1.5) p.restore() # p.scale(2, 2) # p.rotate(45) p.drawPixmap(0, 0, xmax / 4, xmax / 4, QPixmap(I('library.png'))) p.drawRect(0, 0, xmax / 4, xmax / 4) f = p.font() f.setPointSize(20) # f.setLetterSpacing(f.PercentageSpacing, 200) f.setUnderline(True) # f.setOverline(True) # f.setStrikeOut(True) f.setFamily('Calibri') p.setFont(f) # p.setPen(QColor(0, 0, 255)) # p.scale(2, 2) # p.rotate(45) p.drawText(QPoint(xmax / 3.9, 30), 'Some—text not By’s ū --- Д AV ff ff') b = QBrush(Qt.HorPattern) b.setColor(QColor(Qt.blue)) pix = QPixmap(I('console.png')) w = xmax / 4 p.fillRect(0, ymax / 3, w, w, b) p.fillRect(xmax / 3, ymax / 3, w, w, QBrush(pix)) x, y = 2 * xmax / 3, ymax / 3 p.drawTiledPixmap(QRectF(x, y, w, w), pix, QPointF(10, 10)) x, y = 1, ymax / 1.9 g = QLinearGradient(QPointF(x, y), QPointF(x + w, y + w)) g.setColorAt(0, QColor('#00f')) g.setColorAt(1, QColor('#fff')) p.fillRect(x, y, w, w, QBrush(g))
def insert_cover(self): if self.cover_data is None: return item_path = os.path.join(self.tmp_path, 'cover.pdf') printer = get_pdf_printer(self.opts, output_file_name=item_path) self.combine_queue.insert(0, item_path) p = QPixmap() p.loadFromData(self.cover_data) if not p.isNull(): painter = QPainter(printer) draw_image_page(printer, painter, p, preserve_aspect_ratio=self.opts.preserve_cover_aspect_ratio) painter.end() printer.abort()
def __init__(self, parent, drive, name): QWidget.__init__(self, parent) self.setupUi(self) if drive.removable: self.icon.setPixmap( QPixmap(":/gui/pics/drive-removable-media-usb-big.png")) elif drive.name.startswith("mmc"): self.icon.setPixmap( QPixmap(":/gui/pics/media-flash-sd-mmc-big.png")) else: self.icon.setPixmap(QPixmap(":/gui/pics/drive-harddisk-big.png")) self.labelDrive.setText("%s" % (name)) self.labelInfo.setText("%s\n%s GB" % (drive.model, str(int(drive.size) / 1024)))
def __init__(self, data, name, text, parent): QPushButton.__init__(self, text, parent) self.ic = QPixmap(self.iconSize()) color = data[name] self.data, self.name = data, name if color is not None: self.current_color = read_color(color).color() self.ic.fill(self.current_color) else: self.ic.fill(Qt.transparent) self.current_color = color self.update_tooltip() self.setIcon(QIcon(self.ic)) self.clicked.connect(self.choose_color)
def update_result(self, plugin_name, width, height, data): idx = None for plugin, i in self.plugin_map.iteritems(): if plugin.name == plugin_name: idx = i break if idx is None: return pmap = QPixmap() pmap.loadFromData(data) if pmap.isNull(): return self.covers[idx] = self.get_item(plugin_name, pmap, waiting=False) self.dataChanged.emit(self.index(idx), self.index(idx))
def insert_cover(self): if not isinstance(self.cover_data, bytes): return item_path = os.path.join(self.tmp_path, "cover.pdf") printer = get_pdf_printer(self.opts, output_file_name=item_path, for_comic=True) self.combine_queue.insert(0, item_path) p = QPixmap() p.loadFromData(self.cover_data) if not p.isNull(): painter = QPainter(printer) draw_image_page(printer, painter, p, preserve_aspect_ratio=self.opts.preserve_cover_aspect_ratio) painter.end() self.append_doc(item_path) printer.abort()
def dump(self, items, out_stream, pdf_metadata): opts = self.opts self.outline = Outline(self.toc, items) page_size = get_page_size(self.opts) xdpi, ydpi = self.view.logicalDpiX(), self.view.logicalDpiY() ml, mr = opts.margin_left, opts.margin_right margin_side = min(ml, mr) ml, mr = ml - margin_side, mr - margin_side 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) self.page.setViewportSize(QSize(self.doc.width(), self.doc.height())) self.render_queue = items self.total_items = len(items) # TODO: Test margins mt, mb = map(self.doc.to_px, (opts.margin_top, opts.margin_bottom)) ms = self.doc.to_px(margin_side, vertical=False) self.margin_top, self.margin_size, self.margin_bottom = map( lambda x:int(floor(x)), (mt, ms, mb)) self.painter = QPainter(self.doc) self.doc.set_metadata(title=pdf_metadata.title, author=pdf_metadata.author, tags=pdf_metadata.tags) self.painter.save() try: if self.cover_data is not None: p = QPixmap() p.loadFromData(self.cover_data) if not p.isNull(): draw_image_page(QRect(0, 0, self.doc.width(), self.doc.height()), 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) self.loop.exec_() # TODO: Outline and links self.painter.end() if self.doc.errors_occurred: raise Exception('PDF Output failed, see log for details')
def data(self, index, role): pluginListItem= self.plugins[index.row()] if index.isValid(): if role == Qt.DisplayRole: return QVariant(pluginListItem[0].name) if role == Qt.DecorationRole: for directory in GeneralUtilities.getPluginDirs(): picturePath = os.path.join(directory, pluginListItem[0].plugin_object.name, 'logo.png') if picturePath and os.path.exists(picturePath): pixmap = QPixmap(picturePath) return QIcon(pixmap) pixmap = QPixmap(':/creepy/folder') return QIcon(pixmap) else: return QVariant()
def data(self, index, role): pluginListItem= self.plugins[index.row()] if index.isValid(): if role == Qt.DisplayRole: return QVariant(pluginListItem[0].name) if role == Qt.DecorationRole: picturePath = os.path.join(os.getcwdu(), 'plugins', pluginListItem[0].plugin_object.name, 'logo.png') if picturePath and os.path.exists(picturePath): pixmap = QPixmap(picturePath) return QIcon(pixmap) else: pixmap = QPixmap(':/creepy/folder') return QIcon(pixmap) else: return QVariant()
def drag_icon(self, cover, multiple): cover = cover.scaledToHeight(120, Qt.SmoothTransformation) if multiple: base_width = cover.width() base_height = cover.height() base = QImage(base_width + 21, base_height + 21, QImage.Format_ARGB32_Premultiplied) base.fill(QColor(255, 255, 255, 0).rgba()) p = QPainter(base) rect = QRect(20, 0, base_width, base_height) p.fillRect(rect, QColor('white')) p.drawRect(rect) rect.moveLeft(10) rect.moveTop(10) p.fillRect(rect, QColor('white')) p.drawRect(rect) rect.moveLeft(0) rect.moveTop(20) p.fillRect(rect, QColor('white')) p.save() p.setCompositionMode(p.CompositionMode_SourceAtop) p.drawImage(rect.topLeft(), cover) p.restore() p.drawRect(rect) p.end() cover = base return QPixmap.fromImage(cover)
def fset(self, val): val = unicode(val or '') col = QColor(val) orig = self._color if col.isValid(): self._color = val self.setText(val) p = QPixmap(self.iconSize()) p.fill(col) self.setIcon(QIcon(p)) else: self._color = None self.setText(self.choose_text) self.setIcon(QIcon()) if orig != col: self.color_changed.emit(self._color)
def refresh(self, row): if isinstance(row, QModelIndex): row = row.row() if row == self.current_row: return mi = self.view.model().get_book_display_info(row) if mi is None: # Indicates books was deleted from library, or row numbers have # changed return self.previous_button.setEnabled(False if row == 0 else True) self.next_button.setEnabled(False if row == self.view.model().rowCount(QModelIndex()) - 1 else True) self.current_row = row self.setWindowTitle(mi.title) self.cover_pixmap = QPixmap.fromImage(mi.cover_data[1]) self.resize_cover() html = render_html(mi, self.css, True, self, all_fields=True) self.details.setHtml(html) self.marked = mi.marked self.cover.setBackgroundBrush( self.marked_brush if mi.marked else self.normal_brush) self.update_cover_tooltip()
def __init__(self, parent=None): QStackedWidget.__init__(self, parent) self.welcome = w = QLabel('<p>'+_( 'Double click a file in the left panel to start editing' ' it.')) self.addWidget(w) w.setWordWrap(True) w.setAlignment(Qt.AlignTop | Qt.AlignHCenter) self.container = c = QWidget(self) self.addWidget(c) l = c.l = QVBoxLayout(c) c.setLayout(l) l.setContentsMargins(0, 0, 0, 0) self.editor_tabs = t = QTabWidget(c) l.addWidget(t) t.setDocumentMode(True) t.setTabsClosable(True) t.setMovable(True) pal = self.palette() if pal.color(pal.WindowText).lightness() > 128: i = QImage(I('modified.png')) i.invertPixels() self.modified_icon = QIcon(QPixmap.fromImage(i)) else: self.modified_icon = QIcon(I('modified.png')) self.editor_tabs.currentChanged.connect(self.current_editor_changed) self.editor_tabs.tabCloseRequested.connect(self._close_requested) self.search_panel = SearchPanel(self) l.addWidget(self.search_panel) self.restore_state() self.editor_tabs.tabBar().installEventFilter(self)
def show_splash_screen(self): self.splash_pixmap = QPixmap() self.splash_pixmap.load(I("library.png")) self.splash_screen = QSplashScreen(self.splash_pixmap) self.splash_screen.showMessage(_("Starting %s: Loading books...") % __appname__) self.splash_screen.show() QApplication.instance().processEvents()
def drag_icon(self, cover, multiple): cover = cover.scaledToHeight(120, Qt.SmoothTransformation) if multiple: base_width = cover.width() base_height = cover.height() base = QImage(base_width+21, base_height+21, QImage.Format_ARGB32_Premultiplied) base.fill(QColor(255, 255, 255, 0).rgba()) p = QPainter(base) rect = QRect(20, 0, base_width, base_height) p.fillRect(rect, QColor('white')) p.drawRect(rect) rect.moveLeft(10) rect.moveTop(10) p.fillRect(rect, QColor('white')) p.drawRect(rect) rect.moveLeft(0) rect.moveTop(20) p.fillRect(rect, QColor('white')) p.save() p.setCompositionMode(p.CompositionMode_SourceAtop) p.drawImage(rect.topLeft(), cover) p.restore() p.drawRect(rect) p.end() cover = base return QPixmap.fromImage(cover)
def dnd_get_image(md, image_exts=IMAGE_EXTENSIONS): ''' Get the image in the QMimeData object md. :return: None, None if no image is found QPixmap, None if an image is found, the pixmap is guaranteed not null url, filename if a URL that points to an image is found ''' if dnd_has_image(md): for x in md.formats(): x = unicode(x) if x.startswith('image/'): cdata = bytes(md.data(x)) pmap = QPixmap() pmap.loadFromData(cdata) if not pmap.isNull(): return pmap, None break # No image, look for a URL pointing to an image if md.hasUrls(): urls = [unicode(u.toString()) for u in md.urls()] purls = [urlparse(u) for u in urls] # First look for a local file images = [u2p(x) for x in purls if x.scheme in ('', 'file')] images = [x for x in images if posixpath.splitext(urllib.unquote(x))[1][1:].lower() in image_exts] images = [x for x in images if os.path.exists(x)] p = QPixmap() for path in images: try: with open(path, 'rb') as f: p.loadFromData(f.read()) except: continue if not p.isNull(): return p, None # No local images, look for remote ones # First, see if this is from Firefox rurl, fname = get_firefox_rurl(md, image_exts) if rurl and fname: return rurl, fname # Look through all remaining URLs remote_urls = [x for x in purls if x.scheme in ('http', 'https', 'ftp') and posixpath.splitext(x.path)[1][1:].lower() in image_exts] if remote_urls: rurl = remote_urls[0] fname = posixpath.basename(urllib.unquote(rurl.path)) return urlunparse(rurl), fname return None, None
def render_images(self, outpath, mi, items): printer = get_pdf_printer(self.opts, for_comic=True, output_file_name=outpath) printer.setDocName(mi.title) painter = QPainter(printer) painter.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform) for i, imgpath in enumerate(items): self.log("Rendering image:", i) p = QPixmap() p.load(imgpath) if not p.isNull(): if i > 0: printer.newPage() draw_image_page(printer, painter, p) else: self.log.warn("Failed to load image", i) painter.end()
def data(self, role): if role == Qt.DisplayRole: return QVariant(self.title) if role == Qt.DecorationRole: if self.icon is None: icon = '%s.png'%self.urn[8:] p = QPixmap() if icon in self.favicons: try: with zipfile.ZipFile(self.zf, 'r') as zf: p.loadFromData(zf.read(self.favicons[icon])) except: pass if not p.isNull(): self.icon = QVariant(QIcon(p)) else: self.icon = self.default_icon return self.icon return NONE