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 _display_issues(self): self.values_list.clear() issues = self.mm.get_all_issues(True) for id, issue in issues: item = QListWidgetItem(get_icon('images/books.png'), issue, self.values_list) item.setData(1, (id,)) self.values_list.addItem(item)
def __init__(self, pathname, parent=None, watching=Purr.WATCHED): self._pathname = pathname pathname = Kittens.utils.collapseuser(pathname) self._in_setWatching = True QListWidgetItem.__init__(self, pathname, parent) self.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsTristate) self.setWatching(watching)
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 self.devices: 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)) self.existing_plugboards.addItem(item) self.refilling = False
def link_stylesheets(self, names): s = self.categories['styles'] sheets = [unicode(s.child(i).data(0, NAME_ROLE).toString()) 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.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: sheets = [unicode(s.item(i).text()) for i in xrange(s.count()) if s.item(i).checkState() == Qt.Checked] if sheets: self.link_stylesheets_requested.emit(names, sheets)
def add_builtin_recipe(self): from calibre.web.feeds.recipes.collection import \ get_builtin_recipe_collection, get_builtin_recipe_by_id from PyQt4.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).toString()) title = unicode(item.data(Qt.DisplayRole).toString()).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 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 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 _display_choices(self): self.values_list.clear() choices = self.mm.search(self.mi.title) if choices is None or len(choices)==0: item = QListWidgetItem(get_icon('images/books.png'), _('there seem to be no matches'), self.values_list) self.values_list.addItem(item) for id, name in choices.items(): item = QListWidgetItem(get_icon('images/books.png'), name, self.values_list) item.setData(1, (id,)) self.values_list.addItem(item)
def _display_formats(self): self.values_list.clear() formats = self.dm.get_download_info(self.casanova_id) if isinstance(formats, list): for format in formats: item = QListWidgetItem(get_icon('images/books.png'), format['type'], self.values_list) item.setData(1, (format,)) self.values_list.addItem(item) else: return error_dialog(self.gui, 'Casanova message', unicode(formats), show=True)
def add_account_to_list(self, account): at = self.app.preferences.ui.accountList n = at.count() icon = self.app.icons.get_service_icon(account.service, account.url) li = QListWidgetItem( u"{0} ({1})".format( account.name, account.service)) if icon is not None: li.setIcon(icon) at.insertItem(n, li) at.setCurrentRow(n)
def __init__(self, parent, user): if user.username == "root": icon = "root" name = _("Super User") else: name = user.username icon = "normal" label = "%s (%s)" % (name, user.realname) QListWidgetItem.__init__(self, QIcon(":/gui/pics/user_%s.png" % icon), label, parent) self.user = user
def build_dictionaries(self, current=None): self.dictionaries.clear() for dic in sorted(dictionaries.all_user_dictionaries, key=lambda d:sort_key(d.name)): i = QListWidgetItem(dic.name, self.dictionaries) i.setData(Qt.UserRole, dic) if dic.is_active: i.setData(Qt.FontRole, self.emph_font) if current == dic.name: self.dictionaries.setCurrentItem(i) if current is None and self.dictionaries.count() > 0: self.dictionaries.setCurrentRow(0)
def show_current_dictionary(self, *args): d = self.current_dictionary if d is None: return self.dlabel.setText(_('Configure the dictionary: <b>%s') % d.name) self.is_active.blockSignals(True) self.is_active.setChecked(d.is_active) self.is_active.blockSignals(False) self.words.clear() for word, lang in sorted(d.words, key=lambda x:sort_key(x[0])): i = QListWidgetItem('%s [%s]' % (word, get_language(lang)), self.words) i.setData(Qt.UserRole, (word, lang))
def __init__(self, parent, ext, size, path=None, timestamp=None): self.path = path self.ext = ext self.size = float(size)/(1024*1024) text = '%s (%.2f MB)'%(self.ext.upper(), self.size) QListWidgetItem.__init__(self, file_icon_provider().icon_from_ext(ext), text, parent, QListWidgetItem.UserType) if timestamp is not None: ts = timestamp.astimezone(local_tz) t = strftime('%a, %d %b %Y [%H:%M:%S]', ts.timetuple()) text = _('Last modified: %s\n\nDouble click to view')%t self.setToolTip(text) self.setStatusTip(text)
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(set(['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, QVariant(format)) item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsSelectable)
def run(self): for file in self.files: if(self._fnameInCollection(file)): self.emit(SIGNAL('logMessage'), "File {0} is already in test collection".format(os.path.basename(file))) else: item = QListWidgetItem(os.path.basename(file)) tc = TestCase(os.path.basename(file),file) item.setData(Qt.UserRole, tc) self.emit(SIGNAL('addItemToList'), item) self.emit(SIGNAL('logMessage'), "Added file {0}".format(os.path.basename(file))) self.parserHelper.parseListItem(item) self.emit(SIGNAL('setItemIcon'), item, tc.status) self.emit(SIGNAL('sortListAndUpdateButtons'))
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(_('No problems found'))
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 __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__( self, parent, ["paragraph_type", "formatting_type", "markdown_extensions", "preserve_spaces", "txt_in_remove_indents"], ) 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 __init__(self, dev, ignored_folders=None, parent=None): QDialog.__init__(self, parent) self.l = l = QVBoxLayout() self.setLayout(l) self.la = la = QLabel( "<p>" + _("<b>Scanned folders:</b>") + " " + _("You can select which top level folders calibre will " "scan when searching this device for books.") ) la.setWordWrap(True) l.addWidget(la) self.tabs = QTabWidget(self) l.addWidget(self.tabs) self.widgets = [] for storage in dev.filesystem_cache.entries: w = QListWidget(self) w.storage = storage self.tabs.addTab(w, storage.name) self.widgets.append(w) for child in sorted(storage.folders, key=attrgetter("name")): i = QListWidgetItem(child.name) i.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) i.setCheckState( Qt.Unchecked if dev.is_folder_ignored(storage, child.name, ignored_folders=ignored_folders) else Qt.Checked ) w.addItem(i) self.bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.bb.accepted.connect(self.accept) self.bb.rejected.connect(self.reject) self.sab = self.bb.addButton(_("Select &All"), self.bb.ActionRole) self.sab.clicked.connect(self.select_all) self.snb = self.bb.addButton(_("Select &None"), self.bb.ActionRole) self.snb.clicked.connect(self.select_none) l.addWidget(self.bb) self.setWindowTitle(_("Choose folders to scan")) self.setWindowIcon(QIcon(I("devices/tablet.png"))) self.resize(500, 500)
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 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)
def insertItems(self, row, items, setAsDefault = True): """ Insert the <items> specified items in this list widget. The list widget shows item name string , as a QListwidgetItem. This QListWidgetItem object defines a 'key' of a dictionary (self._itemDictionary) and the 'value' of this key is the object specified by the 'item' itself. Example: self._itemDictionary['C6'] = instance of class Atom. @param row: The row number for the item. @type row: int @param items: A list of objects. These objects are treated as values in the self._itemDictionary @type items: list @param setAsDefault: Not used here. See PM_ListWidget.insertItems where it is used. @see: self.renameItemValue() for a comment about self._suppress_itemChanged_signal """ #delete unused argument. Should this be provided as an argument in this #class method ? del setAsDefault #self.__init__ for a comment about this flag self._suppress_itemChanged_signal = True #Clear the previous contents of the self._itemDictionary self._itemDictionary.clear() #Clear the contents of this list widget, using QListWidget.clear() #See U{<http://doc.trolltech.com/4.2/qlistwidget.html>} for details self.clear() for item in items: if hasattr(item.__class__, 'name'): itemName = item.name else: itemName = str(item) listWidgetItem = QListWidgetItem(itemName, self) #When we support editing list widget items , uncomment out the #following line . See also self.editItems -- Ninad 2008-01-16 listWidgetItem.setFlags( listWidgetItem.flags()| Qt.ItemIsEditable) if hasattr(item.__class__, 'iconPath'): try: listWidgetItem.setIcon(geticon(item.iconPath)) except: print_compact_traceback() self._itemDictionary[listWidgetItem] = item #Reset the flag that temporarily suppresses itemChange signal. self._suppress_itemChanged_signal = False
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 set_bookmarks(self, bookmarks=None): if bookmarks is None: bookmarks = self.original_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 len(bookmarks) > 0: self.bookmarks_list.setCurrentItem(self.bookmarks_list.item(0), QItemSelectionModel.ClearAndSelect)
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, QVariant(col)) if col.startswith('#'): item.setData(Qt.DecorationRole, QVariant(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 # Supported, enabled formats all_formats = self.prefs.get('kindle_supported_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, QVariant(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__(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 __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 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, parent, pixmap, user): icon = QIcon(pixmap) QListWidgetItem.__init__(self, icon, QString(user.username), parent) self._user = user
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(): 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() 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, QVariant(key)) item.setData(Qt.DecorationRole, QVariant(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 __init__(self, text='', x=0, color='k'): QListWidgetItem.__init__(self) self.setText(text) self.x = x self.color = color
def __init__(self, gui, initial_panel=None): QDialog.__init__(self, gui) self.l = l = QGridLayout(self) self.setLayout(l) self.setWindowTitle(_('Preferences for Tweak Book')) self.setWindowIcon(QIcon(I('config.png'))) self.stacks = QStackedWidget(self) l.addWidget(self.stacks, 0, 1, 1, 1) self.categories_list = cl = QListWidget(self) cl.currentRowChanged.connect(self.stacks.setCurrentIndex) cl.clearPropertyFlags() cl.setViewMode(cl.IconMode) cl.setFlow(cl.TopToBottom) cl.setMovement(cl.Static) cl.setWrapping(False) cl.setSpacing(15) cl.setWordWrap(True) l.addWidget(cl, 0, 0, 1, 1) self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) self.rdb = b = bb.addButton(_('Restore all defaults'), bb.ResetRole) b.setToolTip(_('Restore defaults for all preferences')) b.clicked.connect(self.restore_all_defaults) self.rcdb = b = bb.addButton(_('Restore current defaults'), bb.ResetRole) b.setToolTip(_('Restore defaults for currently displayed preferences')) b.clicked.connect(self.restore_current_defaults) l.addWidget(bb, 1, 0, 1, 2) self.resize(800, 600) geom = tprefs.get('preferences_geom', None) if geom is not None: self.restoreGeometry(geom) self.keyboard_panel = ShortcutConfig(self) self.keyboard_panel.initialize(gui.keyboard) self.editor_panel = EditorSettings(self) self.integration_panel = IntegrationSettings(self) for name, icon, panel in [ (_('Editor settings'), 'modified.png', 'editor'), (_('Keyboard shortcuts'), 'keyboard-prefs.png', 'keyboard'), (_('Integration with calibre'), 'lt.png', 'integration'), ]: i = QListWidgetItem(QIcon(I(icon)), name, cl) cl.addItem(i) self.stacks.addWidget(getattr(self, panel + '_panel')) cl.setCurrentRow(0) cl.item(0).setSelected(True) w, h = cl.sizeHintForColumn(0), 0 for i in xrange(cl.count()): h = max(h, cl.sizeHintForRow(i)) cl.item(i).setSizeHint(QSize(w, h)) cl.setMaximumWidth(cl.sizeHintForColumn(0) + 35) cl.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
def __init__(self, settings, all_formats, supports_subdirs, must_read_metadata, supports_use_author_sort, extra_customization_message, device): QWidget.__init__(self) Ui_ConfigWidget.__init__(self) self.setupUi(self) self.settings = settings all_formats = set(all_formats) self.calibre_known_formats = device.FORMATS self.device_name = device.get_gui_name() 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, QVariant(format)) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsSelectable) item.setCheckState(Qt.Checked if format in format_map else Qt.Unchecked) self.connect(self.column_up, SIGNAL('clicked()'), self.up_column) self.connect(self.column_down, SIGNAL('clicked()'), self.down_column) if supports_subdirs: self.opt_use_subdirs.setChecked(self.settings.use_subdirs) else: self.opt_use_subdirs.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: 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])) 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.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.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 __init__(self, text, user_data=None): QListWidgetItem.__init__(self, text) self.user_data = user_data
def __init__(self, parent, connection, package): QListWidgetItem.__init__(self, QIcon(":/gui/pics/%s.png" % package), connection, parent) self._connection = [connection, package]