def show_pages(self): self.loading.setVisible(False) if self.error is not None: error_dialog(self, _('Failed to render'), _('Could not render this PDF file'), show=True) self.reject() return files = (glob(os.path.join(self.tdir, '*.jpg')) + glob(os.path.join(self.tdir, '*.jpeg'))) if not files: error_dialog(self, _('Failed to render'), _('This PDF has no pages'), show=True) self.reject() return try: dpr = self.devicePixelRatioF() except AttributeError: dpr = self.devicePixelRatio() for i, f in enumerate(sorted(files)): p = QPixmap(f).scaled(self.covers.iconSize()*dpr, aspectRatioMode=Qt.IgnoreAspectRatio, transformMode=Qt.SmoothTransformation) p.setDevicePixelRatio(dpr) i = QListWidgetItem(_('page %d') % (i + 1)) i.setData(Qt.DecorationRole, p) i.setData(Qt.UserRole, f) self.covers.addItem(i)
def __init__(self, all_formats, format_map): QWidget.__init__(self) self.l = l = QGridLayout() self.setLayout(l) self.f = f = QListWidget(self) l.addWidget(f, 0, 0, 3, 1) unchecked_formats = sorted(all_formats - set(format_map)) for fmt in format_map + unchecked_formats: item = QListWidgetItem(fmt, f) item.setData(Qt.UserRole, fmt) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsSelectable) item.setCheckState(Qt.Checked if fmt in format_map else Qt.Unchecked) self.button_up = b = QToolButton(self) b.setIcon(QIcon(I('arrow-up.png'))) l.addWidget(b, 0, 1) b.clicked.connect(self.up) self.button_down = b = QToolButton(self) b.setIcon(QIcon(I('arrow-down.png'))) l.addWidget(b, 2, 1) b.clicked.connect(self.down)
def add_result(self, result): i = QListWidgetItem(' ', self) i.setData(Qt.UserRole, result) i.setIcon(self.blank_icon) if getattr(result, 'file_name'): i.setData(Qt.ToolTipRole, _('In internal file: {}').format(result.file_name)) return self.count()
def initialize(self): self.confirms_reset = False self.devices.blockSignals(True) self.devices.clear() for dev in self.gui.device_manager.devices: for d, name in iteritems(dev.get_user_blacklisted_devices()): item = QListWidgetItem('%s [%s]' % (name, d), self.devices) item.setData(Qt.ItemDataRole.UserRole, (dev, d)) item.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsUserCheckable | Qt.ItemFlag.ItemIsSelectable) item.setCheckState(Qt.CheckState.Checked) self.devices.blockSignals(False) self.device_plugins.blockSignals(True) for dev in self.gui.device_manager.disabled_device_plugins: n = dev.get_gui_name() item = QListWidgetItem(n, self.device_plugins) item.setData(Qt.ItemDataRole.UserRole, dev) item.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsUserCheckable | Qt.ItemFlag.ItemIsSelectable) item.setCheckState(Qt.CheckState.Checked) item.setIcon(QIcon(I('plugins.png'))) self.device_plugins.sortItems() self.device_plugins.blockSignals(False)
def __init__(self, parent=None): QWidget.__init__(self, parent) self.l = l = QGridLayout(self) def add_row(*args): r = l.rowCount() if len(args) == 1: l.addWidget(args[0], r, 0, 1, 2) else: la = QLabel(args[0]) l.addWidget(la, r, 0, Qt.AlignmentFlag.AlignRight), l.addWidget(args[1], r, 1) la.setBuddy(args[1]) self.heading = la = QLabel('<h2>\xa0') add_row(la) self.helpl = la = QLabel(_('For help with snippets, see the <a href="%s">User Manual</a>') % localize_user_manual_link('https://manual.calibre-ebook.com/snippets.html')) la.setOpenExternalLinks(True) add_row(la) self.name = n = QLineEdit(self) n.setPlaceholderText(_('The name of this snippet')) add_row(_('&Name:'), n) self.trig = t = QLineEdit(self) t.setPlaceholderText(_('The text used to trigger this snippet')) add_row(_('Tri&gger:'), t) self.template = t = QPlainTextEdit(self) la.setBuddy(t) add_row(_('&Template:'), t) self.types = t = QListWidget(self) t.setFlow(QListView.Flow.LeftToRight) t.setWrapping(True), t.setResizeMode(QListView.ResizeMode.Adjust), t.setSpacing(5) fm = t.fontMetrics() t.setMaximumHeight(2*(fm.ascent() + fm.descent()) + 25) add_row(_('&File types:'), t) t.setToolTip(_('Which file types this snippet should be active in')) self.frame = f = QFrame(self) f.setFrameShape(f.HLine) add_row(f) self.test = d = SnippetTextEdit('', self) d.snippet_manager.snip_func = self.snip_func d.setToolTip(_('You can test your snippet here')) d.setMaximumHeight(t.maximumHeight() + 15) add_row(_('T&est:'), d) i = QListWidgetItem(_('All'), t) i.setData(Qt.ItemDataRole.UserRole, '*') i.setCheckState(Qt.CheckState.Checked) i.setFlags(i.flags() | Qt.ItemFlag.ItemIsUserCheckable) for ftype in sorted(all_text_syntaxes): i = QListWidgetItem(ftype, t) i.setData(Qt.ItemDataRole.UserRole, ftype) i.setCheckState(Qt.CheckState.Checked) i.setFlags(i.flags() | Qt.ItemFlag.ItemIsUserCheckable) self.creating_snippet = False
def set_bookmarks(self, bookmarks=()): csb = self.current_sort_by if csb == 'name': sk = lambda x: sort_key(x['title']) elif csb == 'timestamp': sk = itemgetter('timestamp') else: from calibre.ebooks.epub.cfi.parse import cfi_sort_key defval = cfi_sort_key('/99999999') def pos_key(b): if b.get('pos_type') == 'epubcfi': return cfi_sort_key(b['pos'], only_path=False) return defval sk = pos_key bookmarks = sorted(bookmarks, key=sk) current_bookmark_id = self.current_bookmark_id self.bookmarks_list.clear() for bm in bookmarks: i = QListWidgetItem(bm['title']) i.setData(Qt.UserRole, self.bm_to_item(bm)) i.setFlags(i.flags() | Qt.ItemIsEditable) self.bookmarks_list.addItem(i) if bm.get('removed'): i.setHidden(True) for i in range(self.bookmarks_list.count()): item = self.bookmarks_list.item(i) if not item.isHidden(): self.bookmarks_list.setCurrentItem( item, QItemSelectionModel.ClearAndSelect) break if current_bookmark_id is not None: self.current_bookmark_id = current_bookmark_id
def refill_all_boxes(self): if self.refilling: return self.refilling = True self.current_device = None self.current_format = None self.clear_fields(new_boxes=True) self.edit_format.clear() self.edit_format.addItem('') for format_ in self.current_plugboards: self.edit_format.addItem(format_) self.edit_format.setCurrentIndex(0) self.edit_device.clear() self.ok_button.setEnabled(False) self.del_button.setEnabled(False) self.existing_plugboards.clear() for f in self.formats: if f not in self.current_plugboards: continue for d in sorted(self.devices + self.disabled_devices, key=lambda x: x.lower()): if d not in self.current_plugboards[f]: continue ops = [] for op in self.current_plugboards[f][d]: ops.append('([' + op[0] + '] -> ' + op[1] + ')') txt = '%s:%s = %s\n' % (f, d, ', '.join(ops)) item = QListWidgetItem(txt) item.setData(Qt.UserRole, (f, d)) if d in self.disabled_devices: item.setFlags(item.flags() & ~Qt.ItemIsEnabled) self.existing_plugboards.addItem(item) self.refilling = False
def show_pages(self): if self.error is not None: error_dialog(self, _('Failed to render'), _('Could not render this PDF file'), show=True, det_msg=self.error) self.reject() return self.stack.stop() files = glob(os.path.join(self.current_tdir, '*.jpg')) + glob(os.path.join(self.current_tdir, '*.jpeg')) if not files and not self.covers.count(): error_dialog(self, _('Failed to render'), _('This PDF has no pages'), show=True) self.reject() return try: dpr = self.devicePixelRatioF() except AttributeError: dpr = self.devicePixelRatio() for i, f in enumerate(sorted(files)): p = QPixmap(f).scaled( self.covers.iconSize()*dpr, aspectRatioMode=Qt.AspectRatioMode.IgnoreAspectRatio, transformMode=Qt.TransformationMode.SmoothTransformation) p.setDevicePixelRatio(dpr) i = QListWidgetItem(_('page %d') % (self.first + i)) i.setData(Qt.ItemDataRole.DecorationRole, p) i.setData(Qt.ItemDataRole.UserRole, f) self.covers.addItem(i) self.first += len(files) if len(files) == PAGES_PER_RENDER: self.more_pages.setVisible(True)
def _setReferences(self, result): self.reference_field.clear() for reference in result: item = QListWidgetItem() item.setData(Qt.UserRole, reference) item.setText("{}".format(reference.text)) self.reference_field.insertItem(0, item)
def __init__(self, parent, duplicates, loc): QDialog.__init__(self, parent) l = QVBoxLayout() self.setLayout(l) self.la = la = QLabel(_('Books with the same title and author as the following already exist in the library %s.' ' Select which books you want copied anyway.') % os.path.basename(loc)) la.setWordWrap(True) l.addWidget(la) self.setWindowTitle(_('Duplicate books')) self.books = QListWidget(self) self.items = [] for book_id, (title, authors) in duplicates.iteritems(): i = QListWidgetItem(_('{0} by {1}').format(title, ' & '.join(authors[:3])), self.books) i.setData(Qt.UserRole, book_id) i.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) i.setCheckState(Qt.Checked) self.items.append(i) l.addWidget(self.books) self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) self.a = b = bb.addButton(_('Select &all'), bb.ActionRole) b.clicked.connect(self.select_all), b.setIcon(QIcon(I('plus.png'))) self.n = b = bb.addButton(_('Select &none'), bb.ActionRole) b.clicked.connect(self.select_none), b.setIcon(QIcon(I('minus.png'))) self.ctc = b = bb.addButton(_('&Copy to clipboard'), bb.ActionRole) b.clicked.connect(self.copy_to_clipboard), b.setIcon(QIcon(I('edit-copy.png'))) l.addWidget(bb) self.resize(600, 400)
def refill_all_boxes(self): if self.refilling: return self.refilling = True self.current_device = None self.current_format = None self.clear_fields(new_boxes=True) self.edit_format.clear() self.edit_format.addItem('') for format_ in self.current_plugboards: self.edit_format.addItem(format_) self.edit_format.setCurrentIndex(0) self.edit_device.clear() self.ok_button.setEnabled(False) self.del_button.setEnabled(False) self.existing_plugboards.clear() for f in self.formats: if f not in self.current_plugboards: continue for d in sorted(self.devices + self.disabled_devices, key=lambda x:x.lower()): if d not in self.current_plugboards[f]: continue ops = [] for op in self.current_plugboards[f][d]: ops.append('([' + op[0] + '] -> ' + op[1] + ')') txt = '%s:%s = %s\n'%(f, d, ', '.join(ops)) item = QListWidgetItem(txt) item.setData(Qt.UserRole, (f, d)) if d in self.disabled_devices: item.setFlags(item.flags() & ~Qt.ItemIsEnabled) self.existing_plugboards.addItem(item) self.refilling = False
def setup_export_panel(self): self.export_panel = w = QWidget(self) self.stack.addWidget(w) w.l = l = QVBoxLayout(w) w.la = la = QLabel( _('Select which libraries you want to export below')) la.setWordWrap(True), l.addWidget(la) self.lib_list = ll = QListWidget(self) l.addWidget(ll) ll.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection) ll.setStyleSheet('QListView::item { padding: 5px }') ll.setAlternatingRowColors(True) lpaths = all_known_libraries() for lpath in sorted( lpaths, key=lambda x: numeric_sort_key(os.path.basename(x))): i = QListWidgetItem(self.export_lib_text(lpath), ll) i.setData(Qt.ItemDataRole.UserRole, lpath) i.setData(Qt.ItemDataRole.UserRole + 1, lpaths[lpath]) i.setIcon(QIcon(I('lt.png'))) i.setSelected(True) self.update_disk_usage.connect( (lambda i, sz: self.lib_list.item(i).setText( self.export_lib_text( self.lib_list.item(i).data(Qt.ItemDataRole.UserRole), sz)) ), type=Qt.ConnectionType.QueuedConnection)
def show_pages(self): if self.error is not None: error_dialog(self, _('Failed to render'), _('Could not render this PDF file'), show=True, det_msg=self.error) self.reject() return self.stack.stop() files = glob(os.path.join(self.current_tdir, '*.jpg')) + glob(os.path.join(self.current_tdir, '*.jpeg')) if not files and not self.covers.count(): error_dialog(self, _('Failed to render'), _('This PDF has no pages'), show=True) self.reject() return try: dpr = self.devicePixelRatioF() except AttributeError: dpr = self.devicePixelRatio() for i, f in enumerate(sorted(files)): p = QPixmap(f).scaled(self.covers.iconSize()*dpr, aspectRatioMode=Qt.IgnoreAspectRatio, transformMode=Qt.SmoothTransformation) p.setDevicePixelRatio(dpr) i = QListWidgetItem(_('page %d') % (self.first + i)) i.setData(Qt.DecorationRole, p) i.setData(Qt.UserRole, f) self.covers.addItem(i) self.first += len(files) if len(files) == PAGES_PER_RENDER: self.more_pages.setVisible(True)
def create_item(self, alias, key, checked=False): i = QListWidgetItem(alias, self.recipients) i.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsUserCheckable) i.setCheckState( Qt.CheckState.Checked if checked else Qt.CheckState.Unchecked) i.setData(Qt.ItemDataRole.UserRole, key) self.items.append(i)
def __init__(self, parent, duplicates, loc): QDialog.__init__(self, parent) l = QVBoxLayout() self.setLayout(l) self.la = la = QLabel( _('Books with the same, title, author and language as the following already exist in the library %s.' ' Select which books you want copied anyway.') % os.path.basename(loc)) la.setWordWrap(True) l.addWidget(la) self.setWindowTitle(_('Duplicate books')) self.books = QListWidget(self) self.items = [] for book_id, (title, authors) in duplicates.iteritems(): i = QListWidgetItem( _('{0} by {1}').format(title, ' & '.join(authors[:3])), self.books) i.setData(Qt.UserRole, book_id) i.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) i.setCheckState(Qt.Checked) self.items.append(i) l.addWidget(self.books) self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) self.a = b = bb.addButton(_('Select &all'), bb.ActionRole) b.clicked.connect(self.select_all), b.setIcon(QIcon(I('plus.png'))) self.n = b = bb.addButton(_('Select &none'), bb.ActionRole) b.clicked.connect(self.select_none), b.setIcon(QIcon(I('minus.png'))) self.ctc = b = bb.addButton(_('&Copy to clipboard'), bb.ActionRole) b.clicked.connect(self.copy_to_clipboard), b.setIcon( QIcon(I('edit-copy.png'))) l.addWidget(bb) self.resize(600, 400)
def __init__(self, parent=None): QWidget.__init__(self, parent) self.l = l = QGridLayout(self) def add_row(*args): r = l.rowCount() if len(args) == 1: l.addWidget(args[0], r, 0, 1, 2) else: la = QLabel(args[0]) l.addWidget(la, r, 0, Qt.AlignRight), l.addWidget(args[1], r, 1) la.setBuddy(args[1]) self.heading = la = QLabel('<h2>\xa0') add_row(la) self.helpl = la = QLabel(_('For help with snippets, see the <a href="%s">User Manual</a>') % localize_user_manual_link('https://manual.calibre-ebook.com/snippets.html')) la.setOpenExternalLinks(True) add_row(la) self.name = n = QLineEdit(self) n.setPlaceholderText(_('The name of this snippet')) add_row(_('&Name:'), n) self.trig = t = QLineEdit(self) t.setPlaceholderText(_('The text used to trigger this snippet')) add_row(_('Tri&gger:'), t) self.template = t = QPlainTextEdit(self) la.setBuddy(t) add_row(_('&Template:'), t) self.types = t = QListWidget(self) t.setFlow(t.LeftToRight) t.setWrapping(True), t.setResizeMode(t.Adjust), t.setSpacing(5) fm = t.fontMetrics() t.setMaximumHeight(2*(fm.ascent() + fm.descent()) + 25) add_row(_('&File types:'), t) t.setToolTip(_('Which file types this snippet should be active in')) self.frame = f = QFrame(self) f.setFrameShape(f.HLine) add_row(f) self.test = d = SnippetTextEdit('', self) d.snippet_manager.snip_func = self.snip_func d.setToolTip(_('You can test your snippet here')) d.setMaximumHeight(t.maximumHeight() + 15) add_row(_('T&est:'), d) i = QListWidgetItem(_('All'), t) i.setData(Qt.UserRole, '*') i.setCheckState(Qt.Checked) i.setFlags(i.flags() | Qt.ItemIsUserCheckable) for ftype in sorted(all_text_syntaxes): i = QListWidgetItem(ftype, t) i.setData(Qt.UserRole, ftype) i.setCheckState(Qt.Checked) i.setFlags(i.flags() | Qt.ItemIsUserCheckable) self.creating_snippet = False
def setResult(self, references): self.result_list.clear() for reference in references: item = QListWidgetItem() item.setData(Qt.UserRole, reference) item.setText("{}".format(reference.text)) self.result_list.insertItem(0, item)
def add_builtin_recipe(self): from calibre.web.feeds.recipes.collection import \ get_builtin_recipe_collection, get_builtin_recipe_by_id from PyQt5.Qt import QDialog, QVBoxLayout, QListWidgetItem, \ QListWidget, QDialogButtonBox, QSize d = QDialog(self) d.l = QVBoxLayout() d.setLayout(d.l) d.list = QListWidget(d) d.list.doubleClicked.connect(lambda x: d.accept()) d.l.addWidget(d.list) d.bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel, Qt.Horizontal, d) d.bb.accepted.connect(d.accept) d.bb.rejected.connect(d.reject) d.l.addWidget(d.bb) d.setWindowTitle(_('Choose builtin recipe')) items = [] for r in get_builtin_recipe_collection(): id_ = r.get('id', '') title = r.get('title', '') lang = r.get('language', '') if id_ and title: items.append((title + ' [%s]'%lang, id_)) items.sort(key=lambda x:sort_key(x[0])) for title, id_ in items: item = QListWidgetItem(title) item.setData(Qt.UserRole, id_) d.list.addItem(item) d.resize(QSize(450, 400)) ret = d.exec_() d.list.doubleClicked.disconnect() if ret != d.Accepted: return items = list(d.list.selectedItems()) if not items: return item = items[-1] id_ = unicode(item.data(Qt.UserRole) or '') title = unicode(item.data(Qt.DisplayRole) or '').rpartition(' [')[0] profile = get_builtin_recipe_by_id(id_, download_recipe=True) if profile is None: raise Exception('Something weird happened') if self._model.has_title(title): if question_dialog(self, _('Replace recipe?'), _('A custom recipe named %s already exists. Do you want to ' 'replace it?')%title): self._model.replace_by_title(title, profile) else: return else: self.model.add(title, profile) self.clear()
def entry_to_item(entry, parent): icon_path = entry.get('Icon') or I('blank.png') ans = QListWidgetItem(QIcon(icon_path), entry.get('Name') or _('Unknown'), parent) ans.setData(ENTRY_ROLE, entry) comment = (entry.get('Comment') or '') if comment: comment += '\n' ans.setToolTip(comment + _('Command line:') + '\n' + (' '.join(entry['Exec'])))
def to_item(key, ac, parent): ic = ac.icon() if not ic or ic.isNull(): ic = blank ans = QListWidgetItem(ic, unicode(ac.text()).replace('&', ''), parent) ans.setData(Qt.UserRole, key) ans.setToolTip(ac.toolTip()) return ans
def setReferenceList(self, result): self.references_field.clear() for ref in result: item = QListWidgetItem() item.setData(Qt.UserRole, ref) item_text = getBibRenderFromHTML(ref.text) item.setText("{}".format(item_text)) self.references_field.insertItem(0, item)
def populate_column(self, col, asc, is_checked): item = QListWidgetItem(self.gui.library_view.model().headers[col], self) item.setData(Qt.UserRole, col + '|' + str(asc)) flags = Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsUserCheckable item.setFlags(flags) item.setCheckState(Qt.Checked if is_checked else Qt.Unchecked) self.set_sort_icon(item)
def to_item(key, ac, parent): ic = ac.icon() if not ic or ic.isNull(): ic = blank ans = QListWidgetItem(ic, unicode_type(ac.text()).replace('&', ''), parent) ans.setData(Qt.ItemDataRole.UserRole, key) ans.setToolTip(ac.toolTip()) return ans
def create_item(self, data): x = data i = QListWidgetItem( QIcon(QPixmap(x["path"]).scaled(256, 256, transformMode=Qt.SmoothTransformation)), x["name"], self.images ) i.setData(Qt.UserRole, x["fname"]) i.setData(Qt.UserRole + 1, x["path"]) return i
def entry_to_item(entry, parent): icon = get_icon(entry.get('icon_file'), as_data=False) if icon is None: icon = entry_to_icon_text(entry)[0] else: icon = QPixmap.fromImage(icon) ans = QListWidgetItem(QIcon(icon), entry.get('name') or _('Unknown'), parent) ans.setData(ENTRY_ROLE, entry) ans.setToolTip(_('Application path:') + '\n' + entry['path'])
def set_bookmarks(self, bookmarks=()): self.bookmarks_list.clear() for bm in bookmarks: i = QListWidgetItem(bm['title']) i.setData(Qt.UserRole, self.bm_to_item(bm)) i.setFlags(i.flags() | Qt.ItemIsEditable) self.bookmarks_list.addItem(i) if self.bookmarks_list.count() > 0: self.bookmarks_list.setCurrentItem(self.bookmarks_list.item(0), QItemSelectionModel.ClearAndSelect)
def _setValue(self): self.relation_line.setText(self.relation.description) self.study_line.setText(self.relation.study) references = self.relation.reference for ref in references: item = QListWidgetItem() item.setData(Qt.UserRole, ref) item.setText("{}".format(ref.text)) self.references_line.insertItem(0, item)
def search_epub_content(self): ''' Search epub content ''' # reset results layout self.search_results.clear() # get search input keyword = self.search_input.text() # search in each book db = self.db.new_api matched_ids = {book_id for book_id in db.all_book_ids() if 'EPUB' in db.formats(book_id)} for book_id in matched_ids: mi = db.get_metadata(book_id, get_cover=False, cover_as_data=False) if prefs['tags'] in mi.tags: title = mi.title filepath = fmt_path = self.gui.current_db.format_abspath(book_id, 'EPUB', index_is_id=True) grep = EpubGrep(keyword) grep.setPreview(True) grep_result = grep.searchin(filepath) #print(grep_result) if grep_result != None and len(grep_result) != 0: widgetLayout = QVBoxLayout() book_button = QPushButton(title, self) book_button.clicked.connect(partial(self.view, book_id, 0)) widgetLayout.addWidget(book_button) widgetLayout.setSizeConstraint(QLayout.SetFixedSize) widget = QWidget() widget.setLayout(widgetLayout) widgetItem = QListWidgetItem() widgetItem.setSizeHint(widget.sizeHint()) self.search_results.addItem(widgetItem) self.search_results.setItemWidget(widgetItem, widget) #matched = result.stdout.decode('utf-8') matched = grep_result search_result_count = 0 if prefs['search_result_count'] == '' else int(prefs['search_result_count']) count = 0 for lines in matched.split('--\n'): # only handles results within limit if search_result_count != 0 and count >= search_result_count: break widgetLayout = QVBoxLayout() qLabel = QLabel(lines.replace(keyword, '<font color=yellow>' + keyword + '</font>').replace('\n\n', '\n').replace('\n','<br/>') + '<br/>') qLabel.setTextFormat(Qt.RichText) qLabel.setStyleSheet(''' font-size: 24px; ''') widgetLayout.addWidget(qLabel) widgetLayout.setSizeConstraint(QLayout.SetFixedSize) widget = QWidget() widget.setLayout(widgetLayout) widgetItem = QListWidgetItem() widgetItem.setSizeHint(widget.sizeHint()) widgetItem.setData(Qt.ItemDataRole.UserRole, (book_id, count)) self.search_results.addItem(widgetItem) self.search_results.setItemWidget(widgetItem, widget) count += 1 self.search_results.itemClicked.connect(self.view_search_result)
def load(self, highlights): self.clear() self.uuid_map = {} for h in highlights or (): txt = h.get('highlighted_text') if not h.get('removed') and txt: i = QListWidgetItem(txt, self) i.setData(Qt.UserRole, h) self.uuid_map[h['uuid']] = self.count() - 1
def fset(self, wl): self.dictionary_list.clear() for langcode, url in sorted( wl.iteritems(), key=lambda (lc, url): sort_key(calibre_langcode_to_name(lc))): i = QListWidgetItem( '%s: %s' % (calibre_langcode_to_name(langcode), url), self.dictionary_list) i.setData(Qt.UserRole, (langcode, url))
def create_color_scheme(self): scheme = self.colors_map[self.current_colors].data(Qt.ItemDataRole.UserRole) d = CreateColorScheme('#' + _('My Color Scheme'), scheme, set(self.colors_map), parent=self) if d.exec_() == QDialog.DialogCode.Accepted: name, scheme = d.data li = QListWidgetItem(name) li.setData(Qt.ItemDataRole.UserRole, scheme), li.setFlags(li.flags() | Qt.ItemFlag.ItemIsUserCheckable), li.setCheckState(Qt.CheckState.Checked) self.insert_scheme(name, li) self.emit_changed() self.original_prefs['color_themes'] = self.current_prefs['color_themes']
def set_bookmarks(self, bookmarks=()): self.bookmarks_list.clear() for bm in bookmarks: if bm['title'] != 'calibre_current_page_bookmark': i = QListWidgetItem(bm['title']) i.setData(Qt.UserRole, self.bm_to_item(bm)) i.setFlags(i.flags() | Qt.ItemIsEditable) self.bookmarks_list.addItem(i) if self.bookmarks_list.count() > 0: self.bookmarks_list.setCurrentItem(self.bookmarks_list.item(0), QItemSelectionModel.ClearAndSelect)
def resort(self): if self.sort_alphabetically.isChecked(): sorted_locations = sorted(self.locations, key=lambda (name, loc): numeric_sort_key(name)) else: sorted_locations = self.locations self.items.clear() for name, loc in sorted_locations: i = QListWidgetItem(name, self.items) i.setData(Qt.UserRole, loc) self.items.setCurrentRow(0)
def create_color_scheme(self): scheme = self.colors_map[self.current_colors].data(Qt.UserRole) d = CreateColorScheme('#' + _('My Color Scheme'), scheme, set(self.colors_map), parent=self) if d.exec_() == d.Accepted: name, scheme = d.data li = QListWidgetItem(name) li.setData(Qt.UserRole, scheme), li.setFlags(li.flags() | Qt.ItemIsUserCheckable), li.setCheckState(Qt.Checked) self.insert_scheme(name, li) self.emit_changed() self.original_prefs['color_themes'] = self.current_prefs['color_themes']
def populate_column(self, colname, is_checked): item = QListWidgetItem(self.gui.library_view.model().headers[colname], self) item.setData(Qt.UserRole, colname) flags = Qt.ItemIsEnabled | Qt.ItemIsSelectable if colname != 'ondevice': flags |= Qt.ItemIsUserCheckable item.setFlags(flags) if colname != 'ondevice': item.setCheckState(Qt.Checked if is_checked else Qt.Unchecked)
def resort(self): if self.sort_alphabetically.isChecked(): sorted_locations = sorted(self.locations, key=lambda name_loc: numeric_sort_key(name_loc[0])) else: sorted_locations = self.locations self.items.clear() for name, loc in sorted_locations: i = QListWidgetItem(name, self.items) i.setData(Qt.UserRole, loc) self.items.setCurrentRow(0)
def create_item(self, data): x = data i = QListWidgetItem( QIcon( QPixmap(x['path']).scaled( 256, 256, transformMode=Qt.SmoothTransformation)), x['name'], self.images) i.setData(Qt.UserRole, x['fname']) i.setData(Qt.UserRole + 1, x['path']) return i
def setValue(self): self.concept_field.setText(self.concept.name) self.synonyms_field.setText(self.concept.synonyms) self.subcategory_field.setText(self.subcategory.subcategory) self.study_field.setText(self.subcategory.study) descriptions = self.subcategory.description for des in descriptions: item = QListWidgetItem() item.setData(Qt.UserRole, des) item.setText("{}".format(des.text)) self.description_field.insertItem(0, item)
def updateWarriorList (self): row = 0 self.item = [] #self.tableWidget.clear() self.list_filtered.clear() for warrior in self.model.filteredWarriors() : item = QListWidgetItem (str(warrior.name)) item.setData(5,warrior) self.list_filtered.addItem(item) if warrior.selected == True: item.setSelected(True)
def _addReference(self): dialog = NewReferenceDialog(self.parent().db, RelationReference) if dialog.exec_(): references = dialog.getValues() for reference in references: reference.relation_id = self.relation.id self.parent().db.commit(reference) item = QListWidgetItem() item.setData(Qt.UserRole, reference) item.setText("{}".format(reference.text)) self.references_line.insertItem(0, item)
def entry_to_item(entry, parent): try: icon = load_icon_resource(entry.get('icon_resource')) except Exception: icon = None import traceback traceback.print_exc() if not icon: icon = entry_to_icon_text(entry)[0] ans = QListWidgetItem(QIcon(icon), entry.get('name') or _('Unknown'), parent) ans.setData(ENTRY_ROLE, entry) ans.setToolTip(_('Command line:') + '\n' + entry['cmdline'])
def re_sort(self): self.themes.sort(key=lambda x:sort_key(x.get('title', ''))) field = self.sort_on if field == 'number': self.themes.sort(key=lambda x:x.get('number', 0), reverse=True) elif field == 'usage': self.themes.sort(key=lambda x:self.usage.get(x.get('name'), 0), reverse=True) self.theme_list.clear() for theme in self.themes: i = QListWidgetItem(theme.get('title', '') + ' %s %s' % (theme.get('number'), self.usage.get(theme.get('name'))), self.theme_list) i.setData(Qt.UserRole, theme) if 'cover-pixmap' in theme: i.setData(Qt.DecorationRole, theme['cover-pixmap'])
def init_input_order(self, defaults=False): if defaults: input_map = prefs.defaults['input_format_order'] else: input_map = prefs['input_format_order'] all_formats = set() self.opt_input_order.clear() for fmt in all_input_formats().union({'ZIP', 'RAR'}): all_formats.add(fmt.upper()) for format in input_map + list(all_formats.difference(input_map)): item = QListWidgetItem(format, self.opt_input_order) item.setData(Qt.UserRole, (format)) item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsSelectable)
def resources(self, resources): self.items.clear() self.original_resources = resources dc = 0 for url, matches in resources.iteritems(): text = url num = len(matches) if text.startswith('data:'): dc += 1 text = _('Data URL #{}').format(dc) text += ' ({})'.format(ngettext('one instance', '{} instances', num).format(num)) i = QListWidgetItem(text, self.items) i.setData(Qt.UserRole, url) i.setCheckState(Qt.Checked) i.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
def __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__(self, parent, OPTIONS['input']['txt']) self.db, self.book_id = db, book_id for x in get_option('paragraph_type').option.choices: self.opt_paragraph_type.addItem(x) for x in get_option('formatting_type').option.choices: self.opt_formatting_type.addItem(x) self.md_map = {} for name, text in MD_EXTENSIONS.iteritems(): i = QListWidgetItem('%s - %s' % (name, text), self.opt_markdown_extensions) i.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) i.setData(Qt.UserRole, name) self.md_map[name] = i self.initialize_options(get_option, get_help, db, book_id)
def run_checks(self, container): with BusyCursor(): self.show_busy() QApplication.processEvents() errors = run_checks(container) self.hide_busy() for err in sorted(errors, key=lambda e:(100 - e.level, e.name)): i = QListWidgetItem('%s\xa0\xa0\xa0\xa0[%s]' % (err.msg, err.name), self.items) i.setData(Qt.UserRole, err) i.setIcon(icon_for_level(err.level)) if errors: self.items.setCurrentRow(0) self.current_item_changed() self.items.setFocus(Qt.OtherFocusReason) else: self.clear_help()
def change_builtin(self): d = QDialog(self) lw = QListWidget(d) for (trigger, syntaxes), snip in iteritems(builtin_snippets): snip = copy.deepcopy(snip) snip['trigger'], snip['syntaxes'] = trigger, syntaxes i = QListWidgetItem(self.snip_to_text(snip), lw) i.setData(Qt.UserRole, snip) d.l = l = QVBoxLayout(d) l.addWidget(QLabel(_('Choose the built-in snippet to modify:'))) l.addWidget(lw) lw.itemDoubleClicked.connect(d.accept) d.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) l.addWidget(bb) bb.accepted.connect(d.accept), bb.rejected.connect(d.reject) if d.exec_() == d.Accepted and lw.currentItem() is not None: self.stack.setCurrentIndex(1) self.edit_snip.apply_snip(lw.currentItem().data(Qt.UserRole), creating_snippet=True)
def customize_recipe(self): d = QDialog(self) d.l = QVBoxLayout() d.setLayout(d.l) d.list = QListWidget(d) d.list.doubleClicked.connect(lambda x: d.accept()) d.l.addWidget(d.list) d.bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel, Qt.Horizontal, d) d.bb.accepted.connect(d.accept) d.bb.rejected.connect(d.reject) d.l.addWidget(d.bb) d.setWindowTitle(_('Choose builtin recipe')) items = [] for r in get_builtin_recipe_collection(): id_ = r.get('id', '') title = r.get('title', '') lang = r.get('language', '') if id_ and title: items.append((title + ' [%s]'%lang, id_)) items.sort(key=lambda x:sort_key(x[0])) for title, id_ in items: item = QListWidgetItem(title) item.setData(Qt.UserRole, id_) d.list.addItem(item) d.resize(QSize(450, 400)) ret = d.exec_() d.list.doubleClicked.disconnect() if ret != d.Accepted: return items = list(d.list.selectedItems()) if not items: return item = items[-1] id_ = unicode(item.data(Qt.UserRole) or '') title = unicode(item.data(Qt.DisplayRole) or '').rpartition(' [')[0] src = get_builtin_recipe_by_id(id_, download_recipe=True) if src is None: raise Exception('Something weird happened') self.edit_recipe(None, src)
def show_pages(self): self.loading.setVisible(False) if self.error is not None: error_dialog(self, _('Failed to render'), _('Could not render this PDF file'), show=True) self.reject() return files = (glob(os.path.join(self.tdir, '*.jpg')) + glob(os.path.join(self.tdir, '*.jpeg'))) if not files: error_dialog(self, _('Failed to render'), _('This PDF has no pages'), show=True) self.reject() return for f in sorted(files): i = QListWidgetItem(QIcon(f), '') i.setData(Qt.UserRole, f) self.covers.addItem(i)
def setup_export_panel(self): self.export_panel = w = QWidget(self) self.stack.addWidget(w) w.l = l = QVBoxLayout(w) w.la = la = QLabel(_('Select which libraries you want to export below')) la.setWordWrap(True), l.addWidget(la) self.lib_list = ll = QListWidget(self) l.addWidget(ll) ll.setSelectionMode(ll.ExtendedSelection) ll.setStyleSheet('QListView::item { padding: 5px }') ll.setAlternatingRowColors(True) lpaths = all_known_libraries() for lpath in sorted(lpaths, key=lambda x:numeric_sort_key(os.path.basename(x))): i = QListWidgetItem(self.export_lib_text(lpath), ll) i.setData(Qt.UserRole, lpath) i.setData(Qt.UserRole+1, lpaths[lpath]) i.setIcon(QIcon(I('lt.png'))) i.setSelected(True) self.update_disk_usage.connect(( lambda i, sz: self.lib_list.item(i).setText(self.export_lib_text(self.lib_list.item(i).data(Qt.UserRole), sz))), type=Qt.QueuedConnection)
def setup_ui(self): from calibre.ebooks.oeb.polish.images import get_compressible_images self.setWindowIcon(QIcon(I('compress-image.png'))) self.h = h = QHBoxLayout(self) self.images = i = QListWidget(self) h.addWidget(i) self.l = l = QVBoxLayout() h.addLayout(l) c = current_container() for name in sorted(get_compressible_images(c), key=numeric_sort_key): x = QListWidgetItem(name, i) x.setData(Qt.UserRole, c.filesize(name)) i.setSelectionMode(i.ExtendedSelection) i.setMinimumHeight(500), i.setMinimumWidth(350) i.selectAll(), i.setSpacing(5) self.delegate = ImageItemDelegate(self) i.setItemDelegate(self.delegate) self.la = la = QLabel(_( 'You can compress the images in this book losslessly, reducing the file size of the book,' ' without affecting image quality. Typically image size is reduced by 5 - 15%.')) la.setWordWrap(True) la.setMinimumWidth(250) l.addWidget(la), l.addSpacing(30) self.enable_lossy = el = QCheckBox(_('Enable &lossy compression of JPEG images')) el.setToolTip(_('This allows you to change the quality factor used for JPEG images.\nBy lowering' ' the quality you can greatly reduce file size, at the expense of the image looking blurred.')) l.addWidget(el) self.h2 = h = QHBoxLayout() l.addLayout(h) self.jq = jq = QSpinBox(self) jq.setMinimum(0), jq.setMaximum(100), jq.setValue(tprefs.get('jpeg_compression_quality_for_lossless_compression', 80)), jq.setEnabled(False) jq.setToolTip(_('The compression quality, 1 is high compression, 100 is low compression.\nImage' ' quality is inversely correlated with compression quality.')) jq.valueChanged.connect(self.save_compression_quality) el.toggled.connect(jq.setEnabled) self.jql = la = QLabel(_('Compression &quality:')) la.setBuddy(jq) h.addWidget(la), h.addWidget(jq) l.addStretch(10) l.addWidget(self.bb)
def __init__(self, devs, blacklist): QWidget.__init__(self) self.l = l = QVBoxLayout() self.setLayout(l) self.la = la = QLabel('<p>'+_( '''Select the devices to be <b>ignored</b>. calibre <b>will not</b> connect to devices with a checkmark next to their names.''')) la.setWordWrap(True) l.addWidget(la) self.f = f = QListWidget(self) l.addWidget(f) devs = [(snum, (x[0], parse_date(x[1]))) for snum, x in devs.iteritems()] for dev, x in sorted(devs, key=lambda x:x[1][1], reverse=True): name = x[0] name = '%s [%s]'%(name, dev) item = QListWidgetItem(name, f) item.setData(Qt.UserRole, dev) item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable|Qt.ItemIsSelectable) item.setCheckState(Qt.Checked if dev in blacklist else Qt.Unchecked)
def initialize(self): self.devices.blockSignals(True) self.devices.clear() for dev in self.gui.device_manager.devices: for d, name in dev.get_user_blacklisted_devices().iteritems(): item = QListWidgetItem('%s [%s]'%(name, d), self.devices) item.setData(Qt.UserRole, (dev, d)) item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable|Qt.ItemIsSelectable) item.setCheckState(Qt.Checked) self.devices.blockSignals(False) self.device_plugins.blockSignals(True) for dev in self.gui.device_manager.disabled_device_plugins: n = dev.get_gui_name() item = QListWidgetItem(n, self.device_plugins) item.setData(Qt.UserRole, dev) item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable|Qt.ItemIsSelectable) item.setCheckState(Qt.Checked) item.setIcon(QIcon(I('plugins.png'))) self.device_plugins.sortItems() self.device_plugins.blockSignals(False)
def init_columns(self, defaults=False): # Set up columns self.opt_columns.blockSignals(True) model = self.gui.library_view.model() colmap = list(model.column_map) state = self.columns_state(defaults) hidden_cols = state["hidden_columns"] positions = state["column_positions"] colmap.sort(cmp=lambda x, y: cmp(positions[x], positions[y])) self.opt_columns.clear() for col in colmap: item = QListWidgetItem(model.headers[col], self.opt_columns) item.setData(Qt.UserRole, (col)) if col.startswith("#"): item.setData(Qt.DecorationRole, (QIcon(I("column.png")))) flags = Qt.ItemIsEnabled | Qt.ItemIsSelectable if col != "ondevice": flags |= Qt.ItemIsUserCheckable item.setFlags(flags) if col != "ondevice": item.setCheckState(Qt.Unchecked if col in hidden_cols else Qt.Checked) self.opt_columns.blockSignals(False)
def initialize(self, name): ''' Retrieve plugin-specific settings from general prefs store Need to store order of all possible formats, enabled formats ''' self.name = name # Allow for updated KINDLE_SUPPORTED_FORMATS all_formats = self.prefs.get('kindle_supported_formats', KINDLE_SUPPORTED_FORMATS) if len(all_formats) != len(KINDLE_SUPPORTED_FORMATS): all_formats = KINDLE_SUPPORTED_FORMATS enabled_formats = self.prefs.get('kindle_enabled_formats', KINDLE_ENABLED_FORMATS) for format in all_formats: item = QListWidgetItem(format, self.columns) item.setData(Qt.UserRole, format) item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable|Qt.ItemIsSelectable) item.setCheckState(Qt.Checked if format in enabled_formats else Qt.Unchecked) self.column_up.clicked.connect(self.up_column) self.column_down.clicked.connect(self.down_column)
def set_filter_items(self, state): """ Add filter items to QListWidget corresponding to "state" :param state: state of service to filter :type state: str """ services_added = False if state in 'NOT_MONITORED': for service in self.services: if not service.data['active_checks_enabled'] and \ not service.data['passive_checks_enabled']and \ not service.data['ls_downtimed'] and \ not service.data['ls_acknowledged']: self.add_filter_item(service) services_added = True elif state in 'DOWNTIME': for service in self.services: if service.data['ls_downtimed']: self.add_filter_item(service) services_added = True elif state in 'ACKNOWLEDGE': for service in self.services: if service.data['ls_acknowledged']: self.add_filter_item(service) services_added = True else: for service in self.services: if service.data['ls_state'] in state: self.add_filter_item(service) services_added = True if not services_added: not_added_item = QListWidgetItem() not_added_item.setData(Qt.DecorationRole, QIcon(settings.get_image('services_ok'))) not_added_item.setData(Qt.DisplayRole, _('No such services to display...')) self.services_list_widget.addItem(not_added_item)