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 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 image_import(self): """ Take the path(s) of one or more images and import them to the application. :return: Nothing """ file_dialog = QFileDialog() # Create QFileDialog # Open the file dialog as Open File Names dialog (for image choice) f_path = file_dialog.getOpenFileNames(parent=None, caption="Open Image(s)", directory=QDir.homePath(), filter=self.IMG_FILTER, options=self.DIALOG_FLAG)[0] if f_path: # If user chose at least one image img_id_counter = 0 # Set a counter for id for file in f_path: # For all paths in f_paths image_tmp = Image() # Create an Image object success = image_tmp.img_open(file) # Set image parameters if success: # If image exists image_tmp.img_set_image_id(img_id_counter) # Set image counter img_id_counter += 1 # increase the counter by 1 # image_tmp.img_print_info() # print image info for debugging self.image_list.append(image_tmp) # Append image to list item_name = "../" + image_tmp.info.dir_name + "/" + image_tmp.info.name # Set name for view item_widget = QListWidgetItem(item_name) # Append item to window image list item_widget.setFlags(item_widget.flags() | QtCore.Qt.ItemIsUserCheckable) # Set it checkable item_widget.setCheckState(QtCore.Qt.Checked) # Set it checked self.ui_main_win.listImage.addItem(item_widget) # Add item to list self.ui_main_win.menuCamera_Settings.setEnabled(self.UP) # Enable Camera menu self.ui_main_win.actionCrabSFM.setEnabled(self.UP) # Enable SFM action
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 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 __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 resources(self, resources): self.items.clear() self.original_resources = resources for url in resources: i = QListWidgetItem(url, self.items) i.setCheckState(Qt.Checked) i.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
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 __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 __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 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 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 setter(w, val): order_map = {x:i for i, x in enumerate(val)} items = list(w.defaults) limit = len(items) items.sort(key=lambda x:order_map.get(x, limit)) w.clear() for x in items: i = QListWidgetItem(w) i.setText(x) i.setFlags(i.flags() | Qt.ItemFlag.ItemIsDragEnabled)
def setter(w, val): order_map = {x:i for i, x in enumerate(val)} items = list(w.defaults) limit = len(items) items.sort(key=lambda x:order_map.get(x, limit)) w.clear() for x in items: i = QListWidgetItem(w) i.setText(x) i.setFlags(i.flags() | Qt.ItemIsDragEnabled)
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 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 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 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 link_stylesheets(self, names): s = self.categories['styles'] sheets = [ unicode(s.child(i).data(0, NAME_ROLE) or '') for i in xrange(s.childCount()) ] if not sheets: return error_dialog( self, _('No stylesheets'), _('This book currently has no stylesheets. You must first create a stylesheet' ' before linking it.'), show=True) d = QDialog(self) d.l = l = QVBoxLayout(d) d.setLayout(l) d.setWindowTitle(_('Choose stylesheets')) d.la = la = QLabel( _('Choose the stylesheets to link. Drag and drop to re-arrange')) la.setWordWrap(True) l.addWidget(la) d.s = s = QListWidget(d) l.addWidget(s) s.setDragEnabled(True) s.setDropIndicatorShown(True) s.setDragDropMode(self.InternalMove) s.setAutoScroll(True) s.setDefaultDropAction(Qt.MoveAction) for name in sheets: i = QListWidgetItem(name, s) flags = Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsDragEnabled | Qt.ItemIsSelectable i.setFlags(flags) i.setCheckState(Qt.Checked) d.r = r = QCheckBox(_('Remove existing links to stylesheets')) r.setChecked(tprefs['remove_existing_links_when_linking_sheets']) l.addWidget(r) d.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) bb.accepted.connect(d.accept), bb.rejected.connect(d.reject) l.addWidget(bb) if d.exec_() == d.Accepted: tprefs['remove_existing_links_when_linking_sheets'] = r.isChecked() sheets = [ unicode(s.item(il).text()) for il in xrange(s.count()) if s.item(il).checkState() == Qt.Checked ] if sheets: self.link_stylesheets_requested.emit(names, sheets, r.isChecked())
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 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 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 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 link_stylesheets(self, names): s = self.categories["styles"] sheets = [unicode(s.child(i).data(0, NAME_ROLE) or "") for i in xrange(s.childCount())] if not sheets: return error_dialog( self, _("No stylesheets"), _("This book currently has no stylesheets. You must first create a stylesheet" " before linking it."), show=True, ) d = QDialog(self) d.l = l = QVBoxLayout(d) d.setLayout(l) d.setWindowTitle(_("Choose stylesheets")) d.la = la = QLabel(_("Choose the stylesheets to link. Drag and drop to re-arrange")) la.setWordWrap(True) l.addWidget(la) d.s = s = QListWidget(d) l.addWidget(s) s.setDragEnabled(True) s.setDropIndicatorShown(True) s.setDragDropMode(self.InternalMove) s.setAutoScroll(True) s.setDefaultDropAction(Qt.MoveAction) for name in sheets: i = QListWidgetItem(name, s) flags = Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsDragEnabled | Qt.ItemIsSelectable i.setFlags(flags) i.setCheckState(Qt.Checked) d.r = r = QCheckBox(_("Remove existing links to stylesheets")) r.setChecked(tprefs["remove_existing_links_when_linking_sheets"]) l.addWidget(r) d.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) bb.accepted.connect(d.accept), bb.rejected.connect(d.reject) l.addWidget(bb) if d.exec_() == d.Accepted: tprefs["remove_existing_links_when_linking_sheets"] = r.isChecked() sheets = [unicode(s.item(il).text()) for il in xrange(s.count()) if s.item(il).checkState() == Qt.Checked] if sheets: self.link_stylesheets_requested.emit(names, sheets, r.isChecked())
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 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 video_import(self): """ Take the path(s) of one or more videos and import them to the application. :return: """ file_dialog = QFileDialog() f_path = file_dialog.getOpenFileNames(parent=None, caption="Open Video(s)", directory=QDir.homePath(), filter=self.VID_FILTER, options=self.DIALOG_FLAG)[0] if f_path: for file in f_path: video_tmp = Video() success = video_tmp.vid_open(file) if success: self.video_list.append(video_tmp) item_name = "../" + video_tmp.info.dir_name + "/" + video_tmp.info.name item_widget = QListWidgetItem(item_name) item_widget.setFlags(item_widget.flags() | QtCore.Qt.ItemIsUserCheckable) item_widget.setCheckState(QtCore.Qt.Checked) self.ui_main_win.listVideo.addItem(item_widget) self.video_list_info()
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 populate_list_item(self, fav_menu, idx= -1): self.blockSignals(True) if fav_menu is None: item = QListWidgetItem(self.SEP) item.setIcon(self.blank_icon) else: text = fav_menu['display'] item = QListWidgetItem(text) item.setFlags(Qt.ItemIsEditable | item.flags()) paths = fav_menu['path'] item.setToolTip(' -> '.join(paths)) item.setData(Qt.UserRole, (fav_menu,)) icon = fav_menu.get('icon', None) if icon is None: # This is a menu item that hasn't been found in this session # We will display it with a blank icon and disabled icon = self.blank_icon item.setForeground(QBrush(Qt.darkGray)) item.setIcon(icon) if idx < 0: self.addItem(item) else: self.insertItem(idx + 1, item) self.blockSignals(False)
def __init__(self, settings, all_formats, supports_subdirs, supports_non_english_characters, must_read_metadata, supports_use_author_sort, extra_customization_message, device, extra_customization_choices=None): QWidget.__init__(self) Ui_ConfigWidget.__init__(self) self.setupUi(self) self.settings = settings all_formats = set(all_formats) self.calibre_known_formats = device.FORMATS try: self.device_name = device.get_gui_name() except TypeError: self.device_name = getattr(device, 'gui_name', None) or _('Device') if device.USER_CAN_ADD_NEW_FORMATS: all_formats = set(all_formats) | set(BOOK_EXTENSIONS) format_map = settings.format_map disabled_formats = list(set(all_formats).difference(format_map)) for format in format_map + list(sorted(disabled_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 format_map else Qt.Unchecked) self.column_up.clicked.connect(self.up_column) self.column_down.clicked.connect(self.down_column) if device.HIDE_FORMATS_CONFIG_BOX: self.groupBox.hide() if supports_subdirs: self.opt_use_subdirs.setChecked(self.settings.use_subdirs) else: self.opt_use_subdirs.hide() if supports_non_english_characters: self.opt_asciiize.setChecked(self.settings.asciiize) else: self.opt_asciiize.hide() if not must_read_metadata: self.opt_read_metadata.setChecked(self.settings.read_metadata) else: self.opt_read_metadata.hide() if supports_use_author_sort: self.opt_use_author_sort.setChecked(self.settings.use_author_sort) else: self.opt_use_author_sort.hide() if extra_customization_message: extra_customization_choices = extra_customization_choices or {} def parse_msg(m): msg, _, tt = m.partition(':::') if m else ('', '', '') return msg.strip(), textwrap.fill(tt.strip(), 100) if isinstance(extra_customization_message, list): self.opt_extra_customization = [] if len(extra_customization_message) > 6: row_func = lambda x, y: ((x/2) * 2) + y col_func = lambda x: x%2 else: row_func = lambda x, y: x*2 + y col_func = lambda x: 0 for i, m in enumerate(extra_customization_message): label_text, tt = parse_msg(m) if not label_text: self.opt_extra_customization.append(None) continue if isinstance(settings.extra_customization[i], bool): self.opt_extra_customization.append(QCheckBox(label_text)) self.opt_extra_customization[-1].setToolTip(tt) self.opt_extra_customization[i].setChecked(bool(settings.extra_customization[i])) elif i in extra_customization_choices: cb = QComboBox(self) self.opt_extra_customization.append(cb) l = QLabel(label_text) l.setToolTip(tt), cb.setToolTip(tt), l.setBuddy(cb), cb.setToolTip(tt) for li in sorted(extra_customization_choices[i]): self.opt_extra_customization[i].addItem(li) cb.setCurrentIndex(max(0, cb.findText(settings.extra_customization[i]))) else: self.opt_extra_customization.append(QLineEdit(self)) l = QLabel(label_text) l.setToolTip(tt) self.opt_extra_customization[i].setToolTip(tt) l.setBuddy(self.opt_extra_customization[i]) l.setWordWrap(True) self.opt_extra_customization[i].setText(settings.extra_customization[i]) self.opt_extra_customization[i].setCursorPosition(0) self.extra_layout.addWidget(l, row_func(i, 0), col_func(i)) self.extra_layout.addWidget(self.opt_extra_customization[i], row_func(i, 1), col_func(i)) else: self.opt_extra_customization = QLineEdit() label_text, tt = parse_msg(extra_customization_message) l = QLabel(label_text) l.setToolTip(tt) l.setBuddy(self.opt_extra_customization) l.setWordWrap(True) if settings.extra_customization: self.opt_extra_customization.setText(settings.extra_customization) self.opt_extra_customization.setCursorPosition(0) self.opt_extra_customization.setCursorPosition(0) self.extra_layout.addWidget(l, 0, 0) self.extra_layout.addWidget(self.opt_extra_customization, 1, 0) self.opt_save_template.setText(settings.save_template)
def accept(self): col = unicode(self.column_name_box.text()).strip() if not col: return self.simple_error('', _('No lookup name was provided')) if col.startswith('#'): col = col[1:] if re.match('^\w*$', col) is None or not col[0].isalpha() or col.lower() != col: return self.simple_error('', _('The lookup name must contain only ' 'lower case letters, digits and underscores, and start with a letter')) if col.endswith('_index'): return self.simple_error('', _('Lookup names cannot end with _index, ' 'because these names are reserved for the index of a series column.')) col_heading = unicode(self.column_heading_box.text()).strip() col_type = self.column_types[self.column_type_box.currentIndex()]['datatype'] if col_type[0] == '*': col_type = col_type[1:] is_multiple = True else: is_multiple = False if not col_heading: return self.simple_error('', _('No column heading was provided')) db = self.parent.gui.library_view.model().db key = db.field_metadata.custom_field_prefix+col bad_col = False if key in self.parent.custcols: if not self.editing_col or \ self.parent.custcols[key]['colnum'] != self.orig_column_number: bad_col = True if bad_col: return self.simple_error('', _('The lookup name %s is already used')%col) bad_head = False for t in self.parent.custcols: if self.parent.custcols[t]['name'] == col_heading: if not self.editing_col or \ self.parent.custcols[t]['colnum'] != self.orig_column_number: bad_head = True for t in self.standard_colheads: if self.standard_colheads[t] == col_heading: bad_head = True if bad_head: return self.simple_error('', _('The heading %s is already used')%col_heading) display_dict = {} if col_type == 'datetime': if unicode(self.date_format_box.text()).strip(): display_dict = {'date_format':unicode(self.date_format_box.text()).strip()} else: display_dict = {'date_format': None} elif col_type == 'composite': if not unicode(self.composite_box.text()).strip(): return self.simple_error('', _('You must enter a template for' ' composite columns')) display_dict = {'composite_template':unicode(self.composite_box.text()).strip(), 'composite_sort': ['text', 'number', 'date', 'bool'] [self.composite_sort_by.currentIndex()], 'make_category': self.composite_make_category.isChecked(), 'contains_html': self.composite_contains_html.isChecked(), } elif col_type == 'enumeration': if not unicode(self.enum_box.text()).strip(): return self.simple_error('', _('You must enter at least one' ' value for enumeration columns')) l = [v.strip() for v in unicode(self.enum_box.text()).split(',') if v.strip()] l_lower = [v.lower() for v in l] for i,v in enumerate(l_lower): if v in l_lower[i+1:]: return self.simple_error('', _('The value "{0}" is in the ' 'list more than once, perhaps with different case').format(l[i])) c = unicode(self.enum_colors.text()) if c: c = [v.strip() for v in unicode(self.enum_colors.text()).split(',')] else: c = [] if len(c) != 0 and len(c) != len(l): return self.simple_error('', _('The colors box must be empty or ' 'contain the same number of items as the value box')) for tc in c: if tc not in QColor.colorNames() and not re.match("#(?:[0-9a-f]{3}){1,4}",tc,re.I): return self.simple_error('', _('The color {0} is unknown').format(tc)) display_dict = {'enum_values': l, 'enum_colors': c} elif col_type == 'text' and is_multiple: display_dict = {'is_names': self.is_names.isChecked()} elif col_type in ['int', 'float']: if unicode(self.number_format_box.text()).strip(): display_dict = {'number_format':unicode(self.number_format_box.text()).strip()} else: display_dict = {'number_format': None} if col_type in ['text', 'composite', 'enumeration'] and not is_multiple: display_dict['use_decorations'] = self.use_decorations.checkState() display_dict['description'] = self.description_box.text().strip() if not self.editing_col: self.parent.custcols[key] = { 'label':col, 'name':col_heading, 'datatype':col_type, 'display':display_dict, 'normalized':None, 'colnum':None, 'is_multiple':is_multiple, } item = QListWidgetItem(col_heading, self.parent.opt_columns) item.setData(Qt.UserRole, (key)) item.setData(Qt.DecorationRole, (QIcon(I('column.png')))) item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable|Qt.ItemIsSelectable) item.setCheckState(Qt.Checked) else: idx = self.parent.opt_columns.currentRow() item = self.parent.opt_columns.item(idx) item.setText(col_heading) self.parent.custcols[self.orig_column_name]['label'] = col self.parent.custcols[self.orig_column_name]['name'] = col_heading self.parent.custcols[self.orig_column_name]['display'].update(display_dict) self.parent.custcols[self.orig_column_name]['*edited'] = True self.parent.custcols[self.orig_column_name]['*must_restart'] = True QDialog.accept(self)
def accept(self): col = unicode(self.column_name_box.text()).strip() if not col: return self.simple_error('', _('No lookup name was provided')) if col.startswith('#'): col = col[1:] if re.match('^\w*$', col) is None or not col[0].isalpha() or col.lower() != col: return self.simple_error( '', _('The lookup name must contain only ' 'lower case letters, digits and underscores, and start with a letter' )) if col.endswith('_index'): return self.simple_error( '', _('Lookup names cannot end with _index, ' 'because these names are reserved for the index of a series column.' )) col_heading = unicode(self.column_heading_box.text()).strip() col_type = self.column_types[ self.column_type_box.currentIndex()]['datatype'] if col_type[0] == '*': col_type = col_type[1:] is_multiple = True else: is_multiple = False if not col_heading: return self.simple_error('', _('No column heading was provided')) db = self.parent.gui.library_view.model().db key = db.field_metadata.custom_field_prefix + col bad_col = False if key in self.parent.custcols: if not self.editing_col or \ self.parent.custcols[key]['colnum'] != self.orig_column_number: bad_col = True if bad_col: return self.simple_error( '', _('The lookup name %s is already used') % col) bad_head = False for t in self.parent.custcols: if self.parent.custcols[t]['name'] == col_heading: if not self.editing_col or \ self.parent.custcols[t]['colnum'] != self.orig_column_number: bad_head = True for t in self.standard_colheads: if self.standard_colheads[t] == col_heading: bad_head = True if bad_head: return self.simple_error( '', _('The heading %s is already used') % col_heading) display_dict = {} if col_type == 'datetime': if unicode(self.date_format_box.text()).strip(): display_dict = { 'date_format': unicode(self.date_format_box.text()).strip() } else: display_dict = {'date_format': None} elif col_type == 'composite': if not unicode(self.composite_box.text()).strip(): return self.simple_error( '', _('You must enter a template for' ' composite columns')) display_dict = { 'composite_template': unicode(self.composite_box.text()).strip(), 'composite_sort': ['text', 'number', 'date', 'bool'][self.composite_sort_by.currentIndex()], 'make_category': self.composite_make_category.isChecked(), 'contains_html': self.composite_contains_html.isChecked(), } elif col_type == 'enumeration': if not unicode(self.enum_box.text()).strip(): return self.simple_error( '', _('You must enter at least one' ' value for enumeration columns')) l = [ v.strip() for v in unicode(self.enum_box.text()).split(',') if v.strip() ] l_lower = [v.lower() for v in l] for i, v in enumerate(l_lower): if v in l_lower[i + 1:]: return self.simple_error( '', _('The value "{0}" is in the ' 'list more than once, perhaps with different case'). format(l[i])) c = unicode(self.enum_colors.text()) if c: c = [ v.strip() for v in unicode(self.enum_colors.text()).split(',') ] else: c = [] if len(c) != 0 and len(c) != len(l): return self.simple_error( '', _('The colors box must be empty or ' 'contain the same number of items as the value box')) for tc in c: if tc not in QColor.colorNames() and not re.match( "#(?:[0-9a-f]{3}){1,4}", tc, re.I): return self.simple_error( '', _('The color {0} is unknown').format(tc)) display_dict = {'enum_values': l, 'enum_colors': c} elif col_type == 'text' and is_multiple: display_dict = {'is_names': self.is_names.isChecked()} elif col_type in ['int', 'float']: if unicode(self.number_format_box.text()).strip(): display_dict = { 'number_format': unicode(self.number_format_box.text()).strip() } else: display_dict = {'number_format': None} if col_type in ['text', 'composite', 'enumeration' ] and not is_multiple: display_dict['use_decorations'] = self.use_decorations.checkState() display_dict['description'] = self.description_box.text().strip() if not self.editing_col: self.parent.custcols[key] = { 'label': col, 'name': col_heading, 'datatype': col_type, 'display': display_dict, 'normalized': None, 'colnum': None, 'is_multiple': is_multiple, } item = QListWidgetItem(col_heading, self.parent.opt_columns) item.setData(Qt.UserRole, (key)) item.setData(Qt.DecorationRole, (QIcon(I('column.png')))) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsSelectable) item.setCheckState(Qt.Checked) else: idx = self.parent.opt_columns.currentRow() item = self.parent.opt_columns.item(idx) item.setText(col_heading) self.parent.custcols[self.orig_column_name]['label'] = col self.parent.custcols[self.orig_column_name]['name'] = col_heading self.parent.custcols[self.orig_column_name]['display'].update( display_dict) self.parent.custcols[self.orig_column_name]['*edited'] = True self.parent.custcols[self.orig_column_name]['*must_restart'] = True QDialog.accept(self)
def create_item(self, alias, key, checked=False): i = QListWidgetItem(alias, self.recipients) i.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable) i.setCheckState(Qt.Checked if checked else Qt.Unchecked) i.setData(Qt.UserRole, key) self.items.append(i)
def __init__(self, plugin): QWidget.__init__(self) self.plugin = plugin self.layout = QVBoxLayout() self.setLayout(self.layout) self.engine_location_label = QLabel('ElasticSearch engine location:') self.layout.addWidget(self.engine_location_label) self.elasticsearch_url_textbox = QLineEdit(self) self.elasticsearch_url_textbox.setText(prefs['elasticsearch_url']) self.layout.addWidget(self.elasticsearch_url_textbox) self.engine_location_label.setBuddy(self.elasticsearch_url_textbox) self.layout.addSpacing(10) self.pdftotext_path_label = QLabel('Path to pdftotext tool:') self.layout.addWidget(self.pdftotext_path_label) self.pdftotext_path_textbox = QLineEdit(self) self.pdftotext_path_textbox.setText(prefs['pdftotext_path']) self.layout.addWidget(self.pdftotext_path_textbox) self.pdftotext_path_label.setBuddy(self.pdftotext_path_textbox) self.layout.addSpacing(10) self.concurrency_label = QLabel( 'Number of parallel processes for text extraction:') self.layout.addWidget(self.concurrency_label) self.concurrency_textbox = QLineEdit(self) self.concurrency_textbox.setText(str(prefs['concurrency'])) self.layout.addWidget(self.concurrency_textbox) self.concurrency_label.setBuddy(self.concurrency_textbox) self.layout.addSpacing(10) self.formats_label = QLabel('Index book formats:') self.layout.addWidget(self.formats_label) file_formats = prefs['file_formats'].split(',') self.formats_list = QListWidget(self) for fmt in SUPPORTED_FORMATS: item = QListWidgetItem(fmt) item.setFlags(item.flags() | Qt.ItemIsUserCheckable) item.setCheckState(Qt.Checked if fmt in file_formats else Qt.Unchecked) self.formats_list.addItem(item) self.layout.addWidget(self.formats_list) self.formats_label.setBuddy(self.formats_list) self.layout.addSpacing(10) self.autoindex_checkbox = QCheckBox( "Automatically index new books on search", self) self.autoindex_checkbox.setCheckState( Qt.Checked if prefs['autoindex'] else Qt.Unchecked) self.layout.addWidget(self.autoindex_checkbox) self.layout.addSpacing(10) self.privacy_label = QLabel('Privacy:') self.layout.addWidget(self.privacy_label) self.clear_search_history_button = QPushButton('Clear search &history', self) self.clear_search_history_button.clicked.connect(self.on_clear_history) self.layout.addWidget(self.clear_search_history_button) self.clear_search_index_buttin = QPushButton('Clear search &index', self) self.clear_search_index_buttin.clicked.connect(self.on_clear_index) self.layout.addWidget(self.clear_search_index_buttin)