本文整理汇总了Python中PyQt4.Qt.QPushButton.setEnabled方法的典型用法代码示例。如果您正苦于以下问题:Python QPushButton.setEnabled方法的具体用法?Python QPushButton.setEnabled怎么用?Python QPushButton.setEnabled使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt4.Qt.QPushButton
的用法示例。
在下文中一共展示了QPushButton.setEnabled方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: SelectTagsDialog
# 需要导入模块: from PyQt4.Qt import QPushButton [as 别名]
# 或者: from PyQt4.Qt.QPushButton import setEnabled [as 别名]
class SelectTagsDialog(QDialog):
def __init__(self, parent, modal=True, flags=Qt.WindowFlags(), caption="Select Tags", ok_button="Select"):
QDialog.__init__(self, parent, flags)
self.setModal(modal)
self.setWindowTitle(caption)
lo = QVBoxLayout(self)
lo.setMargin(10)
lo.setSpacing(5)
# tag selector
self.wtagsel = QListWidget(self)
lo.addWidget(self.wtagsel)
# self.wtagsel.setColumnMode(QListBox.FitToWidth)
self.wtagsel.setSelectionMode(QListWidget.MultiSelection)
QObject.connect(self.wtagsel, SIGNAL("itemSelectionChanged()"), self._check_tag)
# buttons
lo.addSpacing(10)
lo2 = QHBoxLayout()
lo.addLayout(lo2)
lo2.setContentsMargins(0, 0, 0, 0)
lo2.setMargin(5)
self.wokbtn = QPushButton(ok_button, self)
self.wokbtn.setMinimumWidth(128)
QObject.connect(self.wokbtn, SIGNAL("clicked()"), self.accept)
self.wokbtn.setEnabled(False)
cancelbtn = QPushButton("Cancel", self)
cancelbtn.setMinimumWidth(128)
QObject.connect(cancelbtn, SIGNAL("clicked()"), self.reject)
lo2.addWidget(self.wokbtn)
lo2.addStretch(1)
lo2.addWidget(cancelbtn)
self.setMinimumWidth(384)
self._tagnames = []
def setTags(self, tagnames):
self._tagnames = tagnames
self.wtagsel.clear()
self.wtagsel.insertItems(0, list(tagnames))
def _check_tag(self):
for i in range(len(self._tagnames)):
if self.wtagsel.item(i).isSelected():
self.wokbtn.setEnabled(True)
return
else:
self.wokbtn.setEnabled(False)
def getSelectedTags(self):
return [tag for i, tag in enumerate(self._tagnames) if self.wtagsel.item(i).isSelected()]
示例2: TweakBook
# 需要导入模块: from PyQt4.Qt import QPushButton [as 别名]
# 或者: from PyQt4.Qt.QPushButton import setEnabled [as 别名]
class TweakBook(QDialog):
def __init__(self, parent, book_id, fmts, db):
QDialog.__init__(self, parent)
self.book_id, self.fmts, self.db_ref = book_id, fmts, weakref.ref(db)
self._exploded = None
self._cleanup_dirs = []
self._cleanup_files = []
self.setup_ui()
self.setWindowTitle(_('Tweak Book') + ' - ' + db.title(book_id,
index_is_id=True))
button = self.fmt_choice_buttons[0]
button_map = {unicode(x.text()):x for x in self.fmt_choice_buttons}
of = prefs['output_format'].upper()
df = tweaks.get('default_tweak_format', None)
lf = gprefs.get('last_tweak_format', None)
if df and df.lower() == 'remember' and lf in button_map:
button = button_map[lf]
elif df and df.upper() in button_map:
button = button_map[df.upper()]
elif of in button_map:
button = button_map[of]
button.setChecked(True)
self.init_state()
for button in self.fmt_choice_buttons:
button.toggled.connect(self.init_state)
def init_state(self, *args):
self._exploded = None
self.preview_button.setEnabled(False)
self.rebuild_button.setEnabled(False)
self.explode_button.setEnabled(True)
def setup_ui(self): # {{{
self._g = g = QHBoxLayout(self)
self.setLayout(g)
self._l = l = QVBoxLayout()
g.addLayout(l)
fmts = sorted(x.upper() for x in self.fmts)
self.fmt_choice_box = QGroupBox(_('Choose the format to tweak:'), self)
self._fl = fl = QHBoxLayout()
self.fmt_choice_box.setLayout(self._fl)
self.fmt_choice_buttons = [QRadioButton(y, self) for y in fmts]
for x in self.fmt_choice_buttons:
fl.addWidget(x, stretch=10 if x is self.fmt_choice_buttons[-1] else
0)
l.addWidget(self.fmt_choice_box)
self.fmt_choice_box.setVisible(len(fmts) > 1)
self.help_label = QLabel(_('''\
<h2>About Tweak Book</h2>
<p>Tweak Book allows you to fine tune the appearance of an ebook by
making small changes to its internals. In order to use Tweak Book,
you need to know a little bit about HTML and CSS, technologies that
are used in ebooks. Follow the steps:</p>
<br>
<ol>
<li>Click "Explode Book": This will "explode" the book into its
individual internal components.<br></li>
<li>Right click on any individual file and select "Open with..." to
edit it in your favorite text editor.<br></li>
<li>When you are done Tweaking: <b>close the file browser window
and the editor windows you used to make your tweaks</b>. Then click
the "Rebuild Book" button, to update the book in your calibre
library.</li>
</ol>'''))
self.help_label.setWordWrap(True)
self._fr = QFrame()
self._fr.setFrameShape(QFrame.VLine)
g.addWidget(self._fr)
g.addWidget(self.help_label)
self._b = b = QGridLayout()
left, top, right, bottom = b.getContentsMargins()
top += top
b.setContentsMargins(left, top, right, bottom)
l.addLayout(b, stretch=10)
self.explode_button = QPushButton(QIcon(I('wizard.png')), _('&Explode Book'))
self.preview_button = QPushButton(QIcon(I('view.png')), _('&Preview Book'))
self.cancel_button = QPushButton(QIcon(I('window-close.png')), _('&Cancel'))
self.rebuild_button = QPushButton(QIcon(I('exec.png')), _('&Rebuild Book'))
self.explode_button.setToolTip(
_('Explode the book to edit its components'))
self.preview_button.setToolTip(
_('Preview the result of your tweaks'))
self.cancel_button.setToolTip(
_('Abort without saving any changes'))
self.rebuild_button.setToolTip(
_('Save your changes and update the book in the calibre library'))
a = b.addWidget
a(self.explode_button, 0, 0, 1, 1)
a(self.preview_button, 0, 1, 1, 1)
a(self.cancel_button, 1, 0, 1, 1)
#.........这里部分代码省略.........
示例3: MyBlockingBusy
# 需要导入模块: from PyQt4.Qt import QPushButton [as 别名]
# 或者: from PyQt4.Qt.QPushButton import setEnabled [as 别名]
class MyBlockingBusy(QDialog):
NORMAL = 0
REQUESTED = 1
ACKNOWLEDGED = 2
def __init__(self, gui, msg, size=100, window_title="Marvin XD", show_cancel=False, on_top=False):
flags = Qt.FramelessWindowHint
if on_top:
flags = Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint
QDialog.__init__(self, gui, flags)
self._layout = QVBoxLayout()
self.setLayout(self._layout)
self.cancel_status = 0
self.is_running = False
# Add the spinner
self.pi = ProgressIndicator(self)
self.pi.setDisplaySize(size)
self._layout.addSpacing(15)
self._layout.addWidget(self.pi, 0, Qt.AlignHCenter)
self._layout.addSpacing(15)
# Fiddle with the message
self.msg = QLabel(msg)
# self.msg.setWordWrap(True)
self.font = QFont()
self.font.setPointSize(self.font.pointSize() + 2)
self.msg.setFont(self.font)
self._layout.addWidget(self.msg, 0, Qt.AlignHCenter)
sp = QSizePolicy()
sp.setHorizontalStretch(True)
sp.setVerticalStretch(False)
sp.setHeightForWidth(False)
self.msg.setSizePolicy(sp)
self.msg.setMinimumHeight(self.font.pointSize() + 8)
self._layout.addSpacing(15)
if show_cancel:
self.bb = QDialogButtonBox()
self.cancel_button = QPushButton(QIcon(I("window-close.png")), "Cancel")
self.bb.addButton(self.cancel_button, self.bb.RejectRole)
self.bb.clicked.connect(self.button_handler)
self._layout.addWidget(self.bb)
self.setWindowTitle(window_title)
self.resize(self.sizeHint())
def accept(self):
self.stop()
return QDialog.accept(self)
def button_handler(self, button):
"""
Only change cancel_status from NORMAL to REQUESTED
"""
if self.bb.buttonRole(button) == QDialogButtonBox.RejectRole:
if self.cancel_status == self.NORMAL:
self.cancel_status = self.REQUESTED
self.cancel_button.setEnabled(False)
def reject(self):
"""
Cannot cancel this dialog manually
"""
pass
def set_text(self, text):
self.msg.setText(text)
def start(self):
self.is_running = True
self.pi.startAnimation()
def stop(self):
self.is_running = False
self.pi.stopAnimation()
示例4: DownloadDialog
# 需要导入模块: from PyQt4.Qt import QPushButton [as 别名]
# 或者: from PyQt4.Qt.QPushButton import setEnabled [as 别名]
class DownloadDialog(QDialog):
def __init__(self, gui, icon, do_user_config):
QDialog.__init__(self, gui)
self.gui = gui
self.do_user_config = do_user_config
# The current database shown in the GUI
self.db = gui.current_db
self.prefs = PrefsFacade(self.db)
self.version = Downloader.version
# The GUI, created and layouted by hand...
self.layout = QVBoxLayout()
self.setLayout(self.layout)
self.setWindowTitle('Beam EBooks Downloader')
self.setWindowIcon(icon)
self.log_area = QTextEdit('Log output', self)
self.log_area.setReadOnly(True)
self.log_area.setLineWrapMode(QTextEdit.NoWrap);
self.log_area.setText("")
self.layout.addWidget(self.log_area)
self.download_button = QPushButton('Download books', self)
self.download_button.clicked.connect(self.download)
self.layout.addWidget(self.download_button)
self.conf_button = QPushButton('Configure this plugin', self)
self.conf_button.clicked.connect(self.config)
self.layout.addWidget(self.conf_button)
self.resize(self.sizeHint())
def config(self):
self.do_user_config(parent=self)
# Apply the changes
# Not necessary, the downloader will obtain fresh config anyway...
# self.label.setText(prefs['hello_world_msg'])
def notify(self, message = None):
if message is not None:
# insertPlainText inserts at the beginning of the log area...
self.log_area.append(message)
sb = self.log_area.verticalScrollBar()
sb.setValue(sb.maximum())
def download(self):
prefs = self.prefs
self.download_button.setEnabled(False)
self.conf_button.setEnabled(False)
downloader = BeamEbooksDownloader(self.prefs, self.version, caller = self)
self.notify("Downloader is: %s" % (downloader))
# Loop over all accounts until we have support for selection
for account_id in prefs[prefs.ACCOUNTS]:
account = prefs[prefs.ACCOUNTS][account_id]
account[prefs.ACCOUNT_ID] = account_id
if account[prefs.ENABLED]:
self.enqueue(account, downloader)
self.hide()
def enqueue(self, account, downloader):
prefs = self.prefs
self.notify("Account: '%s'" % account[prefs.USERNAME])
# downloader.login(account)
func = 'arbitrary_n'
# func = 'arbitrary'
cpus = self.gui.job_manager.server.pool_size
print "CPUs: %s" % (cpus)
args = ['calibre_plugins.beam_ebooks_downloader.jobs', 'do_obtain_new_books', (cpus, account)]
desc = 'Beam EBooks Downloader'
job = self.gui.job_manager.run_job(Dispatcher(self._done), func, args=args, description=desc)
print "Job: %s" % (job)
self.notify(" Start parsing OPDS catalog")
# if downloader.successful_login == False:
# self.notify("Failed to log in...")
# else:
# self.notify("Scanning (beam) private library now...")
# downloader.recursive_descent(norms(prefs[prefs.URLBASE]))
def _done(self, job):
print "Done Downloading"
print "Self: %s" % (self)
print "Job: %s" % (job)
#.........这里部分代码省略.........
示例5: MetadataSingleDialogBase
# 需要导入模块: from PyQt4.Qt import QPushButton [as 别名]
# 或者: from PyQt4.Qt.QPushButton import setEnabled [as 别名]
#.........这里部分代码省略.........
_('Could not change the on disk location of this'
' book. Is it open in another program?'),
det_msg=p+traceback.format_exc(), show=True)
return False
raise
for widget in getattr(self, 'custom_metadata_widgets', []):
self.books_to_refresh |= widget.commit(self.book_id)
self.db.commit()
rows = self.db.refresh_ids(list(self.books_to_refresh))
if rows:
self.rows_to_refresh |= set(rows)
return True
def accept(self):
self.save_state()
if not self.apply_changes():
return
ResizableDialog.accept(self)
def reject(self):
self.save_state()
ResizableDialog.reject(self)
def save_state(self):
try:
gprefs['metasingle_window_geometry3'] = bytearray(self.saveGeometry())
except:
# Weird failure, see https://bugs.launchpad.net/bugs/995271
import traceback
traceback.print_exc()
# Dialog use methods {{{
def start(self, row_list, current_row, view_slot=None,
set_current_callback=None):
self.row_list = row_list
self.current_row = current_row
if view_slot is not None:
self.view_format.connect(view_slot)
self.set_current_callback = set_current_callback
self.do_one(apply_changes=False)
ret = self.exec_()
self.break_cycles()
return ret
def next_clicked(self):
if not self.apply_changes():
return
self.do_one(delta=1, apply_changes=False)
def prev_clicked(self):
if not self.apply_changes():
return
self.do_one(delta=-1, apply_changes=False)
def do_one(self, delta=0, apply_changes=True):
if apply_changes:
self.apply_changes()
self.current_row += delta
prev = next_ = None
if self.current_row > 0:
prev = self.db.title(self.row_list[self.current_row-1])
if self.current_row < len(self.row_list) - 1:
next_ = self.db.title(self.row_list[self.current_row+1])
if next_ is not None:
tip = (_('Save changes and edit the metadata of %s')+
' [Alt+Right]')%next_
self.next_button.setToolTip(tip)
self.next_button.setEnabled(next_ is not None)
if prev is not None:
tip = (_('Save changes and edit the metadata of %s')+
' [Alt+Left]')%prev
self.prev_button.setToolTip(tip)
self.prev_button.setEnabled(prev is not None)
self.button_box.button(self.button_box.Ok).setDefault(True)
self.button_box.button(self.button_box.Ok).setFocus(Qt.OtherFocusReason)
self(self.db.id(self.row_list[self.current_row]))
def break_cycles(self):
# Break any reference cycles that could prevent python
# from garbage collecting this dialog
self.set_current_callback = self.db = None
def disconnect(signal):
try:
signal.disconnect()
except:
pass # Fails if view format was never connected
disconnect(self.view_format)
for b in ('next_button', 'prev_button'):
x = getattr(self, b, None)
if x is not None:
disconnect(x.clicked)
for widget in self.basic_metadata_widgets:
bc = getattr(widget, 'break_cycles', None)
if bc is not None and callable(bc):
bc()
for widget in getattr(self, 'custom_metadata_widgets', []):
widget.break_cycles()
示例6: BookInfo
# 需要导入模块: from PyQt4.Qt import QPushButton [as 别名]
# 或者: from PyQt4.Qt.QPushButton import setEnabled [as 别名]
#.........这里部分代码省略.........
self.closed.emit(self)
return ret
def cover_changed(self, data):
if self.current_row is not None:
id_ = self.view.model().id(self.current_row)
self.view.model().db.set_cover(id_, data)
if self.gui.cover_flow:
self.gui.cover_flow.dataChanged()
ci = self.view.currentIndex()
if ci.isValid():
self.view.model().current_changed(ci, ci)
self.cover_pixmap = QPixmap()
self.cover_pixmap.loadFromData(data)
if self.fit_cover.isChecked():
self.resize_cover()
def details_size_hint(self):
return QSize(350, 550)
def toggle_cover_fit(self, state):
gprefs.set('book_info_dialog_fit_cover', self.fit_cover.isChecked())
self.resize_cover()
def cover_view_resized(self, event):
QTimer.singleShot(1, self.resize_cover)
def slave(self, current, previous):
if current.row() != previous.row():
row = current.row()
self.refresh(row)
def move(self, delta=1):
self.view.selectionModel().currentChanged.disconnect(self.slave)
try:
idx = self.view.currentIndex()
if idx.isValid():
m = self.view.model()
ni = m.index(idx.row() + delta, idx.column())
if ni.isValid():
self.view.setCurrentIndex(ni)
self.refresh(ni.row())
if self.view.isVisible():
self.view.scrollTo(ni)
finally:
self.view.selectionModel().currentChanged.connect(self.slave)
def next(self):
self.move()
def previous(self):
self.move(-1)
def resize_cover(self):
if self.cover_pixmap is None:
return
pixmap = self.cover_pixmap
if self.fit_cover.isChecked():
scaled, new_width, new_height = fit_image(pixmap.width(),
pixmap.height(), self.cover.size().width()-10,
self.cover.size().height()-10)
if scaled:
pixmap = pixmap.scaled(new_width, new_height,
Qt.KeepAspectRatio, Qt.SmoothTransformation)
self.cover.set_pixmap(pixmap)
self.update_cover_tooltip()
def update_cover_tooltip(self):
tt = ''
if self.marked:
tt = _('This book is marked') if self.marked in {True, 'true'} else _(
'This book is marked as: %s') % self.marked
tt += '\n\n'
if self.cover_pixmap is not None:
sz = self.cover_pixmap.size()
tt += _('Cover size: %(width)d x %(height)d')%dict(width=sz.width(), height=sz.height())
self.cover.setToolTip(tt)
def refresh(self, row):
if isinstance(row, QModelIndex):
row = row.row()
if row == self.current_row:
return
mi = self.view.model().get_book_display_info(row)
if mi is None:
# Indicates books was deleted from library, or row numbers have
# changed
return
self.previous_button.setEnabled(False if row == 0 else True)
self.next_button.setEnabled(False if row == self.view.model().rowCount(QModelIndex())-1 else True)
self.current_row = row
self.setWindowTitle(mi.title)
self.cover_pixmap = QPixmap.fromImage(mi.cover_data[1])
self.resize_cover()
html = render_html(mi, self.css, True, self, all_fields=True)
self.details.setHtml(html)
self.marked = mi.marked
self.cover.setBackgroundBrush(self.marked_brush if mi.marked else self.normal_brush)
self.update_cover_tooltip()
示例7: MakeBrickDialog
# 需要导入模块: from PyQt4.Qt import QPushButton [as 别名]
# 或者: from PyQt4.Qt.QPushButton import setEnabled [as 别名]
class MakeBrickDialog(QDialog):
def __init__(self, parent, modal=True, flags=Qt.WindowFlags()):
QDialog.__init__(self, parent, flags)
self.setModal(modal)
self.setWindowTitle("Convert sources to FITS brick")
lo = QVBoxLayout(self)
lo.setMargin(10)
lo.setSpacing(5)
# file selector
self.wfile = FileSelector(self, label="FITS filename:", dialog_label="Output FITS file", default_suffix="fits",
file_types="FITS files (*.fits *.FITS)", file_mode=QFileDialog.ExistingFile)
lo.addWidget(self.wfile)
# reference frequency
lo1 = QHBoxLayout()
lo.addLayout(lo1)
lo1.setContentsMargins(0, 0, 0, 0)
label = QLabel("Frequency, MHz:", self)
lo1.addWidget(label)
tip = """<P>If your sky model contains spectral information (such as spectral indices), then a brick may be generated
for a specific frequency. If a frequency is not specified here, the reference frequency of the model sources will be assumed.</P>"""
self.wfreq = QLineEdit(self)
self.wfreq.setValidator(QDoubleValidator(self))
label.setToolTip(tip)
self.wfreq.setToolTip(tip)
lo1.addWidget(self.wfreq)
# beam gain
lo1 = QHBoxLayout()
lo.addLayout(lo1)
lo1.setContentsMargins(0, 0, 0, 0)
self.wpb_apply = QCheckBox("Apply primary beam expression:", self)
self.wpb_apply.setChecked(True)
lo1.addWidget(self.wpb_apply)
tip = """<P>If this option is specified, a primary power beam gain will be applied to the sources before inserting
them into the brick. This can be any valid Python expression making use of the variables 'r' (corresponding
to distance from field centre, in radians) and 'fq' (corresponding to frequency.)</P>"""
self.wpb_exp = QLineEdit(self)
self.wpb_apply.setToolTip(tip)
self.wpb_exp.setToolTip(tip)
lo1.addWidget(self.wpb_exp)
# overwrite or add mode
lo1 = QHBoxLayout()
lo.addLayout(lo1)
lo1.setContentsMargins(0, 0, 0, 0)
self.woverwrite = QRadioButton("overwrite image", self)
self.woverwrite.setChecked(True)
lo1.addWidget(self.woverwrite)
self.waddinto = QRadioButton("add into image", self)
lo1.addWidget(self.waddinto)
# add to model
self.wadd = QCheckBox("Add resulting brick to sky model as a FITS image component", self)
lo.addWidget(self.wadd)
lo1 = QHBoxLayout()
lo.addLayout(lo1)
lo1.setContentsMargins(0, 0, 0, 0)
self.wpad = QLineEdit(self)
self.wpad.setValidator(QDoubleValidator(self))
self.wpad.setText("1.1")
lab = QLabel("...with padding factor:", self)
lab.setToolTip("""<P>The padding factor determines the amount of null padding inserted around the image during
the prediction stage. Padding alleviates the effects of tapering and detapering in the uv-brick, which can show
up towards the edges of the image. For a factor of N, the image will be padded out to N times its original size.
This increases memory use, so if you have no flux at the edges of the image anyway, then a pad factor of 1 is
perfectly fine.</P>""")
self.wpad.setToolTip(lab.toolTip())
QObject.connect(self.wadd, SIGNAL("toggled(bool)"), self.wpad.setEnabled)
QObject.connect(self.wadd, SIGNAL("toggled(bool)"), lab.setEnabled)
self.wpad.setEnabled(False)
lab.setEnabled(False)
lo1.addStretch(1)
lo1.addWidget(lab, 0)
lo1.addWidget(self.wpad, 1)
self.wdel = QCheckBox("Remove from the sky model sources that go into the brick", self)
lo.addWidget(self.wdel)
# OK/cancel buttons
lo.addSpacing(10)
lo2 = QHBoxLayout()
lo.addLayout(lo2)
lo2.setContentsMargins(0, 0, 0, 0)
lo2.setMargin(5)
self.wokbtn = QPushButton("OK", self)
self.wokbtn.setMinimumWidth(128)
QObject.connect(self.wokbtn, SIGNAL("clicked()"), self.accept)
self.wokbtn.setEnabled(False)
cancelbtn = QPushButton("Cancel", self)
cancelbtn.setMinimumWidth(128)
QObject.connect(cancelbtn, SIGNAL("clicked()"), self.reject)
lo2.addWidget(self.wokbtn)
lo2.addStretch(1)
lo2.addWidget(cancelbtn)
self.setMinimumWidth(384)
# signals
QObject.connect(self.wfile, SIGNAL("filenameSelected"), self._fileSelected)
# internal state
self.qerrmsg = QErrorMessage(self)
def setModel(self, model):
self.model = model
pb = self.model.primaryBeam()
if pb:
self.wpb_exp.setText(pb)
#.........这里部分代码省略.........
示例8: TwitterGui
# 需要导入模块: from PyQt4.Qt import QPushButton [as 别名]
# 或者: from PyQt4.Qt.QPushButton import setEnabled [as 别名]
class TwitterGui(QWidget):
URL_REGEX = re.compile(r'''((?:mailto:|ftp://|http://|https://)[^ <>'"{}|\\^`[\]]*)''')
def __init__(self, parent, logger, db_conn, update_func, safe_conn):
super(TwitterGui, self).__init__(parent)
self._db_conn = db_conn
self.logger = logger
self._reply_to_id = 0
self._update_func = update_func
self._list = None
if get_settings().get_proxy():
u = urlparse.urlsplit(get_settings().get_proxy())
proxy = QNetworkProxy()
proxy.setType(QNetworkProxy.HttpProxy)
proxy.setHostName(u.hostname);
proxy.setPort(u.port)
QNetworkProxy.setApplicationProxy(proxy);
self.msgview = QWebView(self)
self.msgview.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
self.msgview.linkClicked.connect(self.link_clicked)
self.userCombo = QComboBox(self)
self.userCombo.setEditable(True)
self.userCombo.activated.connect(self.toggle_user_in_list)
self.showButton = QPushButton(chr(94), self)
self.showButton.setMaximumHeight(13)
self.showButton.clicked.connect(self.show_hide_animation)
self.post_field = QTextEdit(self)
self.post_field.setMaximumHeight(50)
self.post_field.textChanged.connect(self.text_changed)
self.send_button = QPushButton("Post", self)
self.send_button.clicked.connect(self.post_status_clicked)
self.refresh_button = QPushButton("Refresh", self)
self.refresh_button.clicked.connect(self._update_func)
self.attach_button = QPushButton("Attach", self)
self.attach_button.clicked.connect(lambda _ : self.set_status("Attach something"))
self.lists_box = QComboBox(self)
self.lists_box.currentIndexChanged.connect(self.list_changed)
self.lists_box.setEditable(False)
self.lists_box.addItems([u"Home"] + self._db_conn.get_lists())
self.statusLabel = QLabel("Status", self)
self.charCounter = QLabel("0", self)
self.gridw = QWidget(self)
self.gridw.setContentsMargins(0, 0, 0, 0)
gridlay = QGridLayout(self.gridw)
gridlay.setContentsMargins(0, 0, 0, 0)
gridlay.addWidget(self.post_field, 0, 0, 2, 1)
gridlay.addWidget(self.attach_button, 0, 1, 1, 1)
gridlay.addWidget(self.send_button, 1, 1, 1, 1)
gridlay.addWidget(self.lists_box, 0, 2, 1, 1)
gridlay.addWidget(self.refresh_button, 1, 2, 1, 1)
gridlay.addWidget(self.statusLabel, 2, 0, 1, 1)
gridlay.addWidget(self.charCounter, 2, 1, 1, 2)
hlay = QVBoxLayout(self)
hlay.addWidget(self.msgview)
hlay.addWidget(self.userCombo)
hlay.addWidget(self.showButton)
hlay.addWidget(self.gridw)
safe_conn.connect_home_timeline_updated(self.update_view)
safe_conn.connect_twitter_loop_started(self.start_refresh_animation)
safe_conn.connect_twitter_loop_stopped(self.stop_refresh_animation)
safe_conn.connect_update_posted(self.enable_posting)
safe_conn.connect_range_limit_exceeded(lambda _ : self.set_status("Range limit exceeded"))
safe_conn.connect_not_authenticated(lambda _ : self.set_status("Authentication failed"))
self.gridw.hide()
self.update_view()
self.set_status("Twitter plugin initialized")
def enable_posting(self, q_id, m_id):
if m_id>1:
self.post_field.setText("")
self.set_status("Tweet posted")
else:
self.set_status("Failed to post tweet, Error: " + str(abs(m_id)))
self.post_field.setEnabled(True)
def link_clicked(self, url):
if not url.host():
if url.hasQueryItem("reply-to") and url.hasQueryItem("screen-name"):
self._reply_to_id = long(convert_string(url.queryItemValue("reply-to")))
self.post_field.setPlainText("@"+convert_string(url.queryItemValue("screen-name"))+" ")
self.set_status("Reply to @"+convert_string(url.queryItemValue("screen-name")))
else:
self.logger.error("Unknown command from link: "+str(url.toString()))
else:
webbrowser.open(str(url.toString()))
def list_changed(self, list_idx):
if list_idx:
self._list = convert_string(self.lists_box.currentText())
#.........这里部分代码省略.........
示例9: PluginObject
# 需要导入模块: from PyQt4.Qt import QPushButton [as 别名]
# 或者: from PyQt4.Qt.QPushButton import setEnabled [as 别名]
class PluginObject(object):
tabName = 'Pass Phrase Finder'
maxVersion = '0.93.99'
#############################################################################
def __init__(self, main):
self.searchThread = None
self.passPhraseFinder = None
self.isSearchOver = False
def updateResults(resultStr):
self.resultStr += resultStr
def updateDisplay():
if len(self.resultStr) > 0:
self.resultsDisplay.append(self.resultStr)
self.resultStr = ''
self.resultsDisplay.moveCursor(QtGui.QTextCursor.End)
self.resultsDisplay.repaint()
if self.isSearchOver:
endSearch()
# Call this from another thread to end the search
def terminateSearch():
self.isSearchOver = True
# Call this from the main thread to end the search
def endSearch():
self.main.extraHeartbeatAlways.remove(updateDisplay)
self.searchButton.setEnabled(True)
self.stopButton.setEnabled(False)
# If the thread is still searching tell the pass phrase finder to stop
if self.passPhraseFinder and self.searchThread and not self.searchThread.isFinished():
self.passPhraseFinder.isStopped = True
def searchForPassphrase():
# Get the selected wallet from the main screen
wlt = self.getSelectedWlt()
if wlt and not wlt.watchingOnly and wlt.isLocked:
self.resultStr = ''
self.passPhraseFinder = PassPhraseFinder(wlt)
self.resultsDisplay.setText(QString(''))
self.main.extraHeartbeatAlways.append(updateDisplay)
if len(self.segOrdStrSet) > 0:
# From self.segOrdStrList, create a list of lists of indexes that describe the segment orderings to search
# In other words convert all of the strings in orderings list to lists of integers
segOrdIntListList = []
for ordStr in self.segOrdStrSet:
# The indexes provided by the users are 1 based, and the list indexes ought to be 0 based
segOrdIntListList.append([int(indexStr)-1 for indexStr in ordStr.split(',')])
self.searchThread = PyBackgroundThread(self.passPhraseFinder.searchForPassPhrase,
[segDef.getSegList() for segDef in self.segDefList],
segOrdIntListList,
updateResults,
terminateSearch )
# Reset the isSearchOver flag
self.isSearchOver = False
self.searchThread.start()
# Disable search button adn enabled stop button
self.stopButton.setEnabled(True)
self.searchButton.setEnabled(False)
else:
QMessageBox.warning(self.main, tr('Invalid'), tr("""
There are no valid segment combinations to search.
Please add at least one segment and ordering to search."""), QMessageBox.Ok)
else:
QMessageBox.warning(self.main, tr('Invalid'), tr("""
No valid wallet is selected. Please select a locked
non-watching-only from Available Wallets."""), QMessageBox.Ok)
def addKnownSegment():
dlgEnterSegment = DlgEnterSegment(main, main)
if dlgEnterSegment.exec_():
segmentText = str(dlgEnterSegment.editSegment.text())
if len(segmentText)>0:
self.segDefList.append(KnownSeg(segmentText))
self.segDefTableModel.updateSegList(self.segDefList)
def addUnknownCaseSegment():
dlgEnterSegment = DlgEnterSegment(main, main)
if dlgEnterSegment.exec_():
segmentText = str(dlgEnterSegment.editSegment.text())
if len(segmentText)>0:
self.segDefList.append(UnknownCaseSeg(segmentText))
self.segDefTableModel.updateSegList(self.segDefList)
def addUnknownOrderSegment():
dlgEnterSegment = DlgEnterSegment(main, main, isUnknownOrder=True)
if dlgEnterSegment.exec_():
segmentText = str(dlgEnterSegment.editSegment.text())
minLen = int(str(dlgEnterSegment.minSelector.currentText()))
maxLen = int(str(dlgEnterSegment.maxSelector.currentText()))
if len(segmentText)>0:
self.segDefList.append(UnknownSeg(segmentText, minLen, maxLen))
self.segDefTableModel.updateSegList(self.segDefList)
def addOrdering():
if len(self.segDefList) > 0:
#.........这里部分代码省略.........
示例10: MendeleyDialog
# 需要导入模块: from PyQt4.Qt import QPushButton [as 别名]
# 或者: from PyQt4.Qt.QPushButton import setEnabled [as 别名]
class MendeleyDialog(QDialog):
showErrorSignal = pyqtSignal(object, object)
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.layout = QVBoxLayout()
self.setLayout(self.layout)
self.setWindowTitle('Mendeley Plugin')
self.setWindowIcon(icon)
self.setMinimumWidth(500)
self.resize(self.sizeHint())
self.startImportButton = QPushButton('Import documents from \'calibre\' Mendeley folder.')
self.startImportButton.clicked.connect(self.startImport)
self.layout.addWidget(self.startImportButton)
self.helpl = QLabel('\n')
self.helpl.setWordWrap(True)
self.layout.addWidget(self.helpl)
self.layout.setSizeConstraint(QLayout.SetFixedSize)
plugin_prefs = JSONConfig('plugins/Mendeley')
if not plugin_prefs.has_key('account') or not plugin_prefs.has_key('verification'):
from calibre_plugins.mendeley_to_calibre import config as ConfigWidget
dialog = ConfigWidget.ConfigWidget('plugin_option')
dialog.add_ok_cancel_buttons()
dialog.exec_()
self.showErrorSignal.connect(self.show_dialog, type=Qt.QueuedConnection)
def add_document(self,document):
from calibre.ebooks.metadata import MetaInformation
mi = MetaInformation('', [_('Unknown')])
mi.title = document['title']
mi.authors = document['authors']
mi.tags = ["Mendeley"]
mendeley_id = {}
mendeley_id['mendeley'] = document['mendeley_id']
mi.identifiers = mendeley_id
mi.series_index = 1 # needed?
self.db.add_books([document['path']], ['pdf'], [mi], False, True)
os.remove(document['path'])
def show_dialog(self, title, body):
self.close()
QMessageBox.warning(self, title, body)
def startImport(self):
from pprint import pprint
plugin_prefs = JSONConfig('plugins/Mendeley')
job = ThreadedJob('Mendeley_importer',
'Importing Mendeley Documents',
func=do_work,
args=(),
kwargs={},
callback=self.importer_finished)
self.gui.job_manager.run_threaded_job(job)
self.startImportButton.setEnabled(False)
self.helpl.setText('Importing documents. You can close the dialog. See the progress in the Calibre jobs (see the Status Bar).')
def importer_finished(self,job):
if job.failed:
return self.gui.job_exception(job, dialog_title='Failed to download Mendeley documents')
else:
documents = job.result
if documents == []:
self.showErrorSignal.emit('No documents found', "Mendeley 'calibre' folder not found or it's empty. The plugin only fetches documents from the folder called 'calibre' (or 'Calibre') from Mendeley.\n\nReminder: you need to press Sync in Mendeley Desktop after adding documents there.")
return
for document in documents:
self.add_document(document)
self.close()
def about(self):
QMessageBox.about(self, 'About', 'Some text here')
示例11: PluginObject
# 需要导入模块: from PyQt4.Qt import QPushButton [as 别名]
# 或者: from PyQt4.Qt.QPushButton import setEnabled [as 别名]
class PluginObject(object):
tabName = 'Dust-B-Gone'
maxVersion = '0.93.99'
#############################################################################
def __init__(self, main):
def updateDustLimit():
try:
self.dustTableModel.updateDustList(self.getSelectedWlt(),
str2coin(self.dustLimitText.text()))
self.beGoneDustButton.setEnabled(len(self.dustTableModel.dustTxOutlist)>0)
if self.dustTableModel.wlt:
self.lblHeader.setText(tr("""<b>Dust Outputs for Wallet: %s</b>"""
% self.dustTableModel.wlt.labelName))
except NegativeValueError:
pass
except TooMuchPrecisionError:
pass
except:
LOGEXCEPT("Unexpected exception")
pass
def sendDust():
try:
utxiList = []
for utxo in self.dustTableModel.dustTxOutlist:
# The PyCreateAndSignTx method require PyTx and PyBtcAddress objects
rawTx = TheBDM.getTxByHash(utxo.getTxHash()).serialize()
a160 = CheckHash160(utxo.getRecipientScrAddr())
for pyAddr in self.dustTableModel.wlt.addrMap.values():
if a160 == pyAddr.getAddr160():
pubKey = pyAddr.binPublicKey65.toBinStr()
txoIdx = utxo.getTxOutIndex()
utxiList.append(UnsignedTxInput(rawTx, txoIdx, None, pubKey))
break
# Make copies, destroy them in the finally clause
privKeyMap = {}
for addrObj in self.dustTableModel.wlt.addrMap.values():
scrAddr = SCRADDR_P2PKH_BYTE + addrObj.getAddr160()
if self.dustTableModel.wlt.useEncryption and self.dustTableModel.wlt.isLocked:
# Target wallet is encrypted...
unlockdlg = DlgUnlockWallet(self.dustTableModel.wlt,
self.main, self.main, 'Unlock Wallet to Import')
if not unlockdlg.exec_():
QMessageBox.critical(self, 'Wallet is Locked', \
'Cannot send dust without unlocking the wallet!', \
QMessageBox.Ok)
return
privKeyMap[scrAddr] = addrObj.binPrivKey32_Plain.copy()
signedTx = PyCreateAndSignTx(utxiList,
[],
privKeyMap, SIGHASH_NONE|SIGHASH_ANYONECANPAY )
print "-------------"
print binary_to_hex(signedTx.serialize())
# sock = socket.create_connection(('dust-b-gone.bitcoin.petertodd.org',80))
# sock.send(signedTx.serialize())
# sock.send(b'\n')
# sock.close()
except socket.error as err:
QMessageBox.critical(self.main, tr('Negative Value'), tr("""
Failed to connect to dust-b-gone server: %s""" % err.strerror), QMessageBox.Ok)
except NegativeValueError:
QMessageBox.critical(self.main, tr('Negative Value'), tr("""
You must enter a positive value of at least 0.0000 0001
and less than %s for the dust limit.""" % MAX_DUST_LIMIT_STR), QMessageBox.Ok)
except TooMuchPrecisionError:
QMessageBox.critical(self.main.main, tr('Too much precision'), tr("""
Bitcoins can only be specified down to 8 decimal places.
The smallest unit of a Groestlcoin is 0.0000 0001 GRS.
Please enter a dust limit of at least 0.0000 0001 and less than %s.""" % MAX_DUST_LIMIT_STR), QMessageBox.Ok)
finally:
for scraddr in privKeyMap:
privKeyMap[scraddr].destroy()
self.main = main
self.lblHeader = QRichLabel(tr("""<b>Dust Outputs for Wallet: None Selected</b>"""), doWrap=False)
self.beGoneDustButton = QPushButton("Remove Dust")
self.beGoneDustButton.setEnabled(False)
self.main.connect(self.beGoneDustButton, SIGNAL('clicked()'), sendDust)
topRow = makeHorizFrame([self.lblHeader,'stretch'])
secondRow = makeHorizFrame([self.beGoneDustButton, 'stretch'])
self.dustLimitLabel = QLabel("Max Dust Value (GRS): ")
self.dustLimitText = QLineEdit()
self.dustLimitText.setFont(GETFONT('Fixed'))
self.dustLimitText.setMinimumWidth(tightSizeNChar(self.dustLimitText, 6)[0])
self.dustLimitText.setMaximumWidth(tightSizeNChar(self.dustLimitText, 12)[0])
self.dustLimitText.setAlignment(Qt.AlignRight)
self.dustLimitText.setText(coin2str(DEFAULT_DUST_LIMIT))
self.main.connect(self.dustLimitText, SIGNAL('textChanged(QString)'), updateDustLimit)
#.........这里部分代码省略.........
示例12: MainWindow
# 需要导入模块: from PyQt4.Qt import QPushButton [as 别名]
# 或者: from PyQt4.Qt.QPushButton import setEnabled [as 别名]
#.........这里部分代码省略.........
## Directories toolbar
dirs_tb = QToolBar(self.wdirframe)
dirs_tb.setToolButtonStyle(Qt.ToolButtonIconOnly)
dirs_tb.setIconSize(QSize(16, 16))
self.dirs_lo.addWidget(dirs_tb)
label = QLabel("Monitoring directories:", dirs_tb)
self._dirs_tip = """<P>PURR can monitor your working directories for new or updated files. If there's a checkmark
next to the directory name in this list, PURR is monitoring it.</P>
<P>If the checkmark is grey, PURR is monitoring things unobtrusively. When a new or updated file is detected in he monitored directory,
it is quietly added to the list of files in the "New entry" window, even if this window is not currently visible.</P>
<P>If the checkmark is black, PURR will be more obtrusive. Whenever a new or updated file is detected, the "New entry" window will
pop up automatically. This is called "pouncing", and some people find it annoying.</P>
"""
label.setToolTip(self._dirs_tip)
label.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Minimum)
dirs_tb.addWidget(label)
# add directory list widget
self.wdirlist = DirectoryListWidget(self.wdirframe)
self.wdirlist.setToolTip(self._dirs_tip)
QObject.connect(self.wdirlist, SIGNAL("directoryStateChanged"), self._changeWatchedDirState)
self.dirs_lo.addWidget(self.wdirlist)
# self.wdirlist.setMaximumSize(1000000,64)
# add directory button
add = dirs_tb.addAction(pixmaps.list_add.icon(), "Add", self._showAddDirectoryDialog)
add.setToolTip("<P>Click to add another directory to be monitored.</P>")
# remove directory button
delbtn = dirs_tb.addAction(pixmaps.list_remove.icon(), "Remove", self.wdirlist.removeCurrent)
delbtn.setEnabled(False)
delbtn.setToolTip("<P>Click to removed the currently selected directory from the list.</P>")
QObject.connect(self.wdirlist, SIGNAL("hasSelection"), delbtn.setEnabled)
# # qa = dirs_tb.addAction(pixmaps.blue_round_reload.icon(),"Rescan",self._forceRescan)
# # qa.setToolTip("Click to rescan the directories for any new or updated files.")
# self.wshownew = QCheckBox("show new files",dirs_tb)
# dirs_tb.addWidget(self.wshownew)
# self.wshownew.setCheckState(Qt.Checked)
# self.wshownew.setToolTip("""<P>If this is checked, the "New entry" window will pop up automatically whenever
# new or updated files are detected. If this is unchecked, the files will be added to the window quietly
# and unobtrusively; you can show the window manually by clicking on the "New entry..." button below.</P>""")
# self._dir_entries = {}
cwlo.addSpacing(5)
wlogframe = QFrame(cw)
cwlo.addWidget(wlogframe)
log_lo = QVBoxLayout(wlogframe)
log_lo.setMargin(5)
log_lo.setContentsMargins(5, 5, 5, 5)
log_lo.setSpacing(0)
wlogframe.setFrameStyle(QFrame.Box | QFrame.Raised)
wlogframe.setLineWidth(1)
# listview of log entries
self.etw = LogEntryTree(cw)
log_lo.addWidget(self.etw, 1)
self.etw.header().setDefaultSectionSize(128)
self.etw.header().setMovable(False)
self.etw.setHeaderLabels(["date", "entry title", "comment"])
if hasattr(QHeaderView, 'ResizeToContents'):
self.etw.header().setResizeMode(0, QHeaderView.ResizeToContents)
示例13: AddTagDialog
# 需要导入模块: from PyQt4.Qt import QPushButton [as 别名]
# 或者: from PyQt4.Qt.QPushButton import setEnabled [as 别名]
class AddTagDialog(QDialog):
def __init__(self, parent, modal=True, flags=Qt.WindowFlags()):
QDialog.__init__(self, parent, flags)
self.setModal(modal)
self.setWindowTitle("Add Tag")
lo = QVBoxLayout(self)
lo.setMargin(10)
lo.setSpacing(5)
# tag selector
lo1 = QHBoxLayout()
lo.addLayout(lo1)
lo1.setSpacing(5)
self.wtagsel = QComboBox(self)
self.wtagsel.setEditable(True)
wtagsel_lbl = QLabel("&Tag:", self)
wtagsel_lbl.setBuddy(self.wtagsel)
lo1.addWidget(wtagsel_lbl, 0)
lo1.addWidget(self.wtagsel, 1)
QObject.connect(self.wtagsel, SIGNAL("activated(int)"), self._check_tag)
QObject.connect(self.wtagsel, SIGNAL("editTextChanged(const QString &)"), self._check_tag_text)
# value editor
self.valedit = ValueTypeEditor(self)
lo.addWidget(self.valedit)
# buttons
lo.addSpacing(10)
lo2 = QHBoxLayout()
lo.addLayout(lo2)
lo2.setContentsMargins(0, 0, 0, 0)
lo2.setMargin(5)
self.wokbtn = QPushButton("OK", self)
self.wokbtn.setMinimumWidth(128)
QObject.connect(self.wokbtn, SIGNAL("clicked()"), self.accept)
self.wokbtn.setEnabled(False)
cancelbtn = QPushButton("Cancel", self)
cancelbtn.setMinimumWidth(128)
QObject.connect(cancelbtn, SIGNAL("clicked()"), self.reject)
lo2.addWidget(self.wokbtn)
lo2.addStretch(1)
lo2.addWidget(cancelbtn)
self.setMinimumWidth(384)
def setTags(self, tagnames):
self.wtagsel.clear()
self.wtagsel.addItems(list(tagnames))
self.wtagsel.addItem("")
self.wtagsel.setCurrentIndex(len(tagnames))
def setValue(self, value):
self.valedit.setValue(value)
def _check_tag(self, tag):
self.wokbtn.setEnabled(True)
def _check_tag_text(self, text):
self.wokbtn.setEnabled(bool(str(text) != ""))
def accept(self):
"""When dialog is accepted with a default (bool) tag type,
check if the user hasn't entered a name=value entry in the tag name field.
This is a common mistake, and should be treated as a shortcut for setting string tags."""
if isinstance(self.valedit.getValue(), bool):
tagval = str(self.wtagsel.currentText()).split("=", 1)
if len(tagval) > 1:
# print tagval
if QMessageBox.warning(self,
"Set a string tag instead?", """<P>You have included an "=" sign in the tag name.
Perhaps you actually mean to set tag "%s" to the string value "%s"?</P>""" % tuple(tagval),
QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) == QMessageBox.No:
return
self.wtagsel.setEditText(tagval[0])
self.valedit.setValue(tagval[1])
return QDialog.accept(self)
def getTag(self):
return str(self.wtagsel.currentText()), self.valedit.getValue()
示例14: ExportKarmaDialog
# 需要导入模块: from PyQt4.Qt import QPushButton [as 别名]
# 或者: from PyQt4.Qt.QPushButton import setEnabled [as 别名]
class ExportKarmaDialog(QDialog):
def __init__(self, parent, modal=True, flags=Qt.WindowFlags()):
QDialog.__init__(self, parent, flags)
self.setModal(modal)
self.setWindowTitle("Export Karma annotations")
lo = QVBoxLayout(self)
lo.setMargin(10)
lo.setSpacing(5)
# file selector
self.wfile = FileSelector(self, label="Filename:", dialog_label="Karma annotations filename",
default_suffix="ann", file_types="Karma annotations (*.ann)")
lo.addWidget(self.wfile)
# selected sources checkbox
self.wsel = QCheckBox("selected sources only", self)
lo.addWidget(self.wsel)
# OK/cancel buttons
lo.addSpacing(10)
lo2 = QHBoxLayout()
lo.addLayout(lo2)
lo2.setContentsMargins(0, 0, 0, 0)
lo2.setMargin(5)
self.wokbtn = QPushButton("OK", self)
self.wokbtn.setMinimumWidth(128)
QObject.connect(self.wokbtn, SIGNAL("clicked()"), self.accept)
self.wokbtn.setEnabled(False)
cancelbtn = QPushButton("Cancel", self)
cancelbtn.setMinimumWidth(128)
QObject.connect(cancelbtn, SIGNAL("clicked()"), self.reject)
lo2.addWidget(self.wokbtn)
lo2.addStretch(1)
lo2.addWidget(cancelbtn)
self.setMinimumWidth(384)
# signals
QObject.connect(self.wfile, SIGNAL("valid"), self.wokbtn.setEnabled)
# internal state
self.qerrmsg = QErrorMessage(self)
self._model_filename = None
def setModel(self, model):
self.model = model
# set the default annotations filename, whenever a new model filename is set
filename = self.model.filename()
if filename and filename != self._model_filename:
self._model_filename = filename
self.wfile.setFilename(os.path.splitext(filename)[0] + ".ann")
def accept(self):
"""Tries to export annotations, and closes the dialog if successful."""
try:
filename = self.wfile.filename()
if os.path.exists(filename) and QMessageBox.question(self, "Exporting Karma annotations",
"<P>Overwrite the file %s?</P>" % filename,
QMessageBox.Yes | QMessageBox.No,
QMessageBox.Yes) != QMessageBox.Yes:
return
f = file(self.wfile.filename(), "wt")
f.write('COORD W\nPA STANDARD\nCOLOR GREEN\nFONT hershey12\n')
# source list
if self.wsel.isChecked():
sources = [src for src in self.model.sources if src.selected]
else:
sources = self.model.sources
# calculate basis size for crosses (TODO: replace min_size with something more sensible, as this value is in degrees)
brightnesses = [abs(src.brightness()) for src in sources if src.brightness() != 0]
min_bright = brightnesses and min(brightnesses)
min_size = 0.01
# loop over sources
busy = BusyIndicator()
for src in sources:
ra = src.pos.ra / DEG
dec = src.pos.dec / DEG
# figure out source size
if src.brightness() and min_bright:
ysize = (math.log10(abs(src.brightness())) - math.log10(min_bright) + 1) * min_size
else:
ysize = min_size
xsize = ysize / (math.cos(src.pos.dec) or 1)
# figure out source style
style, label = self.model.getSourcePlotStyle(src)
if style:
f.write('# %s\n' % src.name)
# write symbol for source
f.write('COLOR %s\n' % style.symbol_color)
if style.symbol == "plus":
f.write('CROSS %.12f %.12f %f %f\n' % (ra, dec, xsize, ysize))
elif style.symbol == "cross":
f.write('CROSS %.12f %.12f %f %f 45\n' % (ra, dec, ysize, ysize))
elif style.symbol == "circle":
f.write('CIRCLE %.12f %.12f %f\n' % (ra, dec, ysize))
elif style.symbol == "dot":
f.write('DOT %.12f %.12f\n' % (ra, dec))
elif style.symbol == "square":
f.write('CBOX %.12f %.12f %f %f\n' % (ra, dec, xsize, ysize))
elif style.symbol == "diamond":
f.write('CBOX %.12f %.12f %f %f 45\n' % (ra, dec, xsize, ysize))
# write label
if label:
f.write('FONT hershey%d\n' % (style.label_size * 2))
f.write('COLOR %s\n' % style.label_color)
f.write('TEXT %.12f %.12f %s\n' % (ra, dec, label))
#.........这里部分代码省略.........
示例15: CheckLibraryDialog
# 需要导入模块: from PyQt4.Qt import QPushButton [as 别名]
# 或者: from PyQt4.Qt.QPushButton import setEnabled [as 别名]
#.........这里部分代码省略.........
checking the fixable box and pushing this button will tell calibre that
there is no cover for all of the books listed. Use this option if you
are not going to restore the covers from a backup. In the case of extra
cover files, checking the fixable box and pushing this button will tell
calibre that the cover files it found are correct for all the books
listed. Use this when you are not going to delete the file(s). In the
case of missing formats, checking the fixable box and pushing this
button will tell calibre that the formats are really gone. Use this if
you are not going to restore the formats from a backup.</p>
'''))
self.log = QTreeWidget(self)
self.log.itemChanged.connect(self.item_changed)
self.log.itemExpanded.connect(self.item_expanded_or_collapsed)
self.log.itemCollapsed.connect(self.item_expanded_or_collapsed)
self._layout.addWidget(self.log)
self.check_button = QPushButton(_('&Run the check again'))
self.check_button.setDefault(False)
self.check_button.clicked.connect(self.run_the_check)
self.copy_button = QPushButton(_('Copy &to clipboard'))
self.copy_button.setDefault(False)
self.copy_button.clicked.connect(self.copy_to_clipboard)
self.ok_button = QPushButton(_('&Done'))
self.ok_button.setDefault(True)
self.ok_button.clicked.connect(self.accept)
self.delete_button = QPushButton(_('Delete &marked'))
self.delete_button.setToolTip(_('Delete marked files (checked subitems)'))
self.delete_button.setDefault(False)
self.delete_button.clicked.connect(self.delete_marked)
self.fix_button = QPushButton(_('&Fix marked'))
self.fix_button.setDefault(False)
self.fix_button.setEnabled(False)
self.fix_button.setToolTip(_('Fix marked sections (checked fixable items)'))
self.fix_button.clicked.connect(self.fix_items)
self.bbox = QDialogButtonBox(self)
self.bbox.addButton(self.check_button, QDialogButtonBox.ActionRole)
self.bbox.addButton(self.delete_button, QDialogButtonBox.ActionRole)
self.bbox.addButton(self.fix_button, QDialogButtonBox.ActionRole)
self.bbox.addButton(self.copy_button, QDialogButtonBox.ActionRole)
self.bbox.addButton(self.ok_button, QDialogButtonBox.AcceptRole)
h = QHBoxLayout()
ln = QLabel(_('Names to ignore:'))
h.addWidget(ln)
self.name_ignores = QLineEdit()
self.name_ignores.setText(db.prefs.get('check_library_ignore_names', ''))
self.name_ignores.setToolTip(
_('Enter comma-separated standard file name wildcards, such as synctoy*.dat'))
ln.setBuddy(self.name_ignores)
h.addWidget(self.name_ignores)
le = QLabel(_('Extensions to ignore'))
h.addWidget(le)
self.ext_ignores = QLineEdit()
self.ext_ignores.setText(db.prefs.get('check_library_ignore_extensions', ''))
self.ext_ignores.setToolTip(
_('Enter comma-separated extensions without a leading dot. Used only in book folders'))
le.setBuddy(self.ext_ignores)
h.addWidget(self.ext_ignores)
self._layout.addLayout(h)
self._layout.addWidget(self.bbox)
self.resize(950, 500)
self.bbox.setEnabled(True)