本文整理汇总了Python中PyQt5.Qt.QListWidget.addItem方法的典型用法代码示例。如果您正苦于以下问题:Python QListWidget.addItem方法的具体用法?Python QListWidget.addItem怎么用?Python QListWidget.addItem使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.Qt.QListWidget
的用法示例。
在下文中一共展示了QListWidget.addItem方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ChoosePluginToolbarsDialog
# 需要导入模块: from PyQt5.Qt import QListWidget [as 别名]
# 或者: from PyQt5.Qt.QListWidget import addItem [as 别名]
class ChoosePluginToolbarsDialog(QDialog):
def __init__(self, parent, plugin, locations):
QDialog.__init__(self, parent)
self.locations = locations
self.setWindowTitle(
_('Add "%s" to toolbars or menus')%plugin.name)
self._layout = QVBoxLayout(self)
self.setLayout(self._layout)
self._header_label = QLabel(
_('Select the toolbars and/or menus to add <b>%s</b> to:') %
plugin.name)
self._layout.addWidget(self._header_label)
self._locations_list = QListWidget(self)
self._locations_list.setSelectionMode(QAbstractItemView.MultiSelection)
sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
self._locations_list.setSizePolicy(sizePolicy)
for key, text in locations:
self._locations_list.addItem(text)
if key in {'toolbar', 'toolbar-device'}:
self._locations_list.item(self._locations_list.count()-1
).setSelected(True)
self._layout.addWidget(self._locations_list)
self._footer_label = QLabel(
_('You can also customise the plugin locations '
'using <b>Preferences -> Customise the toolbar</b>'))
self._layout.addWidget(self._footer_label)
button_box = QDialogButtonBox(QDialogButtonBox.Ok |
QDialogButtonBox.Cancel)
button_box.accepted.connect(self.accept)
button_box.rejected.connect(self.reject)
self._layout.addWidget(button_box)
self.resize(self.sizeHint())
def selected_locations(self):
selected = []
for row in self._locations_list.selectionModel().selectedRows():
selected.append(self.locations[row.row()])
return selected
示例2: PrefsViewerDialog
# 需要导入模块: from PyQt5.Qt import QListWidget [as 别名]
# 或者: from PyQt5.Qt.QListWidget import addItem [as 别名]
class PrefsViewerDialog(SizePersistedDialog):
def __init__(self, gui, namespace):
SizePersistedDialog.__init__(self, gui, _('Prefs Viewer dialog'))
self.setWindowTitle(_('Preferences for: ')+namespace)
self.gui = gui
self.db = gui.current_db
self.namespace = namespace
self._init_controls()
self.resize_dialog()
self._populate_settings()
if self.keys_list.count():
self.keys_list.setCurrentRow(0)
def _init_controls(self):
layout = QVBoxLayout(self)
self.setLayout(layout)
ml = QHBoxLayout()
layout.addLayout(ml, 1)
self.keys_list = QListWidget(self)
self.keys_list.setSelectionMode(QAbstractItemView.SingleSelection)
self.keys_list.setFixedWidth(150)
self.keys_list.setAlternatingRowColors(True)
ml.addWidget(self.keys_list)
self.value_text = QTextEdit(self)
self.value_text.setTabStopWidth(24)
self.value_text.setReadOnly(True)
ml.addWidget(self.value_text, 1)
button_box = QDialogButtonBox(QDialogButtonBox.Ok)
button_box.accepted.connect(self.accept)
self.clear_button = button_box.addButton(_('Clear'), QDialogButtonBox.ResetRole)
self.clear_button.setIcon(get_icon('trash.png'))
self.clear_button.setToolTip(_('Clear all settings for this plugin'))
self.clear_button.clicked.connect(self._clear_settings)
if DEBUG:
self.edit_button = button_box.addButton(_('Edit'), QDialogButtonBox.ResetRole)
self.edit_button.setIcon(get_icon('edit_input.png'))
self.edit_button.setToolTip(_('Edit settings.'))
self.edit_button.clicked.connect(self._edit_settings)
self.save_button = button_box.addButton(_('Save'), QDialogButtonBox.ResetRole)
self.save_button.setIcon(get_icon('save.png'))
self.save_button.setToolTip(_('Save setting for this plugin'))
self.save_button.clicked.connect(self._save_settings)
self.save_button.setEnabled(False)
layout.addWidget(button_box)
def _populate_settings(self):
self.keys_list.clear()
ns_prefix = self._get_ns_prefix()
keys = sorted([k[len(ns_prefix):] for k in self.db.prefs.iterkeys()
if k.startswith(ns_prefix)])
for key in keys:
self.keys_list.addItem(key)
self.keys_list.setMinimumWidth(self.keys_list.sizeHintForColumn(0))
self.keys_list.currentRowChanged[int].connect(self._current_row_changed)
def _current_row_changed(self, new_row):
if new_row < 0:
self.value_text.clear()
return
key = unicode(self.keys_list.currentItem().text())
val = self.db.prefs.get_namespaced(self.namespace, key, '')
self.value_text.setPlainText(self.db.prefs.to_raw(val))
def _get_ns_prefix(self):
return 'namespaced:%s:'% self.namespace
def _edit_settings(self):
from calibre.gui2.dialogs.confirm_delete import confirm
message = '<p>' + _('Are you sure you want to edit settings in this library for this plugin?') + '</p>' \
+ '<p>' + _('The FanFicFare team does not support hand edited configurations.') + '</p>'
if confirm(message, self.namespace+'_edit_settings', self):
self.save_button.setEnabled(True)
self.edit_button.setEnabled(False)
self.value_text.setReadOnly(False)
def _save_settings(self):
from calibre.gui2.dialogs.confirm_delete import confirm
message = '<p>' + _('Are you sure you want to save this setting in this library for this plugin?') + '</p>' \
+ '<p>' + _('Any settings in other libraries or stored in a JSON file in your calibre plugins folder will not be touched.') + '</p>' \
+ '<p>' + _('You must restart calibre afterwards.') + '</p>'
if not confirm(message, self.namespace+'_save_settings', self):
return
ns_prefix = self._get_ns_prefix()
key = unicode(self.keys_list.currentItem().text())
self.db.prefs.set_namespaced(self.namespace, key,
self.db.prefs.raw_to_object(self.value_text.toPlainText()))
d = info_dialog(self, 'Settings saved',
'<p>' + _('All settings for this plugin in this library have been saved.') + '</p>' \
+ '<p>' + _('Please restart calibre now.') + '</p>',
show_copy_button=False)
b = d.bb.addButton(_('Restart calibre now'), d.bb.AcceptRole)
#.........这里部分代码省略.........
示例3: CalibreBookBrainzPluginDialog
# 需要导入模块: from PyQt5.Qt import QListWidget [as 别名]
# 或者: from PyQt5.Qt.QListWidget import addItem [as 别名]
class CalibreBookBrainzPluginDialog(QDialog):
def __init__(self, gui, icon, do_user_config):
QDialog.__init__(self, gui)
self.gui = gui
self.do_user_config = do_user_config
self.db = gui.current_db
self.l = QVBoxLayout()
self.setLayout(self.l)
self.header = QLabel(prefs['searchinbookbrainz'])
self.l.addWidget(self.header)
self.img = QLabel()
pixmap = QPixmap("images/BBt.svg")
self.img.setPixmap(pixmap)
self.l.addWidget(self.img)
# QCol = QColor()
# QCol.setRed(220)
# QCol.setGreen(255)
# QCol.setBlue(240)
self.setWindowTitle('Calibre Book Brainz Integration')
self.setWindowIcon(icon)
self.search_space = QLineEdit()
self.selected_button = QPushButton('Use title from selected book', self)
self.selected_button.clicked.connect(self.exporttitlefromselected)
self.l.addWidget(self.selected_button)
self.search_space = QLineEdit()
self.l.addWidget(self.search_space)
self.listWidget = QListWidget()
self.l.addWidget(self.listWidget)
self.searchExecutionButton = QPushButton('Search', self)
self.searchExecutionButton.clicked.connect(self.search)
self.l.addWidget(self.searchExecutionButton)
self.aboutButton = QPushButton('About', self)
self.aboutButton.clicked.connect(self.about)
self.l.addWidget(self.aboutButton)
self.resize(400, 600)
self.search_space.setFocus()
def exporttitlefromselected(self):
rows = self.gui.current_view().selectionModel().selectedRows()
if len(rows) == 0:
self.search_space.setText("")
else:
mi = self.gui.library_view.model().db.get_metadata(rows[0].row())
self.search_space.setText(mi.title)
def search(self):
text = self.search_space.text()
print(text)
self.listWidget.clear()
self.listWidget.setFocus()
try:
url = "https://bookbrainz.org/ws/search/?q=\"" + text + "\"&mode=\"search\""
hits = request_get(url)['hits']
except:
return
numQueries = len(hits)
act = 0
for i in range(numQueries):
enttype = hits[i]['_source']['_type']
if not enttype in ['Publication', 'Work', 'Edition']:
continue
print(hits[i])
item = QListWidgetItem("%i. %s BBID : %i" % ((act + 1), hits[i]['_source']['default_alias']['name'], 1))
Qcol = QColor()
if i % 2 == 0:
Qcol.setRed(240)
Qcol.setGreen(255)
Qcol.setBlue(255)
else:
Qcol.setRed(220)
Qcol.setGreen(255)
Qcol.setBlue(240)
item.setBackground(QBrush(Qcol))
self.listWidget.addItem(item)
act += 1
self.listWidget.setFocus()
self.searchExecutionButton.setFocus()
def about(self):
text = get_resources('about.txt')
QMessageBox.about(self, 'About the Calibre Book Brainz Plugin',
text.decode('utf-8'))
def config(self):
self.do_user_config(parent=self)
#.........这里部分代码省略.........
示例4: addItem
# 需要导入模块: from PyQt5.Qt import QListWidget [as 别名]
# 或者: from PyQt5.Qt.QListWidget import addItem [as 别名]
def addItem(self, *args):
try:
return QListWidget.addItem(self, *args)
finally:
self.mark_as_editable()
示例5: ManageKeysDialog
# 需要导入模块: from PyQt5.Qt import QListWidget [as 别名]
# 或者: from PyQt5.Qt.QListWidget import addItem [as 别名]
class ManageKeysDialog(QDialog):
def __init__(self, parent, key_type_name, plugin_keys, create_key, keyfile_ext = u"", wineprefix = None):
QDialog.__init__(self,parent)
self.parent = parent
self.key_type_name = key_type_name
self.plugin_keys = plugin_keys
self.create_key = create_key
self.keyfile_ext = keyfile_ext
self.import_key = (keyfile_ext != u"")
self.binary_file = (keyfile_ext == u"der")
self.json_file = (keyfile_ext == u"k4i")
self.android_file = (keyfile_ext == u"k4a")
self.wineprefix = wineprefix
self.setWindowTitle("{0} {1}: Manage {2}s".format(PLUGIN_NAME, PLUGIN_VERSION, self.key_type_name))
# Start Qt Gui dialog layout
layout = QVBoxLayout(self)
self.setLayout(layout)
help_layout = QHBoxLayout()
layout.addLayout(help_layout)
# Add hyperlink to a help file at the right. We will replace the correct name when it is clicked.
help_label = QLabel('<a href="http://www.foo.com/">Help</a>', self)
help_label.setTextInteractionFlags(Qt.LinksAccessibleByMouse | Qt.LinksAccessibleByKeyboard)
help_label.setAlignment(Qt.AlignRight)
help_label.linkActivated.connect(self.help_link_activated)
help_layout.addWidget(help_label)
keys_group_box = QGroupBox(_(u"{0}s".format(self.key_type_name)), self)
layout.addWidget(keys_group_box)
keys_group_box_layout = QHBoxLayout()
keys_group_box.setLayout(keys_group_box_layout)
self.listy = QListWidget(self)
self.listy.setToolTip(u"{0}s that will be used to decrypt ebooks".format(self.key_type_name))
self.listy.setSelectionMode(QAbstractItemView.SingleSelection)
self.populate_list()
keys_group_box_layout.addWidget(self.listy)
button_layout = QVBoxLayout()
keys_group_box_layout.addLayout(button_layout)
self._add_key_button = QtGui.QToolButton(self)
self._add_key_button.setIcon(QIcon(I('plus.png')))
self._add_key_button.setToolTip(u"Create new {0}".format(self.key_type_name))
self._add_key_button.clicked.connect(self.add_key)
button_layout.addWidget(self._add_key_button)
self._delete_key_button = QtGui.QToolButton(self)
self._delete_key_button.setToolTip(_(u"Delete highlighted key"))
self._delete_key_button.setIcon(QIcon(I('list_remove.png')))
self._delete_key_button.clicked.connect(self.delete_key)
button_layout.addWidget(self._delete_key_button)
if type(self.plugin_keys) == dict and self.import_key:
self._rename_key_button = QtGui.QToolButton(self)
self._rename_key_button.setToolTip(_(u"Rename highlighted key"))
self._rename_key_button.setIcon(QIcon(I('edit-select-all.png')))
self._rename_key_button.clicked.connect(self.rename_key)
button_layout.addWidget(self._rename_key_button)
self.export_key_button = QtGui.QToolButton(self)
self.export_key_button.setToolTip(u"Save highlighted key to a .{0} file".format(self.keyfile_ext))
self.export_key_button.setIcon(QIcon(I('save.png')))
self.export_key_button.clicked.connect(self.export_key)
button_layout.addWidget(self.export_key_button)
spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
button_layout.addItem(spacerItem)
if self.wineprefix is not None:
layout.addSpacing(5)
wineprefix_layout = QHBoxLayout()
layout.addLayout(wineprefix_layout)
wineprefix_layout.setAlignment(Qt.AlignCenter)
self.wp_label = QLabel(u"WINEPREFIX:")
wineprefix_layout.addWidget(self.wp_label)
self.wp_lineedit = QLineEdit(self)
wineprefix_layout.addWidget(self.wp_lineedit)
self.wp_label.setBuddy(self.wp_lineedit)
self.wp_lineedit.setText(self.wineprefix)
layout.addSpacing(5)
migrate_layout = QHBoxLayout()
layout.addLayout(migrate_layout)
if self.import_key:
migrate_layout.setAlignment(Qt.AlignJustify)
self.migrate_btn = QPushButton(u"Import Existing Keyfiles", self)
self.migrate_btn.setToolTip(u"Import *.{0} files (created using other tools).".format(self.keyfile_ext))
self.migrate_btn.clicked.connect(self.migrate_wrapper)
migrate_layout.addWidget(self.migrate_btn)
migrate_layout.addStretch()
self.button_box = QDialogButtonBox(QDialogButtonBox.Close)
self.button_box.rejected.connect(self.close)
migrate_layout.addWidget(self.button_box)
self.resize(self.sizeHint())
def getwineprefix(self):
if self.wineprefix is not None:
return unicode(self.wp_lineedit.text()).strip()
#.........这里部分代码省略.........
示例6: ChooseFormatDialog
# 需要导入模块: from PyQt5.Qt import QListWidget [as 别名]
# 或者: from PyQt5.Qt.QListWidget import addItem [as 别名]
class ChooseFormatDialog(QDialog):
def __init__(self, window, msg, formats, show_open_with=False):
QDialog.__init__(self, window)
self.resize(507, 377)
self.setWindowIcon(QIcon(I("mimetypes/unknown.png")))
self.setWindowTitle(_('Choose format'))
self.l = l = QVBoxLayout(self)
self.msg = QLabel(msg)
l.addWidget(self.msg)
self.formats = QListWidget(self)
self.formats.setIconSize(QSize(64, 64))
self.formats.activated[QModelIndex].connect(self.activated_slot)
l.addWidget(self.formats)
self.h = h = QHBoxLayout()
h.setContentsMargins(0, 0, 0, 0)
l.addLayout(h)
if show_open_with:
self.owb = QPushButton(_('&Open with...'), self)
self.formats.currentRowChanged.connect(self.update_open_with_button)
h.addWidget(self.owb)
self.own = QMenu(self.owb.text())
self.owb.setMenu(self.own)
self.own.aboutToShow.connect(self.populate_open_with)
self.buttonBox = bb = QDialogButtonBox(self)
bb.setStandardButtons(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
bb.accepted.connect(self.accept), bb.rejected.connect(self.reject)
h.addStretch(10), h.addWidget(self.buttonBox)
for format in formats:
self.formats.addItem(QListWidgetItem(file_icon_provider().icon_from_ext(format.lower()),
format.upper()))
self._formats = formats
self.formats.setCurrentRow(0)
self._format = self.open_with_format = None
if show_open_with:
self.populate_open_with()
self.update_open_with_button()
def populate_open_with(self):
from calibre.gui2.open_with import populate_menu, edit_programs
menu = self.own
menu.clear()
fmt = self._formats[self.formats.currentRow()]
def connect_action(ac, entry):
connect_lambda(ac.triggered, self, lambda self: self.open_with(entry))
populate_menu(menu, connect_action, fmt)
if len(menu.actions()) == 0:
menu.addAction(_('Open %s with...') % fmt.upper(), self.choose_open_with)
else:
menu.addSeparator()
menu.addAction(_('Add other application for %s files...') % fmt.upper(), self.choose_open_with)
menu.addAction(_('Edit "Open with" applications...'), partial(edit_programs, fmt, self))
def update_open_with_button(self):
fmt = self._formats[self.formats.currentRow()]
self.owb.setText(_('Open %s with...') % fmt)
def open_with(self, entry):
self.open_with_format = (self._formats[self.formats.currentRow()], entry)
self.accept()
def choose_open_with(self):
from calibre.gui2.open_with import choose_program
fmt = self._formats[self.formats.currentRow()]
entry = choose_program(fmt, self)
if entry is not None:
self.open_with(entry)
def book_converted(self, book_id, fmt):
fmt = fmt.upper()
if fmt not in self._formats:
self._formats.append(fmt)
self.formats.addItem(QListWidgetItem(
file_icon_provider().icon_from_ext(fmt.lower()), fmt.upper()))
def activated_slot(self, *args):
self.accept()
def format(self):
return self._format
def accept(self):
self._format = self._formats[self.formats.currentRow()]
return QDialog.accept(self)
示例7: ManageKeysDialog
# 需要导入模块: from PyQt5.Qt import QListWidget [as 别名]
# 或者: from PyQt5.Qt.QListWidget import addItem [as 别名]
class ManageKeysDialog(QDialog):
def __init__(self, parent, key_type_name, plugin_keys, create_key, keyfile_ext = u""):
QDialog.__init__(self,parent)
self.parent = parent
self.key_type_name = key_type_name
self.plugin_keys = plugin_keys
self.create_key = create_key
self.keyfile_ext = keyfile_ext
self.json_file = (keyfile_ext == u"k4i")
self.setWindowTitle("{0} {1}: Manage {2}s".format(PLUGIN_NAME, PLUGIN_VERSION, self.key_type_name))
# Start Qt Gui dialog layout
layout = QVBoxLayout(self)
self.setLayout(layout)
keys_group_box = QGroupBox(_(u"{0}s".format(self.key_type_name)), self)
layout.addWidget(keys_group_box)
keys_group_box_layout = QHBoxLayout()
keys_group_box.setLayout(keys_group_box_layout)
self.listy = QListWidget(self)
self.listy.setToolTip(u"{0}s that will be used to decrypt ebooks".format(self.key_type_name))
self.listy.setSelectionMode(QAbstractItemView.SingleSelection)
self.populate_list()
keys_group_box_layout.addWidget(self.listy)
button_layout = QVBoxLayout()
keys_group_box_layout.addLayout(button_layout)
self._add_key_button = QtGui.QToolButton(self)
self._add_key_button.setIcon(QIcon(I('plus.png')))
self._add_key_button.setToolTip(u"Create new {0}".format(self.key_type_name))
self._add_key_button.clicked.connect(self.add_key)
button_layout.addWidget(self._add_key_button)
self._delete_key_button = QtGui.QToolButton(self)
self._delete_key_button.setToolTip(_(u"Delete highlighted key"))
self._delete_key_button.setIcon(QIcon(I('list_remove.png')))
self._delete_key_button.clicked.connect(self.delete_key)
button_layout.addWidget(self._delete_key_button)
spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
button_layout.addItem(spacerItem)
layout.addSpacing(5)
migrate_layout = QHBoxLayout()
layout.addLayout(migrate_layout)
migrate_layout.addStretch()
self.button_box = QDialogButtonBox(QDialogButtonBox.Close)
self.button_box.rejected.connect(self.close)
migrate_layout.addWidget(self.button_box)
self.resize(self.sizeHint())
def populate_list(self):
if type(self.plugin_keys) == dict:
for key in self.plugin_keys.keys():
self.listy.addItem(QListWidgetItem(key))
else:
for key in self.plugin_keys:
self.listy.addItem(QListWidgetItem(key))
def add_key(self):
d = self.create_key(self)
d.exec_()
if d.result() != d.Accepted:
# New key generation cancelled.
return
new_key_value = d.key_value
if new_key_value in self.plugin_keys:
info_dialog(None, "{0} {1}: Duplicate {2}".format(PLUGIN_NAME, PLUGIN_VERSION,self.key_type_name),
u"This {0} is already in the list of {0}s has not been added.".format(self.key_type_name), show=True)
return
self.plugin_keys.append(d.key_value)
self.listy.clear()
self.populate_list()
def rename_key(self):
if not self.listy.currentItem():
errmsg = u"No {0} selected to rename. Highlight a keyfile first.".format(self.key_type_name)
r = error_dialog(None, "{0} {1}".format(PLUGIN_NAME, PLUGIN_VERSION),
_(errmsg), show=True, show_copy_button=False)
return
d = RenameKeyDialog(self)
d.exec_()
if d.result() != d.Accepted:
# rename cancelled or moot.
return
keyname = unicode(self.listy.currentItem().text())
if not question_dialog(self, "{0} {1}: Confirm Rename".format(PLUGIN_NAME, PLUGIN_VERSION), u"Do you really want to rename the {2} named <strong>{0}</strong> to <strong>{1}</strong>?".format(keyname,d.key_name,self.key_type_name), show_copy_button=False, default_yes=False):
return
self.plugin_keys[d.key_name] = self.plugin_keys[keyname]
del self.plugin_keys[keyname]
self.listy.clear()
self.populate_list()
#.........这里部分代码省略.........
示例8: MainDialog
# 需要导入模块: from PyQt5.Qt import QListWidget [as 别名]
# 或者: from PyQt5.Qt.QListWidget import addItem [as 别名]
#.........这里部分代码省略.........
cover = self.db.cover(book_id, index_is_id=True)
self.db.set_cover(new_book_id, cover)
# TODO aggiungere qui un test sul remove/add
self.gui.status_bar.show_message("Done adding ex libris to book %s/%s." % (counter, total), 60000)
except Exception as msg:
print(str(msg.args[0]))
self.gui.status_bar.show_message(str(msg.args[0]))
self.gui.library_view.model().refresh()
self.close()
def parseUserReplacementStrings(self, string):
toReturn = dict()
pairs = string.split(';')
for pair in pairs:
sep = pair.split('=')
if (len(sep) == 2):
key = sep[0].strip()
value = sep[1]
toReturn[key] = value
return toReturn
def populateSpineList(self, fileName):
try:
# create exlibris instance
inputEPUB = fileName
workingDirectory = PersistentTemporaryDirectory()
producer = exlibris(calibre=True)
producer.initialize(inputEPUB, inputEPUB, inputEPUB, '1', '1', None, workingDirectory, None, None, None, None)
# get spine list
spineList = producer.getSpineList()
pageDictionary = producer.getPageDictionary()
# add spine list to listbox
maxIndex = int(spineList[-1][0])
nod = len(str(maxIndex))
maxLen = 0
for l in spineList:
maxLen = max(maxLen, len(l[1]))
for l in spineList:
index = str(l[0]).zfill(nod)
idref = l[1]
pageFileName = pageDictionary.get(idref, 'UNKNOWN')
string = "%s %s (%s)" % (index, idref, pageFileName)
self.spine.addItem(string.decode('utf-8'))
self.spine.addItem("=== Insert as last element ===")
# remove tmp dir
producer.clean()
# update self.spine_max_index
self.spine_max_index = len(spineList) + 1
except Exception as msg:
self.gui.status_bar.show_message(str(msg.args[0]))
def populateTOCList(self, fileName):
try:
# create exlibris instance
inputEPUB = fileName
workingDirectory = PersistentTemporaryDirectory()
producer = exlibris(calibre=True)
producer.initialize(inputEPUB, inputEPUB, inputEPUB, '1', '1', None, workingDirectory, None, None, None, None)
# get spine list
tocList = producer.getTOCList()
pageDictionary = producer.getPageDictionary()
# add TOC list to listbox
maxIndex = int(tocList[-1][0])
nod = len(str(maxIndex))
maxLen = 0
for l in tocList:
maxLen = max(maxLen, len(l[1]))
for l in tocList:
index = str(l[0]).zfill(nod)
text = l[1]
spaces = " " + ("-" * (l[2] * 3)) + " "
string = "%s%s%s" % (index, spaces, text.ljust(maxLen))
self.toc.addItem(string.decode('utf-8'))
self.toc.addItem("=== Insert as last element ===")
# remove tmp dir
producer.clean()
# update self.toc_max_index
self.toc_max_index = len(tocList) + 1
except Exception as msg:
self.gui.status_bar.show_message(str(msg.args[0]))
示例9: ServicesQWidget
# 需要导入模块: from PyQt5.Qt import QListWidget [as 别名]
# 或者: from PyQt5.Qt.QListWidget import addItem [as 别名]
#.........这里部分代码省略.........
: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)
def add_filter_item(self, filter_item):
"""
Add filter item to QListWidget
:param filter_item: filter item (service)
:type filter_item: alignak_app.items.service.Service
"""
item = QListWidgetItem()
monitored = \
filter_item.data['passive_checks_enabled'] + filter_item.data['active_checks_enabled']
icon_name = get_icon_name(
filter_item.item_type,
filter_item.data['ls_state'],
filter_item.data['ls_acknowledged'],
filter_item.data['ls_downtimed'],
monitored
)
item.setData(Qt.DecorationRole, QIcon(settings.get_image(icon_name)))
item.setData(Qt.DisplayRole, filter_item.get_display_name())
item.setData(Qt.UserRole, filter_item.item_id)
item.setToolTip(filter_item.get_tooltip())
self.services_list_widget.addItem(item)
def update_widget(self, services):
"""
Update the QTreeWidget and its items
:param services: list of :class:`Services <alignak_app.items.service.Service>` items
:type services: list
示例10: ConfigWidget
# 需要导入模块: from PyQt5.Qt import QListWidget [as 别名]
# 或者: from PyQt5.Qt.QListWidget import addItem [as 别名]
#.........这里部分代码省略.........
self.l.addWidget(self.checkbox_include_guide_text, row, 0)
self.l.addWidget(self.label_include_guide_text, row, 1)
row += 1
self.l.addWidget(self.include_guide_text, row, 1)
row += 1
self.l.addWidget(QLabel(''), row, 1)
row += 1
self.label_include_toc_text = QLabel('Include in TOC with string:')
self.checkbox_include_toc_text = QCheckBox('', self)
self.checkbox_include_toc_text.setChecked(prefs['checkbox_include_toc_text'] == 'True')
self.include_toc_text = QLineEdit(self)
self.include_toc_text.setText(prefs['include_toc_text'])
self.l.addWidget(self.checkbox_include_toc_text, row, 0)
self.l.addWidget(self.label_include_toc_text, row, 1)
row += 1
self.l.addWidget(self.include_toc_text, row, 1)
row += 1
self.l.addWidget(QLabel(''), row, 1)
row += 1
self.label_ask_replace = QLabel('Ask before replacing book in library')
self.checkbox_ask_replace = QCheckBox('', self)
self.checkbox_ask_replace.setChecked(prefs['checkbox_ask_replace'] == 'True')
self.l.addWidget(self.checkbox_ask_replace, row, 0)
self.l.addWidget(self.label_ask_replace, row, 1)
row += 1
self.label_disable_first_last_only = QLabel('When multiple EPUB files are selected, allow insertion points other than "1", "first", and "last"')
self.checkbox_disable_first_last_only = QCheckBox('', self)
self.checkbox_disable_first_last_only.setChecked(prefs['checkbox_disable_first_last_only'] == 'True')
self.l.addWidget(self.checkbox_disable_first_last_only, row, 0)
self.l.addWidget(self.label_disable_first_last_only, row, 1)
row += 1
self.l.addWidget(QLabel(''), row, 1)
row += 1
self.label_replace_strings = QLabel('Replace strings:')
self.replace_strings = QTextEdit(self)
self.replace_strings.setText(prefs['replace_strings'])
self.label_supportedMetadata = QLabel('Supported metadata:')
self.supportedMetadata = QListWidget(self)
#QtCore.QObject.connect(self.supportedMetadata, QtCore.SIGNAL("doubleClicked()"), self.add_replace_string)
self.supportedMetadata.doubleClicked.connect(self.add_replace_string)
producer = exlibris()
tags = producer.getSupportedMetadataList()
for tag in tags:
self.supportedMetadata.addItem(tag.decode('utf-8'))
self.l.addWidget(self.label_replace_strings, row, 1)
self.l.addWidget(self.label_supportedMetadata, row, 2)
row += 1
self.l.addWidget(self.replace_strings, row, 1)
self.l.addWidget(self.supportedMetadata, row, 2)
row += 1
self.resize(self.sizeHint())
def add_replace_string(self):
currentText = str(self.replace_strings.toPlainText()).strip()
currentItem = self.supportedMetadata.currentItem().text()
self.replace_strings.setText("%s\n%s=your_value_goes_here;" % (currentText, currentItem))
def button_xhtml_filename_handler(self):
initial_dir = os.path.dirname(str(self.xhtml_filename.text()))
new_file = QFileDialog.getOpenFileName(self, "Select ex libris XHTML file", initial_dir, "XHTML Files (*.xhtml)")
if new_file:
new_file = new_file[0] if isinstance(new_file, tuple) else new_file
if new_file and os.path.exists(new_file):
self.xhtml_filename.setText(new_file)
def button_include_dir_handler(self):
initial_dir = os.path.dirname(str(self.include_dir.text()))
dirDialog = QFileDialog()
dirDialog.setFileMode(QFileDialog.Directory)
new_dir = dirDialog.getExistingDirectory(self, "Select directory", initial_dir)
if (len(new_dir) > 0):
self.include_dir.setText(new_dir)
def save_settings(self):
prefs['xhtml_filename'] = unicode(self.xhtml_filename.text())
prefs['include_dir'] = unicode(self.include_dir.text())
prefs['include_guide_text'] = unicode(self.include_guide_text.text())
prefs['include_toc_text'] = unicode(self.include_toc_text.text())
prefs['replace_strings'] = unicode(self.replace_strings.toPlainText())
prefs['checkbox_include_dir'] = unicode(self.checkbox_include_dir.isChecked())
prefs['checkbox_include_guide_text'] = unicode(self.checkbox_include_guide_text.isChecked())
prefs['checkbox_include_toc_text'] = unicode(self.checkbox_include_toc_text.isChecked())
prefs['checkbox_ask_replace'] = unicode(self.checkbox_ask_replace.isChecked())
prefs['checkbox_disable_first_last_only'] = unicode(self.checkbox_disable_first_last_only.isChecked())
# TODO: save value from main.py (?)
prefs['include_spine'] = u'1'
prefs['include_toc'] = u'1'
示例11: PrefsViewerDialog
# 需要导入模块: from PyQt5.Qt import QListWidget [as 别名]
# 或者: from PyQt5.Qt.QListWidget import addItem [as 别名]
class PrefsViewerDialog(SizePersistedDialog):
def __init__(self, gui, namespace):
SizePersistedDialog.__init__(self, gui, 'Prefs Viewer dialog')
self.setWindowTitle('Preferences for: '+namespace)
self.gui = gui
self.db = gui.current_db
self.namespace = namespace
self._init_controls()
self.resize_dialog()
self._populate_settings()
if self.keys_list.count():
self.keys_list.setCurrentRow(0)
def _init_controls(self):
layout = QVBoxLayout(self)
self.setLayout(layout)
ml = QHBoxLayout()
layout.addLayout(ml, 1)
self.keys_list = QListWidget(self)
self.keys_list.setSelectionMode(QAbstractItemView.SingleSelection)
self.keys_list.setFixedWidth(150)
self.keys_list.setAlternatingRowColors(True)
ml.addWidget(self.keys_list)
self.value_text = QTextEdit(self)
self.value_text.setTabStopWidth(24)
self.value_text.setReadOnly(False)
ml.addWidget(self.value_text, 1)
button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
button_box.accepted.connect(self._apply_changes)
button_box.rejected.connect(self.reject)
self.clear_button = button_box.addButton('Clear', QDialogButtonBox.ResetRole)
self.clear_button.setIcon(get_icon('trash.png'))
self.clear_button.setToolTip('Clear all settings for this plugin')
self.clear_button.clicked.connect(self._clear_settings)
layout.addWidget(button_box)
def _populate_settings(self):
self.keys_list.clear()
ns_prefix = self._get_ns_prefix()
keys = sorted([k[len(ns_prefix):] for k in self.db.prefs.iterkeys()
if k.startswith(ns_prefix)])
for key in keys:
self.keys_list.addItem(key)
self.keys_list.setMinimumWidth(self.keys_list.sizeHintForColumn(0))
self.keys_list.currentRowChanged[int].connect(self._current_row_changed)
def _current_row_changed(self, new_row):
if new_row < 0:
self.value_text.clear()
return
key = unicode(self.keys_list.currentItem().text())
val = self.db.prefs.get_namespaced(self.namespace, key, '')
self.value_text.setPlainText(self.db.prefs.to_raw(val))
def _get_ns_prefix(self):
return 'namespaced:%s:'% self.namespace
def _apply_changes(self):
from calibre.gui2.dialogs.confirm_delete import confirm
message = '<p>Are you sure you want to change your settings in this library for this plugin?</p>' \
'<p>Any settings in other libraries or stored in a JSON file in your calibre plugins ' \
'folder will not be touched.</p>' \
'<p>You must restart calibre afterwards.</p>'
if not confirm(message, self.namespace+'_clear_settings', self):
return
val = self.db.prefs.raw_to_object(unicode(self.value_text.toPlainText()))
key = unicode(self.keys_list.currentItem().text())
self.db.prefs.set_namespaced(self.namespace, key, val)
restart = prompt_for_restart(self, 'Settings changed',
'<p>Settings for this plugin in this library have been changed.</p>'
'<p>Please restart calibre now.</p>')
self.close()
if restart:
self.gui.quit(restart=True)
def _clear_settings(self):
from calibre.gui2.dialogs.confirm_delete import confirm
message = '<p>Are you sure you want to clear your settings in this library for this plugin?</p>' \
'<p>Any settings in other libraries or stored in a JSON file in your calibre plugins ' \
'folder will not be touched.</p>' \
'<p>You must restart calibre afterwards.</p>'
if not confirm(message, self.namespace+'_clear_settings', self):
return
ns_prefix = self._get_ns_prefix()
keys = [k for k in self.db.prefs.iterkeys() if k.startswith(ns_prefix)]
for k in keys:
del self.db.prefs[k]
self._populate_settings()
restart = prompt_for_restart(self, 'Settings deleted',
'<p>All settings for this plugin in this library have been cleared.</p>'
#.........这里部分代码省略.........
示例12: SavedSearchEditor
# 需要导入模块: from PyQt5.Qt import QListWidget [as 别名]
# 或者: from PyQt5.Qt.QListWidget import addItem [as 别名]
class SavedSearchEditor(Dialog):
def __init__(self, parent, initial_search=None):
self.initial_search = initial_search
Dialog.__init__(
self, _('Manage saved searches'), 'manage-saved-searches', parent)
def setup_ui(self):
from calibre.gui2.ui import get_gui
db = get_gui().current_db
self.l = l = QVBoxLayout(self)
b = self.bb.addButton(_('&Add search'), self.bb.ActionRole)
b.setIcon(QIcon(I('plus.png')))
b.clicked.connect(self.add_search)
b = self.bb.addButton(_('&Remove search'), self.bb.ActionRole)
b.setIcon(QIcon(I('minus.png')))
b.clicked.connect(self.del_search)
b = self.bb.addButton(_('&Edit search'), self.bb.ActionRole)
b.setIcon(QIcon(I('modified.png')))
b.clicked.connect(self.edit_search)
self.slist = QListWidget(self)
self.slist.setStyleSheet('QListView::item { padding: 3px }')
self.slist.activated.connect(self.edit_search)
self.slist.setAlternatingRowColors(True)
self.searches = {name: db.saved_search_lookup(name) for name in db.saved_search_names()}
self.populate_search_list()
if self.initial_search is not None and self.initial_search in self.searches:
self.select_search(self.initial_search)
elif self.searches:
self.slist.setCurrentRow(0)
self.slist.currentItemChanged.connect(self.current_index_changed)
l.addWidget(self.slist)
self.desc = la = QLabel('\xa0')
la.setWordWrap(True)
l.addWidget(la)
l.addWidget(self.bb)
self.current_index_changed(self.slist.currentItem())
self.setMinimumHeight(500)
self.setMinimumWidth(600)
@property
def current_search_name(self):
i = self.slist.currentItem()
if i is not None:
ans = i.text()
if ans in self.searches:
return ans
def populate_search_list(self):
self.slist.clear()
for name in sorted(self.searches.keys(), key=sort_key):
self.slist.addItem(name)
def add_search(self):
d = AddSavedSearch(parent=self, commit_changes=False)
if d.exec_() != d.Accepted:
return
name, expression = d.accepted_data
nmap = {icu_lower(n):n for n in self.searches}
if icu_lower(name) in nmap:
q = nmap[icu_lower(name)]
del self.searches[q]
self.select_search(q)
self.slist.takeItem(self.slist.currentRow())
self.searches[name] = expression
self.slist.insertItem(0, name)
self.slist.setCurrentRow(0)
self.current_index_changed(self.slist.currentItem())
def del_search(self):
n = self.current_search_name
if n is not None:
if not confirm(
'<p>' + _(
'The current saved search will be '
'<b>permanently deleted</b>. Are you sure?') + '</p>',
'saved_search_editor_delete', self):
return
self.slist.takeItem(self.slist.currentRow())
del self.searches[n]
def edit_search(self):
n = self.current_search_name
if not n:
return
d = AddSavedSearch(parent=self, commit_changes=False, label=_('Edit the name and/or expression below.'), validate=self.validate_edit)
d.setWindowTitle(_('Edit saved search'))
d.sname.setText(n)
d.search.setText(self.searches[n])
if d.exec_() != d.Accepted:
return
name, expression = d.accepted_data
self.slist.currentItem().setText(name)
del self.searches[n]
self.searches[name] = expression
#.........这里部分代码省略.........