Use the new PyQt scoped enums

This commit is contained in:
Kovid Goyal 2020-12-03 09:17:37 +05:30
parent c420493507
commit 5c9e597fb3
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
256 changed files with 2706 additions and 2706 deletions

View File

@ -141,7 +141,7 @@ class Plugin(object): # {{{
geom = gprefs.get(prefname, None)
config_dialog = QDialog(parent)
button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
v = QVBoxLayout(config_dialog)
def size_dialog():
@ -171,7 +171,7 @@ class Plugin(object): # {{{
size_dialog()
config_dialog.exec_()
if config_dialog.result() == QDialog.Accepted:
if config_dialog.result() == QDialog.DialogCode.Accepted:
if hasattr(config_widget, 'validate'):
if config_widget.validate():
self.save_settings(config_widget)
@ -183,7 +183,7 @@ class Plugin(object): # {{{
help_text = self.customization_help(gui=True)
help_text = QLabel(help_text, config_dialog)
help_text.setWordWrap(True)
help_text.setTextInteractionFlags(Qt.LinksAccessibleByMouse | Qt.LinksAccessibleByKeyboard)
help_text.setTextInteractionFlags(Qt.TextInteractionFlag.LinksAccessibleByMouse | Qt.TextInteractionFlag.LinksAccessibleByKeyboard)
help_text.setOpenExternalLinks(True)
v.addWidget(help_text)
sc = plugin_customization(self)
@ -196,7 +196,7 @@ class Plugin(object): # {{{
size_dialog()
config_dialog.exec_()
if config_dialog.result() == QDialog.Accepted:
if config_dialog.result() == QDialog.DialogCode.Accepted:
sc = unicode_type(sc.text()).strip()
customize_plugin(self, sc)

View File

@ -663,7 +663,7 @@ if __name__ == '__main__':
d.l = QVBoxLayout()
d.setLayout(d.l)
d.l.addWidget(cw)
bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel)
d.l.addWidget(bb)
bb.accepted.connect(d.accept)
bb.rejected.connect(d.reject)

View File

@ -154,7 +154,7 @@ class PDFOutput(OutputFormatPlugin):
from calibre.constants import FAKE_PROTOCOL
scheme = QWebEngineUrlScheme(FAKE_PROTOCOL.encode('ascii'))
scheme.setSyntax(QWebEngineUrlScheme.Syntax.Host)
scheme.setFlags(QWebEngineUrlScheme.SecureScheme)
scheme.setFlags(QWebEngineUrlScheme.Flag.SecureScheme)
QWebEngineUrlScheme.registerScheme(scheme)
must_use_qt()
self.input_fmt = input_fmt

View File

@ -111,7 +111,7 @@ def parse_text_formatting(text):
for tag, start, length in chain(ranges, open_ranges):
fmt = QTextCharFormat()
if tag in {'b', 'strong'}:
fmt.setFontWeight(QFont.Bold)
fmt.setFontWeight(QFont.Weight.Bold)
elif tag in {'i', 'em'}:
fmt.setFontItalic(True)
else:
@ -128,7 +128,7 @@ def parse_text_formatting(text):
class Block(object):
def __init__(self, text='', width=0, font=None, img=None, max_height=100, align=Qt.AlignCenter):
def __init__(self, text='', width=0, font=None, img=None, max_height=100, align=Qt.AlignmentFlag.AlignCenter):
self.layouts = []
self._position = Point(0, 0)
self.leading = self.line_spacing = 0
@ -141,7 +141,7 @@ class Block(object):
l = QTextLayout(unescape_formatting(text), font, img)
l.setAdditionalFormats(formats)
to = QTextOption(align)
to.setWrapMode(QTextOption.WrapAtWordBoundaryOrAnywhere)
to.setWrapMode(QTextOption.WrapMode.WrapAtWordBoundaryOrAnywhere)
l.setTextOption(to)
l.beginLayout()
@ -191,7 +191,7 @@ class Block(object):
if hasattr(l, 'draw'):
# Etch effect for the text
painter.save()
painter.setRenderHints(QPainter.TextAntialiasing | QPainter.Antialiasing)
painter.setRenderHints(QPainter.RenderHint.TextAntialiasing | QPainter.RenderHint.Antialiasing)
painter.save()
painter.setPen(QColor(255, 255, 255, 125))
l.draw(painter, QPointF(1, 1))
@ -205,21 +205,21 @@ def layout_text(prefs, img, title, subtitle, footer, max_height, style):
title, subtitle, footer = title, subtitle, footer
title_font = QFont(prefs.title_font_family or 'Liberation Serif')
title_font.setPixelSize(prefs.title_font_size)
title_font.setStyleStrategy(QFont.PreferAntialias)
title_font.setStyleStrategy(QFont.StyleStrategy.PreferAntialias)
title_block = Block(title, width, title_font, img, max_height, style.TITLE_ALIGN)
title_block.position = style.hmargin, style.vmargin
subtitle_block = Block()
if subtitle:
subtitle_font = QFont(prefs.subtitle_font_family or 'Liberation Sans')
subtitle_font.setPixelSize(prefs.subtitle_font_size)
subtitle_font.setStyleStrategy(QFont.PreferAntialias)
subtitle_font.setStyleStrategy(QFont.StyleStrategy.PreferAntialias)
gap = 2 * title_block.leading
mh = max_height - title_block.height - gap
subtitle_block = Block(subtitle, width, subtitle_font, img, mh, style.SUBTITLE_ALIGN)
subtitle_block.position = style.hmargin, title_block.position.y + title_block.height + gap
footer_font = QFont(prefs.footer_font_family or 'Liberation Serif')
footer_font.setStyleStrategy(QFont.PreferAntialias)
footer_font.setStyleStrategy(QFont.StyleStrategy.PreferAntialias)
footer_font.setPixelSize(prefs.footer_font_size)
footer_block = Block(footer, width, footer_font, img, max_height, style.FOOTER_ALIGN)
footer_block.position = style.hmargin, img.height() - style.vmargin - footer_block.height
@ -342,7 +342,7 @@ def color(color_theme, name):
class Style(object):
TITLE_ALIGN = SUBTITLE_ALIGN = FOOTER_ALIGN = Qt.AlignHCenter | Qt.AlignTop
TITLE_ALIGN = SUBTITLE_ALIGN = FOOTER_ALIGN = Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop
def __init__(self, color_theme, prefs):
self.load_colors(color_theme)
@ -370,9 +370,9 @@ class Cross(Style):
title_block.height + subtitle_block.height + subtitle_block.line_spacing // 2 + title_block.leading)
painter.save()
p = QPainterPath()
p.addRoundedRect(QRectF(r), 10, 10 * r.width()/r.height(), Qt.RelativeSize)
p.addRoundedRect(QRectF(r), 10, 10 * r.width()/r.height(), Qt.SizeMode.RelativeSize)
painter.setClipPath(p)
painter.setRenderHint(QPainter.Antialiasing)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.fillRect(r, self.color2)
painter.restore()
r = QRect(0, 0, int(title_block.position.x), rect.height())
@ -458,10 +458,10 @@ class Banner(Style):
right_fold, right_inner = draw_fold(right + width23, m=-1, corner=right_corner)
painter.save()
painter.setRenderHint(QPainter.Antialiasing)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
pen = QPen(self.ccolor2)
pen.setWidth(3)
pen.setJoinStyle(Qt.RoundJoin)
pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
painter.setPen(pen)
for r in (left_fold, right_fold):
painter.fillPath(r, QBrush(self.color2))
@ -499,7 +499,7 @@ class Ornamental(Style):
import traceback
traceback.print_exc()
p = painter
painter.setRenderHint(QPainter.Antialiasing)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
g = QRadialGradient(QPointF(rect.center()), rect.width())
g.setColorAt(0, self.color1), g.setColorAt(1, self.color2)
painter.fillRect(rect, QBrush(g))
@ -546,7 +546,7 @@ class Blocks(Style):
NAME = 'Blocks'
GUI_NAME = _('Blocks')
FOOTER_ALIGN = Qt.AlignRight | Qt.AlignTop
FOOTER_ALIGN = Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignTop
def __call__(self, painter, rect, color_theme, title_block, subtitle_block, footer_block):
painter.fillRect(rect, self.color1)
@ -593,7 +593,7 @@ def generate_cover(mi, prefs=None, as_qimage=False):
color_theme = random.choice(load_color_themes(prefs))
style = random.choice(load_styles(prefs))(color_theme, prefs)
title, subtitle, footer = format_text(mi, prefs)
img = QImage(prefs.cover_width, prefs.cover_height, QImage.Format_ARGB32)
img = QImage(prefs.cover_width, prefs.cover_height, QImage.Format.Format_ARGB32)
title_block, subtitle_block, footer_block = layout_text(
prefs, img, title, subtitle, footer, img.height() // 3, style)
p = QPainter(img)
@ -647,8 +647,8 @@ def calibre_cover2(title, author_string='', series_string='', prefs=None, as_qim
scale = 800. / prefs['cover_height']
scale_cover(prefs, scale)
prefs = Prefs(**prefs)
img = QImage(prefs.cover_width, prefs.cover_height, QImage.Format_ARGB32)
img.fill(Qt.white)
img = QImage(prefs.cover_width, prefs.cover_height, QImage.Format.Format_ARGB32)
img.fill(Qt.GlobalColor.white)
# colors = to_theme('ffffff ffffff 000000 000000')
color_theme = theme_to_colors(fallback_colors)
@ -666,7 +666,7 @@ def calibre_cover2(title, author_string='', series_string='', prefs=None, as_qim
scaled, width, height = fit_image(logo.width(), logo.height(), pwidth, pheight)
x, y = (pwidth - width) // 2, (pheight - height) // 2
rect = QRect(x, top + y, width, height)
painter.setRenderHint(QPainter.SmoothPixmapTransform)
painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform)
painter.drawImage(rect, logo)
return self.ccolor1, self.ccolor1, self.ccolor1
style = CalibeLogoStyle(color_theme, prefs)
@ -687,14 +687,14 @@ def calibre_cover2(title, author_string='', series_string='', prefs=None, as_qim
def message_image(text, width=500, height=400, font_size=20):
init_environment()
img = QImage(width, height, QImage.Format_ARGB32)
img.fill(Qt.white)
img = QImage(width, height, QImage.Format.Format_ARGB32)
img.fill(Qt.GlobalColor.white)
p = QPainter(img)
f = QFont()
f.setPixelSize(font_size)
p.setFont(f)
r = img.rect().adjusted(10, 10, -10, -10)
p.drawText(r, Qt.AlignJustify | Qt.AlignVCenter | Qt.TextWordWrap, text)
p.drawText(r, Qt.AlignmentFlag.AlignJustify | Qt.AlignmentFlag.AlignVCenter | Qt.TextFlag.TextWordWrap, text)
p.end()
return pixmap_to_data(img)
@ -707,15 +707,15 @@ def scale_cover(prefs, scale):
def generate_masthead(title, output_path=None, width=600, height=60, as_qimage=False, font_family=None):
init_environment()
font_family = font_family or cprefs['title_font_family'] or 'Liberation Serif'
img = QImage(width, height, QImage.Format_ARGB32)
img.fill(Qt.white)
img = QImage(width, height, QImage.Format.Format_ARGB32)
img.fill(Qt.GlobalColor.white)
p = QPainter(img)
p.setRenderHints(QPainter.Antialiasing | QPainter.TextAntialiasing)
p.setRenderHints(QPainter.RenderHint.Antialiasing | QPainter.RenderHint.TextAntialiasing)
f = QFont(font_family)
f.setStyleStrategy(QFont.PreferAntialias)
f.setStyleStrategy(QFont.StyleStrategy.PreferAntialias)
f.setPixelSize((height * 3) // 4), f.setBold(True)
p.setFont(f)
p.drawText(img.rect(), Qt.AlignLeft | Qt.AlignVCenter, sanitize(title))
p.drawText(img.rect(), Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, sanitize(title))
p.end()
if as_qimage:
return img

View File

@ -77,7 +77,7 @@ every time you add an HTML file to the library.\
QLabel, Qt, QLineEdit, QCheckBox)
config_dialog = QDialog(parent)
button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
v = QVBoxLayout(config_dialog)
def size_dialog():
@ -91,7 +91,7 @@ every time you add an HTML file to the library.\
help_text = self.customization_help(gui=True)
help_text = QLabel(help_text, config_dialog)
help_text.setWordWrap(True)
help_text.setTextInteractionFlags(Qt.LinksAccessibleByMouse | Qt.LinksAccessibleByKeyboard)
help_text.setTextInteractionFlags(Qt.TextInteractionFlag.LinksAccessibleByMouse | Qt.TextInteractionFlag.LinksAccessibleByKeyboard)
help_text.setOpenExternalLinks(True)
v.addWidget(help_text)
bf = QCheckBox(_('Add linked files in breadth first order'))
@ -113,7 +113,7 @@ every time you add an HTML file to the library.\
size_dialog()
config_dialog.exec_()
if config_dialog.result() == QDialog.Accepted:
if config_dialog.result() == QDialog.DialogCode.Accepted:
sc = unicode_type(sc.text()).strip()
if bf.isChecked():
sc += '|bf'

View File

@ -124,7 +124,7 @@ def create_profile():
s = QWebEngineScript()
s.setName('csslint.js')
s.setSourceCode(csslint_js())
s.setWorldId(QWebEngineScript.ApplicationWorld)
s.setWorldId(QWebEngineScript.ScriptWorldId.ApplicationWorld)
ans.scripts().insert(s)
return ans
@ -163,7 +163,7 @@ class Worker(QWebEnginePage):
self.working = True
self.console_messages = []
self.runJavaScript(
'window.check_css({})'.format(json.dumps(src)), QWebEngineScript.ApplicationWorld, self.check_done)
'window.check_css({})'.format(json.dumps(src)), QWebEngineScript.ScriptWorldId.ApplicationWorld, self.check_done)
def check_css_when_ready(self, src):
if self.ready:
@ -195,7 +195,7 @@ class Pool(object):
self.assign_work()
app = QApplication.instance()
while self.working:
app.processEvents(QEventLoop.WaitForMoreEvents | QEventLoop.ExcludeUserInputEvents)
app.processEvents(QEventLoop.ProcessEventsFlag.WaitForMoreEvents | QEventLoop.ProcessEventsFlag.ExcludeUserInputEvents)
return self.results
def assign_work(self):

View File

@ -89,17 +89,17 @@ class SVGRasterizer(object):
size.setWidth(sizes[0])
size.setHeight(sizes[1])
if width or height:
size.scale(width, height, Qt.KeepAspectRatio)
size.scale(width, height, Qt.AspectRatioMode.KeepAspectRatio)
logger.info('Rasterizing %r to %dx%d'
% (elem, size.width(), size.height()))
image = QImage(size, QImage.Format_ARGB32_Premultiplied)
image = QImage(size, QImage.Format.Format_ARGB32_Premultiplied)
image.fill(QColor("white").rgb())
painter = QPainter(image)
svg.render(painter)
painter.end()
array = QByteArray()
buffer = QBuffer(array)
buffer.open(QIODevice.WriteOnly)
buffer.open(QIODevice.OpenModeFlag.WriteOnly)
image.save(buffer, format)
return array.data()
@ -185,7 +185,7 @@ class SVGRasterizer(object):
data = QByteArray(svgitem.bytes_representation)
svg = QSvgRenderer(data)
size = svg.defaultSize()
size.scale(width, height, Qt.KeepAspectRatio)
size.scale(width, height, Qt.AspectRatioMode.KeepAspectRatio)
key = (svgitem.href, size.width(), size.height())
if key in self.images:
href = self.images[key]
@ -193,14 +193,14 @@ class SVGRasterizer(object):
logger = self.oeb.logger
logger.info('Rasterizing %r to %dx%d'
% (svgitem.href, size.width(), size.height()))
image = QImage(size, QImage.Format_ARGB32_Premultiplied)
image = QImage(size, QImage.Format.Format_ARGB32_Premultiplied)
image.fill(QColor("white").rgb())
painter = QPainter(image)
svg.render(painter)
painter.end()
array = QByteArray()
buffer = QBuffer(array)
buffer.open(QIODevice.WriteOnly)
buffer.open(QIODevice.OpenModeFlag.WriteOnly)
image.save(buffer, 'PNG')
data = array.data()
manifest = self.oeb.manifest

View File

@ -17,7 +17,7 @@ OUTPUT = '/t/dev.pdf'
class Renderer(QWebEnginePage):
def do_print(self, ok):
p = QPageLayout(QPageSize(QPageSize(QPageSize.A4)), QPageLayout.Portrait, QMarginsF(72, 0, 72, 0))
p = QPageLayout(QPageSize(QPageSize(QPageSize.PageSizeId.A4)), QPageLayout.Orientation.Portrait, QMarginsF(72, 0, 72, 0))
self.printToPdf(self.print_finished, p)
def print_finished(self, pdf_data):

View File

@ -179,7 +179,7 @@ class Renderer(QWebEnginePage):
self.loadFinished.connect(self.load_finished)
self.load_hang_check_timer = t = QTimer(self)
self.load_started_at = 0
t.setTimerType(Qt.VeryCoarseTimer)
t.setTimerType(Qt.TimerType.VeryCoarseTimer)
t.setInterval(HANG_TIME * 1000)
t.setSingleShot(True)
t.timeout.connect(self.on_load_hang)
@ -384,7 +384,7 @@ def job_for_name(container, name, margins, page_layout):
index_file = container.name_to_abspath(name)
if margins:
page_layout = QPageLayout(page_layout)
page_layout.setUnits(QPageLayout.Point)
page_layout.setUnits(QPageLayout.Unit.Point)
new_margins = QMarginsF(*resolve_margins(margins, page_layout))
page_layout.setMargins(new_margins)
return index_file, page_layout, name

View File

@ -56,7 +56,7 @@ def parse_pdf_page_size(spec, unit='inch', dpi=72.0):
'didot':didot, 'pica':pica, 'millimeter':mm,
'centimeter':cm
}.get(unit, 1.0)
return QPageSize(QSizeF(factor*width, factor*height), QPageSize.Point, matchPolicy=QPageSize.ExactMatch)
return QPageSize(QSizeF(factor*width, factor*height), QPageSize.Unit.Point, matchPolicy=QPageSize.SizeMatchPolicy.ExactMatch)
def get_page_size(opts, for_comic=False):
@ -68,7 +68,7 @@ def get_page_size(opts, for_comic=False):
opts.output_profile.height)
dpi = opts.output_profile.dpi
factor = 72.0 / dpi
page_size = QPageSize(QSizeF(factor * w, factor * h), QPageSize.Point, matchPolicy=QPageSize.ExactMatch)
page_size = QPageSize(QSizeF(factor * w, factor * h), QPageSize.Unit.Point, matchPolicy=QPageSize.SizeMatchPolicy.ExactMatch)
else:
page_size = None
if opts.custom_size is not None:
@ -85,8 +85,8 @@ def get_page_layout(opts, for_comic=False):
return max(0, getattr(opts, 'pdf_page_margin_' + which) or getattr(opts, 'margin_' + which))
margins = QMarginsF(m('left'), m('top'), m('right'), m('bottom'))
ans = QPageLayout(page_size, QPageLayout.Portrait, margins)
ans.setMode(QPageLayout.FullPageMode)
ans = QPageLayout(page_size, QPageLayout.Orientation.Portrait, margins)
ans.setMode(QPageLayout.Mode.FullPageMode)
return ans
# }}}

View File

@ -8,18 +8,18 @@ __docformat__ = 'restructuredtext en'
from PyQt5.Qt import QPrinter
UNITS = {
'millimeter' : QPrinter.Millimeter,
'point' : QPrinter.Point,
'inch' : QPrinter.Inch,
'pica' : QPrinter.Pica,
'didot' : QPrinter.Didot,
'cicero' : QPrinter.Cicero,
'devicepixel' : QPrinter.DevicePixel,
'millimeter' : QPrinter.Unit.Millimeter,
'point' : QPrinter.Unit.Point,
'inch' : QPrinter.Unit.Inch,
'pica' : QPrinter.Unit.Pica,
'didot' : QPrinter.Unit.Didot,
'cicero' : QPrinter.Unit.Cicero,
'devicepixel' : QPrinter.Unit.DevicePixel,
}
def unit(unit):
return UNITS.get(unit, QPrinter.Inch)
return UNITS.get(unit, QPrinter.Unit.Inch)
PAPER_SIZES = {
@ -62,13 +62,13 @@ def paper_size(size):
ORIENTATIONS = {
'portrait' : QPrinter.Portrait,
'landscape' : QPrinter.Landscape,
'portrait' : QPrinter.Orientation.Portrait,
'landscape' : QPrinter.Orientation.Landscape,
}
def orientation(orientation):
return ORIENTATIONS.get(orientation, QPrinter.Portrait)
return ORIENTATIONS.get(orientation, QPrinter.Orientation.Portrait)
def size(size):

View File

@ -235,8 +235,8 @@ class TexturePattern(TilingPattern):
image = pixmap.toImage()
cache_key = pixmap.cacheKey()
imgref = pdf.add_image(image, cache_key)
paint_type = (2 if image.format() in {QImage.Format_MonoLSB,
QImage.Format_Mono} else 1)
paint_type = (2 if image.format() in {QImage.Format.Format_MonoLSB,
QImage.Format.Format_Mono} else 1)
super(TexturePattern, self).__init__(
cache_key, matrix, w=image.width(), h=image.height(),
paint_type=paint_type)
@ -257,7 +257,7 @@ class GraphicsState(object):
'clip_updated', 'do_fill', 'do_stroke')
def __init__(self):
self.fill = QBrush(Qt.white)
self.fill = QBrush(Qt.GlobalColor.white)
self.stroke = QPen()
self.opacity = 1.0
self.transform = QTransform()
@ -303,22 +303,22 @@ class Graphics(object):
s = self.pending_state
if flags & QPaintEngine.DirtyTransform:
if flags & QPaintEngine.DirtyFlag.DirtyTransform:
s.transform = state.transform()
if flags & QPaintEngine.DirtyBrushOrigin:
if flags & QPaintEngine.DirtyFlag.DirtyBrushOrigin:
s.brush_origin = state.brushOrigin()
if flags & QPaintEngine.DirtyBrush:
if flags & QPaintEngine.DirtyFlag.DirtyBrush:
s.fill = state.brush()
if flags & QPaintEngine.DirtyPen:
if flags & QPaintEngine.DirtyFlag.DirtyPen:
s.stroke = state.pen()
if flags & QPaintEngine.DirtyOpacity:
if flags & QPaintEngine.DirtyFlag.DirtyOpacity:
s.opacity = state.opacity()
if flags & QPaintEngine.DirtyClipPath or flags & QPaintEngine.DirtyClipRegion:
if flags & QPaintEngine.DirtyFlag.DirtyClipPath or flags & QPaintEngine.DirtyFlag.DirtyClipRegion:
s.clip_updated = True
def reset(self):
@ -354,8 +354,8 @@ class Graphics(object):
path = painter.clipPath()
if not path.isEmpty():
p = convert_path(path)
fill_rule = {Qt.OddEvenFill:'evenodd',
Qt.WindingFill:'winding'}[path.fillRule()]
fill_rule = {Qt.FillRule.OddEvenFill:'evenodd',
Qt.FillRule.WindingFill:'winding'}[path.fillRule()]
pdf.add_clip(p, fill_rule=fill_rule)
self.current_state = self.pending_state
@ -375,26 +375,26 @@ class Graphics(object):
vals = list(brush.color().getRgbF())
self.brushobj = None
if style <= Qt.DiagCrossPattern:
if style <= Qt.BrushStyle.DiagCrossPattern:
opacity *= vals[-1]
color = vals[:3]
if style > Qt.SolidPattern:
if style > Qt.BrushStyle.SolidPattern:
pat = QtPattern(style, matrix)
elif style == Qt.TexturePattern:
elif style == Qt.BrushStyle.TexturePattern:
pat = TexturePattern(brush.texture(), matrix, pdf)
if pat.paint_type == 2:
opacity *= vals[-1]
color = vals[:3]
elif style == Qt.LinearGradientPattern:
elif style == Qt.BrushStyle.LinearGradientPattern:
pat = LinearGradientPattern(brush, matrix, pdf, self.page_width_px,
self.page_height_px)
opacity *= pat.const_opacity
# TODO: Add support for radial/conical gradient fills
if opacity < 1e-4 or style == Qt.NoBrush:
if opacity < 1e-4 or style == Qt.BrushStyle.NoBrush:
do_fill = False
self.brushobj = Brush(brush_origin, pat, color)
@ -420,22 +420,22 @@ class Graphics(object):
pdf.current_page.write(' w ')
# Line cap
cap = {Qt.FlatCap:0, Qt.RoundCap:1, Qt.SquareCap:
cap = {Qt.PenCapStyle.FlatCap:0, Qt.PenCapStyle.RoundCap:1, Qt.PenCapStyle.SquareCap:
2}.get(pen.capStyle(), 0)
pdf.current_page.write('%d J '%cap)
# Line join
join = {Qt.MiterJoin:0, Qt.RoundJoin:1,
Qt.BevelJoin:2}.get(pen.joinStyle(), 0)
join = {Qt.PenJoinStyle.MiterJoin:0, Qt.PenJoinStyle.RoundJoin:1,
Qt.PenJoinStyle.BevelJoin:2}.get(pen.joinStyle(), 0)
pdf.current_page.write('%d j '%join)
# Dash pattern
if pen.style() == Qt.CustomDashLine:
if pen.style() == Qt.PenStyle.CustomDashLine:
pdf.serialize(Array(pen.dashPattern()))
pdf.current_page.write(' %d d ' % pen.dashOffset())
else:
ps = {Qt.DashLine:[3], Qt.DotLine:[1,2], Qt.DashDotLine:[3,2,1,2],
Qt.DashDotDotLine:[3, 2, 1, 2, 1, 2]}.get(pen.style(), [])
ps = {Qt.PenStyle.DashLine:[3], Qt.PenStyle.DotLine:[1,2], Qt.PenStyle.DashDotLine:[3,2,1,2],
Qt.PenStyle.DashDotDotLine:[3, 2, 1, 2, 1, 2]}.get(pen.style(), [])
pdf.serialize(Array(ps))
pdf.current_page.write(' 0 d ')
@ -444,7 +444,7 @@ class Graphics(object):
pen.brush(), state.brush_origin, state.opacity, pdf_system,
painter.transform())
self.pdf.apply_stroke(color, pattern, opacity)
if pen.style() == Qt.NoPen:
if pen.style() == Qt.PenStyle.NoPen:
self.pending_state.do_stroke = False
def apply_fill(self, state, pdf_system, painter):

View File

@ -298,7 +298,7 @@ class PDFStream(object):
self.debug = debug
self.page_size = page_size
self.links = Links(self, mark_links, page_size)
i = QImage(1, 1, QImage.Format_ARGB32)
i = QImage(1, 1, QImage.Format.Format_ARGB32)
i.fill(qRgba(0, 0, 0, 255))
self.alpha_bit = i.constBits().asstring(4).find(b'\xff')
@ -427,21 +427,21 @@ class PDFStream(object):
fmt = img.format()
image = QImage(img)
if (image.depth() == 1 and img.colorTable().size() == 2 and
img.colorTable().at(0) == QColor(Qt.black).rgba() and
img.colorTable().at(1) == QColor(Qt.white).rgba()):
if fmt == QImage.Format_MonoLSB:
image = image.convertToFormat(QImage.Format_Mono)
fmt = QImage.Format_Mono
img.colorTable().at(0) == QColor(Qt.GlobalColor.black).rgba() and
img.colorTable().at(1) == QColor(Qt.GlobalColor.white).rgba()):
if fmt == QImage.Format.Format_MonoLSB:
image = image.convertToFormat(QImage.Format.Format_Mono)
fmt = QImage.Format.Format_Mono
else:
if (fmt != QImage.Format_RGB32 and fmt != QImage.Format_ARGB32):
image = image.convertToFormat(QImage.Format_ARGB32)
fmt = QImage.Format_ARGB32
if (fmt != QImage.Format.Format_RGB32 and fmt != QImage.Format.Format_ARGB32):
image = image.convertToFormat(QImage.Format.Format_ARGB32)
fmt = QImage.Format.Format_ARGB32
w = image.width()
h = image.height()
d = image.depth()
if fmt == QImage.Format_Mono:
if fmt == QImage.Format.Format_Mono:
bytes_per_line = (w + 7) >> 3
data = image.constBits().asstring(bytes_per_line * h)
return self.write_image(data, w, h, d, cache_key=cache_key)
@ -449,7 +449,7 @@ class PDFStream(object):
has_alpha = False
soft_mask = None
if fmt == QImage.Format_ARGB32:
if fmt == QImage.Format.Format_ARGB32:
tmask = image.constBits().asstring(4*w*h)[self.alpha_bit::4]
sdata = bytearray(tmask)
vals = set(sdata)
@ -458,8 +458,8 @@ class PDFStream(object):
if has_alpha:
# Blend image onto a white background as otherwise Qt will render
# transparent pixels as black
background = QImage(image.size(), QImage.Format_ARGB32_Premultiplied)
background.fill(Qt.white)
background = QImage(image.size(), QImage.Format.Format_ARGB32_Premultiplied)
background.fill(Qt.GlobalColor.white)
painter = QPainter(background)
painter.drawImage(0, 0, image)
painter.end()

View File

@ -27,7 +27,7 @@ class Render(QWebEnginePage):
QWebEnginePage.__init__(self)
secure_webengine(self)
self.printing_started = False
self.loadFinished.connect(self.load_finished, type=Qt.QueuedConnection)
self.loadFinished.connect(self.load_finished, type=Qt.ConnectionType.QueuedConnection)
self.pdfPrintingFinished.connect(self.print_finished)
self.hang_timer = t = QTimer(self)
t.setInterval(500)
@ -45,7 +45,7 @@ class Render(QWebEnginePage):
} catch {}
}
ans;
''', QWebEngineScript.ApplicationWorld, self.start_print)
''', QWebEngineScript.ScriptWorldId.ApplicationWorld, self.start_print)
else:
self.hang_timer.stop()
QApplication.instance().exit(1)
@ -70,14 +70,14 @@ class Render(QWebEnginePage):
def start_print(self, data):
margins = QMarginsF(0, 0, 0, 0)
page_size = QPageSize(QPageSize.A4)
page_size = QPageSize(QPageSize.PageSizeId.A4)
if isinstance(data, dict):
try:
if 'margins' in data:
margins = QMarginsF(*data['margins'])
if 'size' in data:
sz = data['size']
if type(getattr(QPageSize, sz, None)) is type(QPageSize.A4): # noqa
if type(getattr(QPageSize, sz, None)) is type(QPageSize.PageSizeId.A4): # noqa
page_size = QPageSize(getattr(QPageSize, sz))
else:
from calibre.ebooks.pdf.image_writer import parse_pdf_page_size
@ -86,7 +86,7 @@ class Render(QWebEnginePage):
page_size = ps
except Exception:
pass
page_layout = QPageLayout(page_size, QPageLayout.Portrait, margins)
page_layout = QPageLayout(page_size, QPageLayout.Orientation.Portrait, margins)
self.printToPdf('rendered.pdf', page_layout)
self.printing_started = True
self.start_time = monotonic()

View File

@ -44,7 +44,7 @@ from polyglot.builtins import (
)
try:
NO_URL_FORMATTING = QUrl.None_
NO_URL_FORMATTING = QUrl.UrlFormattingOption.None_
except AttributeError:
NO_URL_FORMATTING = getattr(QUrl, 'None')
@ -318,9 +318,9 @@ config = _config()
# }}}
QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, config_dir)
QSettings.setPath(QSettings.IniFormat, QSettings.SystemScope, config_dir)
QSettings.setDefaultFormat(QSettings.IniFormat)
QSettings.setPath(QSettings.Format.IniFormat, QSettings.Scope.UserScope, config_dir)
QSettings.setPath(QSettings.Format.IniFormat, QSettings.Scope.SystemScope, config_dir)
QSettings.setDefaultFormat(QSettings.Format.IniFormat)
def default_author_link():
@ -485,9 +485,9 @@ class Dispatcher(QObject):
def __init__(self, func, queued=True, parent=None):
QObject.__init__(self, parent)
self.func = func
typ = Qt.QueuedConnection
typ = Qt.ConnectionType.QueuedConnection
if not queued:
typ = Qt.AutoConnection if queued is None else Qt.DirectConnection
typ = Qt.ConnectionType.AutoConnection if queued is None else Qt.ConnectionType.DirectConnection
self.dispatch_signal.connect(self.dispatch, type=typ)
def __call__(self, *args, **kwargs):
@ -517,9 +517,9 @@ class FunctionDispatcher(QObject):
QObject.__init__(self, parent)
self.func = func
typ = Qt.QueuedConnection
typ = Qt.ConnectionType.QueuedConnection
if not queued:
typ = Qt.AutoConnection if queued is None else Qt.DirectConnection
typ = Qt.ConnectionType.AutoConnection if queued is None else Qt.ConnectionType.DirectConnection
self.dispatch_signal.connect(self.dispatch, type=typ)
self.q = queue.Queue()
self.lock = threading.Lock()
@ -553,8 +553,8 @@ class GetMetadata(QObject):
def __init__(self):
QObject.__init__(self)
self.edispatch.connect(self._get_metadata, type=Qt.QueuedConnection)
self.idispatch.connect(self._from_formats, type=Qt.QueuedConnection)
self.edispatch.connect(self._get_metadata, type=Qt.ConnectionType.QueuedConnection)
self.idispatch.connect(self._from_formats, type=Qt.ConnectionType.QueuedConnection)
def __call__(self, id, *args, **kwargs):
self.edispatch.emit(id, args, kwargs)
@ -639,9 +639,9 @@ class FileIconProvider(QFileIconProvider):
def icon(self, arg):
if isinstance(arg, QFileInfo):
return self.load_icon(arg)
if arg == QFileIconProvider.Folder:
if arg == QFileIconProvider.IconType.Folder:
return self.icons['dir']
if arg == QFileIconProvider.File:
if arg == QFileIconProvider.IconType.File:
return self.icons['default']
return QFileIconProvider.icon(self, arg)
@ -686,7 +686,7 @@ def is_dark_theme():
def choose_osx_app(window, name, title, default_dir='/Applications'):
fd = FileDialog(title=title, parent=window, name=name, mode=QFileDialog.ExistingFile,
fd = FileDialog(title=title, parent=window, name=name, mode=QFileDialog.FileMode.ExistingFile,
default_dir=default_dir)
app = fd.get_files()
fd.setParent(None)
@ -821,11 +821,11 @@ def setup_hidpi():
if hidpi == 'on' or (hidpi == 'auto' and not has_env_setting):
if DEBUG:
prints('Turning on automatic hidpi scaling')
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
QApplication.setAttribute(Qt.ApplicationAttribute.AA_EnableHighDpiScaling, True)
elif hidpi == 'off':
if DEBUG:
prints('Turning off automatic hidpi scaling')
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, False)
QApplication.setAttribute(Qt.ApplicationAttribute.AA_EnableHighDpiScaling, False)
for p in env_vars:
os.environ.pop(p, None)
elif DEBUG:
@ -852,9 +852,9 @@ def setup_unix_signals(self):
original_handlers[sig] = signal.signal(sig, lambda x, y: None)
signal.siginterrupt(sig, False)
signal.set_wakeup_fd(write_fd)
self.signal_notifier = QSocketNotifier(read_fd, QSocketNotifier.Read, self)
self.signal_notifier = QSocketNotifier(read_fd, QSocketNotifier.Type.Read, self)
self.signal_notifier.setEnabled(True)
self.signal_notifier.activated.connect(self.signal_received, type=Qt.QueuedConnection)
self.signal_notifier.activated.connect(self.signal_received, type=Qt.ConnectionType.QueuedConnection)
return original_handlers
@ -894,7 +894,7 @@ class Application(QApplication):
QApplication.setApplicationName(APP_UID)
if override_program_name and hasattr(QApplication, 'setDesktopFileName'):
QApplication.setDesktopFileName(override_program_name)
QApplication.setAttribute(Qt.AA_ShareOpenGLContexts, True) # needed for webengine
QApplication.setAttribute(Qt.ApplicationAttribute.AA_ShareOpenGLContexts, True) # needed for webengine
QApplication.__init__(self, qargs)
sh = self.styleHints()
if hasattr(sh, 'setShowShortcutsInContextMenus'):
@ -902,8 +902,8 @@ class Application(QApplication):
if ismacos:
from calibre_extensions.cocoa import disable_cocoa_ui_elements
disable_cocoa_ui_elements()
self.setAttribute(Qt.AA_UseHighDpiPixmaps)
self.setAttribute(Qt.AA_SynthesizeTouchForUnhandledMouseEvents, False)
self.setAttribute(Qt.ApplicationAttribute.AA_UseHighDpiPixmaps)
self.setAttribute(Qt.ApplicationAttribute.AA_SynthesizeTouchForUnhandledMouseEvents, False)
try:
base_dir()
except EnvironmentError as err:
@ -919,7 +919,7 @@ class Application(QApplication):
if not iswindows:
self.setup_unix_signals()
if islinux or isbsd:
self.setAttribute(Qt.AA_DontUseNativeMenuBar, 'CALIBRE_NO_NATIVE_MENUBAR' in os.environ)
self.setAttribute(Qt.ApplicationAttribute.AA_DontUseNativeMenuBar, 'CALIBRE_NO_NATIVE_MENUBAR' in os.environ)
self.setup_styles(force_calibre_style)
self.setup_ui_font()
if not self.using_calibre_style and self.style().objectName() == 'fusion':
@ -1080,7 +1080,7 @@ class Application(QApplication):
# appearance is changed. And it has to be after current event
# processing finishes as of Qt 5.14 otherwise the palette change is
# ignored.
QTimer.singleShot(1000, lambda: QApplication.instance().setAttribute(Qt.AA_SetPalette, False))
QTimer.singleShot(1000, lambda: QApplication.instance().setAttribute(Qt.ApplicationAttribute.AA_SetPalette, False))
self.ignore_palette_changes = False
def on_palette_change(self):
@ -1136,8 +1136,8 @@ class Application(QApplication):
if ismacos:
from calibre_extensions.cocoa import transient_scroller
transient_scroller = transient_scroller()
icon_map[QStyle.SP_CustomBase + 1] = I('close-for-light-theme.png')
icon_map[QStyle.SP_CustomBase + 2] = I('close-for-dark-theme.png')
icon_map[QStyle.StandardPixmap.SP_CustomBase + 1] = I('close-for-light-theme.png')
icon_map[QStyle.StandardPixmap.SP_CustomBase + 2] = I('close-for-dark-theme.png')
self.pi.load_style(icon_map, transient_scroller)
def _send_file_open_events(self):
@ -1153,8 +1153,8 @@ class Application(QApplication):
self.installTranslator(self._translator)
def event(self, e):
if callable(self.file_event_hook) and e.type() == QEvent.FileOpen:
url = e.url().toString(QUrl.FullyEncoded)
if callable(self.file_event_hook) and e.type() == QEvent.Type.FileOpen:
url = e.url().toString(QUrl.ComponentFormattingOption.FullyEncoded)
if url and url.startswith('calibre://'):
with self._file_open_lock:
self._file_open_paths.append(url)
@ -1314,7 +1314,7 @@ def ensure_app(headless=True):
if ismacos:
os.environ['QT_MAC_DISABLE_FOREGROUND_APPLICATION_TRANSFORM'] = '1'
if headless and iswindows:
QApplication.setAttribute(Qt.AA_UseSoftwareOpenGL, True)
QApplication.setAttribute(Qt.ApplicationAttribute.AA_UseSoftwareOpenGL, True)
_store_app = QApplication(args)
if headless and has_headless:
_store_app.headless = True
@ -1504,8 +1504,8 @@ def add_to_recent_docs(path):
def windows_is_system_dark_mode_enabled():
s = QSettings(r"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize", QSettings.NativeFormat)
if s.status() == QSettings.NoError:
s = QSettings(r"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize", QSettings.Format.NativeFormat)
if s.status() == QSettings.Status.NoError:
return s.value("AppsUseLightTheme") == 0
return False

View File

@ -66,7 +66,7 @@ class InterfaceAction(QObject):
priority = 1
#: The menu popup type for when this plugin is added to a toolbar
popup_type = QToolButton.MenuButtonPopup
popup_type = QToolButton.ToolButtonPopupMode.MenuButtonPopup
#: Whether this action should be auto repeated when its shortcut
#: key is held down.
@ -186,7 +186,7 @@ class InterfaceAction(QObject):
shortcut_name = unicode_type(spec[0])
if shortcut_name and self.action_spec[0] and not (
attr == 'qaction' and self.popup_type == QToolButton.InstantPopup):
attr == 'qaction' and self.popup_type == QToolButton.ToolButtonPopupMode.InstantPopup):
try:
self.gui.keyboard.register_shortcut(self.unique_name + ' - ' + attr,
shortcut_name, default_keys=keys,
@ -199,7 +199,7 @@ class InterfaceAction(QObject):
except:
pass
shortcut_action.setShortcuts([QKeySequence(key,
QKeySequence.PortableText) for key in keys])
QKeySequence.SequenceFormat.PortableText) for key in keys])
else:
self.shortcut_action_for_context_menu = shortcut_action
if ismacos:

View File

@ -36,8 +36,8 @@ class Updater(QThread): # {{{
self.pd.setModal(True)
self.pd.show()
self.update_progress.connect(self.pd.set_value,
type=Qt.QueuedConnection)
self.update_done.connect(self.pd.hide, type=Qt.QueuedConnection)
type=Qt.ConnectionType.QueuedConnection)
self.update_done.connect(self.pd.hide, type=Qt.ConnectionType.QueuedConnection)
def canceled(self):
self.keep_going = False

View File

@ -28,8 +28,8 @@ class BrowseAnnotationsAction(InterfaceAction):
from calibre.gui2.library.annotations import AnnotationsBrowser
self.gui.library_view.selection_changed.connect(self.selection_changed)
self._browser = AnnotationsBrowser(self.gui)
self._browser.show_book.connect(self.open_book, type=Qt.QueuedConnection)
self._browser.open_annotation.connect(self.open_annotation, type=Qt.QueuedConnection)
self._browser.show_book.connect(self.open_book, type=Qt.ConnectionType.QueuedConnection)
self._browser.open_annotation.connect(self.open_annotation, type=Qt.ConnectionType.QueuedConnection)
return self._browser
def show_browser(self):

View File

@ -123,7 +123,7 @@ class MovedDialog(QDialog): # {{{
self.cd.setIcon(QIcon(I('document_open.png')))
self.cd.clicked.connect(self.choose_dir)
l.addWidget(self.cd, l.rowCount() - 1, 1, 1, 1)
self.bb = QDialogButtonBox(QDialogButtonBox.Abort)
self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Abort)
b = self.bb.addButton(_('Library moved'), self.bb.AcceptRole)
b.setIcon(QIcon(I('ok.png')))
b = self.bb.addButton(_('Forget library'), self.bb.RejectRole)
@ -164,7 +164,7 @@ class BackupStatus(QDialog): # {{{
self.msg = QLabel('')
self.msg.setWordWrap(True)
l.addWidget(self.msg)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.Close)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close)
bb.accepted.connect(self.accept)
bb.rejected.connect(self.reject)
b = bb.addButton(_('Queue &all books for backup'), bb.ActionRole)
@ -219,8 +219,8 @@ class ChooseLibraryAction(InterfaceAction):
ac.triggered.connect(self.exim_data)
self.stats = LibraryUsageStats()
self.popup_type = (QToolButton.InstantPopup if len(self.stats.stats) > 1 else
QToolButton.MenuButtonPopup)
self.popup_type = (QToolButton.ToolButtonPopupMode.InstantPopup if len(self.stats.stats) > 1 else
QToolButton.ToolButtonPopupMode.MenuButtonPopup)
if len(self.stats.stats) > 1:
self.action_choose.triggered.connect(self.choose_library)
else:
@ -257,7 +257,7 @@ class ChooseLibraryAction(InterfaceAction):
ac.setVisible(False)
connect_lambda(ac.triggered, self, lambda self:
self.switch_requested(self.qs_locations[int(self.gui.sender().objectName())]),
type=Qt.QueuedConnection)
type=Qt.ConnectionType.QueuedConnection)
self.choose_menu.addAction(ac)
self.rename_separator = self.choose_menu.addSeparator()
@ -265,26 +265,26 @@ class ChooseLibraryAction(InterfaceAction):
self.maintenance_menu = QMenu(_('Library maintenance'))
ac = self.create_action(spec=(_('Library metadata backup status'),
'lt.png', None, None), attr='action_backup_status')
ac.triggered.connect(self.backup_status, type=Qt.QueuedConnection)
ac.triggered.connect(self.backup_status, type=Qt.ConnectionType.QueuedConnection)
self.maintenance_menu.addAction(ac)
ac = self.create_action(spec=(_('Check library'), 'lt.png',
None, None), attr='action_check_library')
ac.triggered.connect(self.check_library, type=Qt.QueuedConnection)
ac.triggered.connect(self.check_library, type=Qt.ConnectionType.QueuedConnection)
self.maintenance_menu.addAction(ac)
ac = self.create_action(spec=(_('Restore database'), 'lt.png',
None, None),
attr='action_restore_database')
ac.triggered.connect(self.restore_database, type=Qt.QueuedConnection)
ac.triggered.connect(self.restore_database, type=Qt.ConnectionType.QueuedConnection)
self.maintenance_menu.addAction(ac)
self.choose_menu.addMenu(self.maintenance_menu)
self.view_state_map = {}
self.restore_view_state.connect(self._restore_view_state,
type=Qt.QueuedConnection)
type=Qt.ConnectionType.QueuedConnection)
ac = self.create_action(spec=(_('Switch to previous library'), 'lt.png',
None, None),
attr='action_previous_library')
ac.triggered.connect(self.switch_to_previous_library, type=Qt.QueuedConnection)
ac.triggered.connect(self.switch_to_previous_library, type=Qt.ConnectionType.QueuedConnection)
self.gui.keyboard.register_shortcut(
self.unique_name + '-' + 'action_previous_library',
ac.text(), action=ac, group=self.action_spec[0], default_keys=('Ctrl+Alt+p',))

View File

@ -48,7 +48,7 @@ def ask_about_cc_mismatch(gui, db, newdb, missing_cols, incompatible_cols): # {
d.w.setLayout(l)
d.setMinimumWidth(600)
d.setMinimumHeight(500)
d.bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
d.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel)
msg = _('The custom columns in the <i>{0}</i> library are different from the '
'custom columns in the <i>{1}</i> library. As a result, some metadata might not be copied.').format(
@ -201,7 +201,7 @@ class ChooseLibrary(Dialog): # {{{
self.items.clear()
for name, loc in sorted_locations:
i = QListWidgetItem(name, self.items)
i.setData(Qt.UserRole, loc)
i.setData(Qt.ItemDataRole.UserRole, loc)
self.items.setCurrentRow(0)
def setup_ui(self):
@ -233,7 +233,7 @@ class ChooseLibrary(Dialog): # {{{
v.addLayout(h)
v.addStretch(10)
bb = self.bb
bb.setStandardButtons(QDialogButtonBox.Cancel)
bb.setStandardButtons(QDialogButtonBox.StandardButton.Cancel)
self.delete_after_copy = False
b = bb.addButton(_('&Copy'), bb.AcceptRole)
b.setIcon(QIcon(I('edit-copy.png')))
@ -244,7 +244,7 @@ class ChooseLibrary(Dialog): # {{{
b2.setToolTip(_('Copy to the specified library and delete from the current library'))
b.setDefault(True)
l.addWidget(bb, 1, 0, 1, 2)
self.items.setFocus(Qt.OtherFocusReason)
self.items.setFocus(Qt.FocusReason.OtherFocusReason)
def sizeHint(self):
return QSize(800, 550)
@ -252,7 +252,7 @@ class ChooseLibrary(Dialog): # {{{
def current_changed(self):
i = self.items.currentItem() or self.items.item(0)
if i is not None:
loc = i.data(Qt.UserRole)
loc = i.data(Qt.ItemDataRole.UserRole)
self.le.setText(loc)
def browse(self):
@ -283,12 +283,12 @@ class DuplicatesQuestion(QDialog): # {{{
self.items = []
for book_id, (title, authors) in iteritems(duplicates):
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)
i.setData(Qt.ItemDataRole.UserRole, book_id)
i.setFlags(Qt.ItemFlag.ItemIsUserCheckable | Qt.ItemFlag.ItemIsEnabled)
i.setCheckState(Qt.CheckState.Checked)
self.items.append(i)
l.addWidget(self.books)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
bb.accepted.connect(self.accept)
bb.rejected.connect(self.reject)
self.a = b = bb.addButton(_('Select &all'), bb.ActionRole)
@ -301,21 +301,21 @@ class DuplicatesQuestion(QDialog): # {{{
self.resize(600, 400)
def copy_to_clipboard(self):
items = [('' if item.checkState() == Qt.Checked else '') + ' ' + unicode_type(item.text())
items = [('' if item.checkState() == Qt.CheckState.Checked else '') + ' ' + unicode_type(item.text())
for item in self.items]
QApplication.clipboard().setText('\n'.join(items))
def select_all(self):
for i in self.items:
i.setCheckState(Qt.Checked)
i.setCheckState(Qt.CheckState.Checked)
def select_none(self):
for i in self.items:
i.setCheckState(Qt.Unchecked)
i.setCheckState(Qt.CheckState.Unchecked)
@property
def ids(self):
return {int(i.data(Qt.UserRole)) for i in self.items if i.checkState() == Qt.Checked}
return {int(i.data(Qt.ItemDataRole.UserRole)) for i in self.items if i.checkState() == Qt.CheckState.Checked}
# }}}
@ -330,7 +330,7 @@ class CopyToLibraryAction(InterfaceAction):
name = 'Copy To Library'
action_spec = (_('Copy to library'), 'copy-to-library.png',
_('Copy selected books to the specified library'), None)
popup_type = QToolButton.InstantPopup
popup_type = QToolButton.ToolButtonPopupMode.InstantPopup
dont_add_to = frozenset(['context-menu-device'])
action_type = 'current'
action_add_menu = True

View File

@ -180,7 +180,7 @@ class ConnectShareAction(InterfaceAction):
name = 'Connect Share'
action_spec = (_('Connect/share'), 'connect_share.png',
_('Share books using a web server or email. Connect to special devices, etc.'), None)
popup_type = QToolButton.InstantPopup
popup_type = QToolButton.ToolButtonPopupMode.InstantPopup
def genesis(self):
self.content_server_is_running = False

View File

@ -80,7 +80,7 @@ class EmbedAction(InterfaceAction):
def do_embed(self, book_ids, only_fmts=None):
pd = QProgressDialog(_('Embedding updated metadata into book files...'), _('&Stop'), 0, len(book_ids), self.gui)
pd.setWindowTitle(_('Embedding metadata...'))
pd.setWindowModality(Qt.WindowModal)
pd.setWindowModality(Qt.WindowModality.WindowModal)
errors = []
self.job_data = (0, tuple(book_ids), pd, only_fmts, errors)
self.pd_timer.start()

View File

@ -32,7 +32,7 @@ class FetchNewsAction(InterfaceAction):
def init_scheduler(self, db):
from calibre.gui2.dialogs.scheduler import Scheduler
self.scheduler = Scheduler(self.gui, db)
self.scheduler.start_recipe_fetch.connect(self.download_scheduled_recipe, type=Qt.QueuedConnection)
self.scheduler.start_recipe_fetch.connect(self.download_scheduled_recipe, type=Qt.ConnectionType.QueuedConnection)
self.qaction.setMenu(self.scheduler.news_menu)
self.qaction.triggered.connect(
self.scheduler.show_dialog)
@ -46,7 +46,7 @@ class FetchNewsAction(InterfaceAction):
def connect_scheduler(self):
self.scheduler.delete_old_news.connect(
self.gui.library_view.model().delete_books_by_id,
type=Qt.QueuedConnection)
type=Qt.ConnectionType.QueuedConnection)
def download_custom_recipe(self, title, urn):
arg = {'title': title, 'urn': urn, 'username': None, 'password': None}

View File

@ -79,9 +79,9 @@ class MarkBooksAction(InterfaceAction):
continue
def eventFilter(self, obj, ev):
if ev.type() == ev.MouseButtonPress and ev.button() == Qt.LeftButton:
if ev.type() == ev.MouseButtonPress and ev.button() == Qt.MouseButton.LeftButton:
mods = QApplication.keyboardModifiers()
if mods & Qt.ControlModifier or mods & Qt.ShiftModifier:
if mods & Qt.KeyboardModifier.ControlModifier or mods & Qt.KeyboardModifier.ShiftModifier:
self.show_marked()
return True
return False

View File

@ -26,7 +26,7 @@ class PluginUpdaterAction(InterfaceAction):
# Get the user to choose a plugin to install
initial_filter = FILTER_UPDATE_AVAILABLE
mods = QApplication.keyboardModifiers()
if mods & Qt.ControlModifier or mods & Qt.ShiftModifier:
if mods & Qt.KeyboardModifier.ControlModifier or mods & Qt.KeyboardModifier.ShiftModifier:
initial_filter = FILTER_ALL
d = PluginUpdaterDialog(self.gui, initial_filter=initial_filter)

View File

@ -109,14 +109,14 @@ class Polish(QDialog): # {{{
l.addWidget(la, count, 1, 1, 1)
count += 1
l.addItem(QSpacerItem(10, 10, vPolicy=QSizePolicy.Expanding), count, 1, 1, 2)
l.addItem(QSpacerItem(10, 10, vPolicy=QSizePolicy.Policy.Expanding), count, 1, 1, 2)
la = self.help_label = QLabel('')
self.help_link_activated('#polish')
la.setWordWrap(True)
la.setTextFormat(Qt.RichText)
la.setFrameShape(QFrame.StyledPanel)
la.setAlignment(Qt.AlignLeft|Qt.AlignTop)
la.setTextFormat(Qt.TextFormat.RichText)
la.setFrameShape(QFrame.Shape.StyledPanel)
la.setAlignment(Qt.AlignmentFlag.AlignLeft|Qt.AlignmentFlag.AlignTop)
la.setLineWidth(2)
la.setStyleSheet('QLabel { margin-left: 75px }')
l.addWidget(la, 0, 2, count+1, 1)
@ -127,7 +127,7 @@ class Polish(QDialog): # {{{
sr.setToolTip(textwrap.fill(_('Show a report of all the actions performed'
' after polishing is completed')))
l.addWidget(sr, count+1, 0, 1, 1)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel)
bb.accepted.connect(self.accept)
bb.rejected.connect(self.reject)
self.save_button = sb = bb.addButton(_('&Save settings'), bb.ActionRole)
@ -194,7 +194,7 @@ class Polish(QDialog): # {{{
x.blockSignals(False)
def option_toggled(self, name, state):
if state == Qt.Checked:
if state == Qt.CheckState.Checked:
self.help_label.setText(self.help_text[name])
def help_link_activated(self, link):
@ -313,7 +313,7 @@ class Report(QDialog): # {{{
def __init__(self, parent):
QDialog.__init__(self, parent)
self.gui = parent
self.setAttribute(Qt.WA_DeleteOnClose, False)
self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, False)
self.setWindowIcon(QIcon(I('polish.png')))
self.reports = []
@ -331,7 +331,7 @@ class Report(QDialog): # {{{
self.ign = QCheckBox(_('Ignore remaining reports'), self)
l.addWidget(self.ign, 2, 0)
bb = self.bb = QDialogButtonBox(QDialogButtonBox.Close)
bb = self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close)
bb.accepted.connect(self.accept)
bb.rejected.connect(self.reject)
b = self.log_button = bb.addButton(_('View full &log'), bb.ActionRole)
@ -339,7 +339,7 @@ class Report(QDialog): # {{{
bb.button(bb.Close).setDefault(True)
l.addWidget(bb, 2, 1)
self.finished.connect(self.show_next, type=Qt.QueuedConnection)
self.finished.connect(self.show_next, type=Qt.ConnectionType.QueuedConnection)
self.resize(QSize(800, 600))
@ -361,7 +361,7 @@ class Report(QDialog): # {{{
self.setWindowTitle(_('Polishing of %s')%book_title)
self.view.setText(markdown('# %s\n\n'%book_title + report,
output_format='html4'))
self.bb.button(self.bb.Close).setFocus(Qt.OtherFocusReason)
self.bb.button(self.bb.Close).setFocus(Qt.FocusReason.OtherFocusReason)
self.backup_msg.setVisible(bool(fmts))
if fmts:
m = ngettext('The original file has been saved as %s.',

View File

@ -65,7 +65,7 @@ class PreferencesAction(InterfaceAction):
d = Preferences(self.gui, initial_plugin=initial_plugin,
close_after_initial=close_after_initial)
d.run_wizard_requested.connect(self.gui.run_wizard,
type=Qt.QueuedConnection)
type=Qt.ConnectionType.QueuedConnection)
d.exec_()
if d.do_restart:
self.gui.quit(restart=True)

View File

@ -39,9 +39,9 @@ class ShowBookDetailsAction(InterfaceAction):
if index.isValid():
d = BookInfo(self.gui, self.gui.library_view, index,
self.gui.book_details.handle_click)
d.open_cover_with.connect(self.gui.bd_open_cover_with, type=Qt.QueuedConnection)
d.open_cover_with.connect(self.gui.bd_open_cover_with, type=Qt.ConnectionType.QueuedConnection)
self.memory.append(d)
d.closed.connect(self.closed, type=Qt.QueuedConnection)
d.closed.connect(self.closed, type=Qt.ConnectionType.QueuedConnection)
d.show()
def closed(self, d):

View File

@ -17,7 +17,7 @@ class SimilarBooksAction(InterfaceAction):
name = 'Similar Books'
action_spec = (_('Similar books...'), 'similar.png', _('Show books similar to the current book'), None)
popup_type = QToolButton.InstantPopup
popup_type = QToolButton.ToolButtonPopupMode.InstantPopup
action_type = 'current'
action_add_menu = True

View File

@ -30,7 +30,7 @@ class SortByAction(InterfaceAction):
name = 'Sort By'
action_spec = (_('Sort by'), 'sort.png', _('Sort the list of books'), None)
action_type = 'current'
popup_type = QToolButton.InstantPopup
popup_type = QToolButton.ToolButtonPopupMode.InstantPopup
action_add_menu = True
dont_add_to = frozenset(('context-menu-cover-browser', ))

View File

@ -38,7 +38,7 @@ class ChooseFormat(QDialog): # {{{
self.buttons.append(b)
self.formats = gprefs.get('edit_toc_last_selected_formats', ['EPUB',])
bb = self.bb = QDialogButtonBox(
QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel)
bb.addButton(_('&All formats'),
bb.ActionRole).clicked.connect(self.do_all)
bb.accepted.connect(self.accept)

View File

@ -154,7 +154,7 @@ class TweakEpubAction(InterfaceAction):
' library maintenance.') % fmt, show=True)
tweak = 'ebook-edit'
try:
self.gui.setCursor(Qt.BusyCursor)
self.gui.setCursor(Qt.CursorShape.BusyCursor)
if tprefs['update_metadata_from_calibre']:
db.new_api.embed_metadata((book_id,), only_fmts={fmt})
notify = '%d:%s:%s:%s' % (book_id, fmt, db.library_id, db.library_path)

View File

@ -94,7 +94,7 @@ class UnpackBook(QDialog):
</ol>'''))
self.help_label.setWordWrap(True)
self._fr = QFrame()
self._fr.setFrameShape(QFrame.VLine)
self._fr.setFrameShape(QFrame.Shape.VLine)
g.addWidget(self._fr)
g.addWidget(self.help_label)

View File

@ -147,7 +147,7 @@ class ViewAction(InterfaceAction):
self._view_file(job.result)
def _launch_viewer(self, name=None, viewer='ebook-viewer', internal=True, calibre_book_data=None, open_at=None):
self.gui.setCursor(Qt.BusyCursor)
self.gui.setCursor(Qt.CursorShape.BusyCursor)
try:
if internal:
args = [viewer]

View File

@ -16,7 +16,7 @@ class VirtualLibraryAction(InterfaceAction):
)
action_type = 'current'
action_add_menu = True
popup_type = QToolButton.InstantPopup
popup_type = QToolButton.ToolButtonPopupMode.InstantPopup
dont_add_to = frozenset(('context-menu-device', 'menubar-device'))
def genesis(self):

View File

@ -82,7 +82,7 @@ class Adder(QObject):
self.list_of_archives = list_of_archives
self.callback = callback
self.add_formats_to_existing = prefs['add_formats_to_existing']
self.do_one_signal.connect(self.tick, type=Qt.QueuedConnection)
self.do_one_signal.connect(self.tick, type=Qt.ConnectionType.QueuedConnection)
self.pool = pool
self.pd = ProgressDialog(_('Adding books...'), _('Scanning for files...'), min=0, max=0, parent=parent, icon='add_book.png')
self.db = getattr(db, 'new_api', None)

View File

@ -167,12 +167,12 @@ class AutoAdder(QObject):
self.watcher = QFileSystemWatcher(self)
self.worker = Worker(path, self.metadata_read.emit)
self.watcher.directoryChanged.connect(self.dir_changed,
type=Qt.QueuedConnection)
type=Qt.ConnectionType.QueuedConnection)
self.metadata_read.connect(self.add_to_db,
type=Qt.QueuedConnection)
type=Qt.ConnectionType.QueuedConnection)
QTimer.singleShot(2000, self.initialize)
self.auto_convert.connect(self.do_auto_convert,
type=Qt.QueuedConnection)
type=Qt.ConnectionType.QueuedConnection)
elif path:
prints(path,
'is not a valid directory to watch for new ebooks, ignoring')
@ -206,7 +206,7 @@ class AutoAdder(QObject):
self.worker.join()
def __enter__(self):
QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
QApplication.setOverrideCursor(QCursor(Qt.CursorShape.WaitCursor))
def __exit__(self, *args):
QApplication.restoreOverrideCursor()

View File

@ -28,7 +28,7 @@ class RevealBar(QWidget): # {{{
self.setVisible(False)
self._animated_size = 1.0
self.animation = QPropertyAnimation(self, b'animated_size', self)
self.animation.setEasingCurve(QEasingCurve.Linear)
self.animation.setEasingCurve(QEasingCurve.Type.Linear)
self.animation.setDuration(1000), self.animation.setStartValue(0.0), self.animation.setEndValue(1.0)
self.animation.valueChanged.connect(self.animation_value_changed)
self.animation.finished.connect(self.animation_done)
@ -122,7 +122,7 @@ def wrap_all_button_texts(all_buttons):
def create_donate_button(action):
ans = ThrobbingButton()
ans.setAutoRaise(True)
ans.setCursor(Qt.PointingHandCursor)
ans.setCursor(Qt.CursorShape.PointingHandCursor)
ans.clicked.connect(action.trigger)
ans.setToolTip(action.text().replace('&', ''))
ans.setIcon(action.icon())
@ -136,8 +136,8 @@ class ToolBar(QToolBar): # {{{
QToolBar.__init__(self, parent)
self.setMovable(False)
self.setFloatable(False)
self.setOrientation(Qt.Horizontal)
self.setAllowedAreas(Qt.TopToolBarArea|Qt.BottomToolBarArea)
self.setOrientation(Qt.Orientation.Horizontal)
self.setAllowedAreas(Qt.ToolBarArea.TopToolBarArea|Qt.ToolBarArea.BottomToolBarArea)
self.setStyleSheet('QToolButton:checked { font-weight: bold }')
self.preferred_width = self.sizeHint().width()
self.gui = parent
@ -157,14 +157,14 @@ class ToolBar(QToolBar): # {{{
self.donate_button.setToolButtonStyle(style)
def get_text_style(self):
style = Qt.ToolButtonTextUnderIcon
style = Qt.ToolButtonStyle.ToolButtonTextUnderIcon
s = gprefs['toolbar_icon_size']
if s != 'off':
p = gprefs['toolbar_text']
if p == 'never':
style = Qt.ToolButtonIconOnly
style = Qt.ToolButtonStyle.ToolButtonIconOnly
elif p == 'auto' and self.preferred_width > self.width()+15:
style = Qt.ToolButtonIconOnly
style = Qt.ToolButtonStyle.ToolButtonIconOnly
return style
def contextMenuEvent(self, ev):
@ -201,7 +201,7 @@ class ToolBar(QToolBar): # {{{
for ac in self.location_manager.all_actions:
self.addAction(ac)
self.added_actions.append(ac)
self.setup_tool_button(self, ac, QToolButton.MenuButtonPopup)
self.setup_tool_button(self, ac, QToolButton.ToolButtonPopupMode.MenuButtonPopup)
ac.setVisible(False)
elif what == 'Donate':
self.donate_button = create_donate_button(self.donate_action)
@ -223,7 +223,7 @@ class ToolBar(QToolBar): # {{{
ch = bar.widgetForAction(ac)
if ch is None:
ch = self.child_bar.widgetForAction(ac)
ch.setCursor(Qt.PointingHandCursor)
ch.setCursor(Qt.CursorShape.PointingHandCursor)
if hasattr(ch, 'setText') and hasattr(ch, 'text'):
self.all_widgets.append(ch)
if hasattr(ch, 'setAutoRaise'): # is a QToolButton or similar
@ -253,7 +253,7 @@ class ToolBar(QToolBar): # {{{
md = event.mimeData()
if md.hasFormat("application/calibre+from_library") or \
md.hasFormat("application/calibre+from_device"):
event.setDropAction(Qt.CopyAction)
event.setDropAction(Qt.DropAction.CopyAction)
event.accept()
return
@ -346,7 +346,7 @@ if ismacos:
def __init__(self, clone, parent, is_top_level=False, clone_shortcuts=True):
QAction.__init__(self, clone.text().replace('&&', '&'), parent)
self.setMenuRole(QAction.NoRole) # ensure this action is not moved around by Qt
self.setMenuRole(QAction.MenuRole.NoRole) # ensure this action is not moved around by Qt
self.is_top_level = is_top_level
self.clone_shortcuts = clone_shortcuts
self.clone = clone
@ -447,7 +447,7 @@ if ismacos:
def adapt_for_dialog(self, enter):
def ac(text, key, role=QAction.TextHeuristicRole):
def ac(text, key, role=QAction.MenuRole.TextHeuristicRole):
ans = QAction(text, self)
ans.setMenuRole(role)
ans.setShortcut(QKeySequence(key))
@ -460,9 +460,9 @@ if ismacos:
self.edit_menu = QMenu()
self.edit_action = QAction(_('Edit'), self)
self.edit_action.setMenu(self.edit_menu)
ac(_('Copy'), QKeySequence.Copy),
ac(_('Paste'), QKeySequence.Paste),
ac(_('Select all'), QKeySequence.SelectAll),
ac(_('Copy'), QKeySequence.StandardKey.Copy),
ac(_('Paste'), QKeySequence.StandardKey.Paste),
ac(_('Select all'), QKeySequence.StandardKey.SelectAll),
mb.addAction(self.edit_action)
self.added_actions = [self.edit_action]
else:
@ -705,9 +705,9 @@ class BarsManager(QObject):
def apply_settings(self):
sz = gprefs['toolbar_icon_size']
sz = {'off':0, 'small':24, 'medium':48, 'large':64}[sz]
style = Qt.ToolButtonTextUnderIcon
style = Qt.ToolButtonStyle.ToolButtonTextUnderIcon
if sz > 0 and gprefs['toolbar_text'] == 'never':
style = Qt.ToolButtonIconOnly
style = Qt.ToolButtonStyle.ToolButtonIconOnly
for bar in self.bars:
bar.setIconSize(QSize(sz, sz))

View File

@ -380,7 +380,7 @@ def details_context_menu_event(view, ev, book_info, add_popup_action=False, edit
else:
from calibre.gui2.ui import get_gui
ema = get_gui().iactions['Edit Metadata'].menuless_qaction
menu.addAction(_('Open the Edit metadata window') + '\t' + ema.shortcut().toString(QKeySequence.NativeText), edit_metadata)
menu.addAction(_('Open the Edit metadata window') + '\t' + ema.shortcut().toString(QKeySequence.SequenceFormat.NativeText), edit_metadata)
if len(menu.actions()) > 0:
menu.exec_(ev.globalPos())
# }}}
@ -418,14 +418,14 @@ class CoverView(QWidget): # {{{
self.vertical = vertical
self.animation = QPropertyAnimation(self, b'current_pixmap_size', self)
self.animation.setEasingCurve(QEasingCurve(QEasingCurve.OutExpo))
self.animation.setEasingCurve(QEasingCurve(QEasingCurve.Type.OutExpo))
self.animation.setDuration(1000)
self.animation.setStartValue(QSize(0, 0))
self.animation.valueChanged.connect(self.value_changed)
self.setSizePolicy(
QSizePolicy.Expanding if vertical else QSizePolicy.Minimum,
QSizePolicy.Expanding)
QSizePolicy.Policy.Expanding if vertical else QSizePolicy.Policy.Minimum,
QSizePolicy.Policy.Expanding)
self.default_pixmap = QPixmap(I('default_cover.png'))
self.pixmap = self.default_pixmap
@ -485,12 +485,12 @@ class CoverView(QWidget): # {{{
y = int(extray//2)
target = QRect(x, y, width, height)
p = QPainter(self)
p.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
p.setRenderHints(QPainter.RenderHint.Antialiasing | QPainter.RenderHint.SmoothPixmapTransform)
try:
dpr = self.devicePixelRatioF()
except AttributeError:
dpr = self.devicePixelRatio()
spmap = self.pixmap.scaled(target.size() * dpr, Qt.KeepAspectRatio, Qt.SmoothTransformation)
spmap = self.pixmap.scaled(target.size() * dpr, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)
spmap.setDevicePixelRatio(dpr)
p.drawPixmap(target, spmap)
if gprefs['bd_overlay_cover_size']:
@ -499,7 +499,7 @@ class CoverView(QWidget): # {{{
f.setBold(True)
p.setFont(f)
sz = '\u00a0%d x %d\u00a0'%(self.pixmap.width(), self.pixmap.height())
flags = Qt.AlignBottom|Qt.AlignRight|Qt.TextSingleLine
flags = Qt.AlignmentFlag.AlignBottom|Qt.AlignmentFlag.AlignRight|Qt.TextFlag.TextSingleLine
szrect = p.boundingRect(sztgt, flags, sz)
p.fillRect(szrect.adjusted(0, 0, 0, 4), QColor(0, 0, 0, 200))
p.setPen(QPen(QColor(255,255,255)))
@ -662,7 +662,7 @@ class BookInfo(HTMLDisplay):
self.remove_item_action = ac = QAction(QIcon(I('minus.png')), '...', self)
ac.data = (None, None, None)
ac.triggered.connect(self.remove_item_triggered)
self.setFocusPolicy(Qt.NoFocus)
self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.setDefaultStyleSheet(css())
def refresh_css(self):
@ -867,7 +867,7 @@ class BookDetails(QWidget): # {{{
event.acceptProposedAction()
def dropEvent(self, event):
event.setDropAction(Qt.CopyAction)
event.setDropAction(Qt.DropAction.CopyAction)
md = event.mimeData()
image_exts = set(image_extensions()) - set(tweaks['cover_drop_exclude'])
@ -936,7 +936,7 @@ class BookDetails(QWidget): # {{{
self.book_info.manage_category.connect(self.manage_category)
self.book_info.find_in_tag_browser.connect(self.find_in_tag_browser)
self.book_info.edit_identifiers.connect(self.edit_identifiers)
self.setCursor(Qt.PointingHandCursor)
self.setCursor(Qt.CursorShape.PointingHandCursor)
def search_internet(self, data):
if self.last_data:
@ -954,7 +954,7 @@ class BookDetails(QWidget): # {{{
def browse(url):
try:
safe_open_url(QUrl(url, QUrl.TolerantMode))
safe_open_url(QUrl(url, QUrl.ParsingMode.TolerantMode))
except Exception:
import traceback
traceback.print_exc()

View File

@ -53,7 +53,7 @@ class PluginWidget(QWidget):
l.addWidget(la)
self.db_fields.setDragEnabled(True)
self.db_fields.setDragDropMode(QListWidget.InternalMove)
self.db_fields.setDefaultDropAction(Qt.CopyAction if ismacos else Qt.MoveAction)
self.db_fields.setDefaultDropAction(Qt.DropAction.CopyAction if ismacos else Qt.DropAction.MoveAction)
self.db_fields.setAlternatingRowColors(True)
self.db_fields.setObjectName("db_fields")
@ -79,24 +79,24 @@ class PluginWidget(QWidget):
self.db_fields.clear()
for x in sorted(self.all_fields, key=key):
QListWidgetItem(name(x) + ' (%s)' % x, self.db_fields).setData(Qt.UserRole, x)
QListWidgetItem(name(x) + ' (%s)' % x, self.db_fields).setData(Qt.ItemDataRole.UserRole, x)
if x.startswith('#') and fm[x]['datatype'] == 'series':
x += '_index'
QListWidgetItem(name(x) + ' (%s)' % x, self.db_fields).setData(Qt.UserRole, x)
QListWidgetItem(name(x) + ' (%s)' % x, self.db_fields).setData(Qt.ItemDataRole.UserRole, x)
# Restore the activated fields from last use
for x in range(self.db_fields.count()):
item = self.db_fields.item(x)
item.setCheckState(Qt.Checked if unicode_type(item.data(Qt.UserRole)) in fields else Qt.Unchecked)
item.setCheckState(Qt.CheckState.Checked if unicode_type(item.data(Qt.ItemDataRole.UserRole)) in fields else Qt.CheckState.Unchecked)
def options(self):
# Save the currently activated fields
fields, all_fields = [], []
for x in range(self.db_fields.count()):
item = self.db_fields.item(x)
all_fields.append(unicode_type(item.data(Qt.UserRole)))
if item.checkState() == Qt.Checked:
fields.append(unicode_type(item.data(Qt.UserRole)))
all_fields.append(unicode_type(item.data(Qt.ItemDataRole.UserRole)))
if item.checkState() == Qt.CheckState.Checked:
fields.append(unicode_type(item.data(Qt.ItemDataRole.UserRole)))
set_saved_field_data(self.name, fields, {x:i for i, x in enumerate(all_fields)})
# Return a dictionary with current options for this widget

View File

@ -845,26 +845,26 @@ class CheckableTableWidgetItem(QTableWidgetItem):
def __init__(self, checked=False, is_tristate=False):
QTableWidgetItem.__init__(self, '')
self.setFlags(Qt.ItemFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled))
self.setFlags(Qt.ItemFlags(Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsUserCheckable | Qt.ItemFlag.ItemIsEnabled))
if is_tristate:
self.setFlags(self.flags() | Qt.ItemIsTristate)
self.setFlags(self.flags() | Qt.ItemFlag.ItemIsTristate)
if checked:
self.setCheckState(Qt.Checked)
self.setCheckState(Qt.CheckState.Checked)
else:
if is_tristate and checked is None:
self.setCheckState(Qt.PartiallyChecked)
self.setCheckState(Qt.CheckState.PartiallyChecked)
else:
self.setCheckState(Qt.Unchecked)
self.setCheckState(Qt.CheckState.Unchecked)
def get_boolean_value(self):
'''
Return a boolean value indicating whether checkbox is checked
If this is a tristate checkbox, a partially checked value is returned as None
'''
if self.checkState() == Qt.PartiallyChecked:
if self.checkState() == Qt.CheckState.PartiallyChecked:
return None
else:
return self.checkState() == Qt.Checked
return self.checkState() == Qt.CheckState.Checked
class NoWheelComboBox(QComboBox):
@ -911,7 +911,7 @@ class GenericRulesTable(QTableWidget):
self.layout = parent_gb.layout()
# Add ourselves to the layout
sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)
sizePolicy = QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
# sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
@ -1206,7 +1206,7 @@ class ExclusionRules(GenericRulesTable):
self.setColumnCount(len(header_labels))
self.setHorizontalHeaderLabels(header_labels)
self.setSortingEnabled(False)
self.setSelectionBehavior(QAbstractItemView.SelectRows)
self.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
def _initialize(self):
self.populate_table()
@ -1218,7 +1218,7 @@ class ExclusionRules(GenericRulesTable):
def convert_row_to_data(self, row):
data = self.create_blank_row_data()
data['ordinal'] = row
data['enabled'] = self.item(row,self.COLUMNS['ENABLED']['ordinal']).checkState() == Qt.Checked
data['enabled'] = self.item(row,self.COLUMNS['ENABLED']['ordinal']).checkState() == Qt.CheckState.Checked
data['name'] = unicode_type(self.cellWidget(row,self.COLUMNS['NAME']['ordinal']).text()).strip()
data['field'] = unicode_type(self.cellWidget(row,self.COLUMNS['FIELD']['ordinal']).currentText()).strip()
data['pattern'] = unicode_type(self.cellWidget(row,self.COLUMNS['PATTERN']['ordinal']).currentText()).strip()
@ -1299,7 +1299,7 @@ class PrefixRules(GenericRulesTable):
self.setColumnCount(len(header_labels))
self.setHorizontalHeaderLabels(header_labels)
self.setSortingEnabled(False)
self.setSelectionBehavior(QAbstractItemView.SelectRows)
self.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
def _initialize(self):
self.generate_prefix_list()
@ -1312,7 +1312,7 @@ class PrefixRules(GenericRulesTable):
def convert_row_to_data(self, row):
data = self.create_blank_row_data()
data['ordinal'] = row
data['enabled'] = self.item(row,self.COLUMNS['ENABLED']['ordinal']).checkState() == Qt.Checked
data['enabled'] = self.item(row,self.COLUMNS['ENABLED']['ordinal']).checkState() == Qt.CheckState.Checked
data['name'] = unicode_type(self.cellWidget(row,self.COLUMNS['NAME']['ordinal']).text()).strip()
data['prefix'] = unicode_type(self.cellWidget(row,self.COLUMNS['PREFIX']['ordinal']).currentText()).strip()
data['field'] = unicode_type(self.cellWidget(row,self.COLUMNS['FIELD']['ordinal']).currentText()).strip()

View File

@ -333,15 +333,15 @@ class EditorWidget(QTextEdit, LineEditECM): # {{{
self.update_cursor_position_actions()
def keyPressEvent(self, ev):
if ev.matches(QKeySequence.Bold):
if ev.matches(QKeySequence.StandardKey.Bold):
ev.accept()
self.action_bold.toggle(), self.action_bold.trigger()
return
if ev.matches(QKeySequence.Italic):
if ev.matches(QKeySequence.StandardKey.Italic):
ev.accept()
self.action_italic.toggle(), self.action_italic.trigger()
return
if ev.matches(QKeySequence.Underline):
if ev.matches(QKeySequence.StandardKey.Underline):
ev.accept()
self.action_underline.toggle(), self.action_underline.trigger()
return
@ -357,22 +357,22 @@ class EditorWidget(QTextEdit, LineEditECM): # {{{
def update_cursor_position_actions(self):
c = self.textCursor()
ls = c.currentList()
self.action_ordered_list.setChecked(ls is not None and ls.format().style() == QTextListFormat.ListDecimal)
self.action_unordered_list.setChecked(ls is not None and ls.format().style() == QTextListFormat.ListDisc)
self.action_ordered_list.setChecked(ls is not None and ls.format().style() == QTextListFormat.Style.ListDecimal)
self.action_unordered_list.setChecked(ls is not None and ls.format().style() == QTextListFormat.Style.ListDisc)
tcf = c.charFormat()
vert = tcf.verticalAlignment()
self.action_superscript.setChecked(vert == QTextCharFormat.AlignSuperScript)
self.action_subscript.setChecked(vert == QTextCharFormat.AlignSubScript)
self.action_bold.setChecked(tcf.fontWeight() == QFont.Bold)
self.action_superscript.setChecked(vert == QTextCharFormat.VerticalAlignment.AlignSuperScript)
self.action_subscript.setChecked(vert == QTextCharFormat.VerticalAlignment.AlignSubScript)
self.action_bold.setChecked(tcf.fontWeight() == QFont.Weight.Bold)
self.action_italic.setChecked(tcf.fontItalic())
self.action_underline.setChecked(tcf.fontUnderline())
self.action_strikethrough.setChecked(tcf.fontStrikeOut())
bf = c.blockFormat()
a = bf.alignment()
self.action_align_left.setChecked(a == Qt.AlignLeft)
self.action_align_right.setChecked(a == Qt.AlignRight)
self.action_align_center.setChecked(a == Qt.AlignHCenter)
self.action_align_justified.setChecked(a == Qt.AlignJustify)
self.action_align_left.setChecked(a == Qt.AlignmentFlag.AlignLeft)
self.action_align_right.setChecked(a == Qt.AlignmentFlag.AlignRight)
self.action_align_center.setChecked(a == Qt.AlignmentFlag.AlignHCenter)
self.action_align_justified.setChecked(a == Qt.AlignmentFlag.AlignJustify)
lvl = bf.headingLevel()
name = 'p'
if lvl == 0:
@ -387,13 +387,13 @@ class EditorWidget(QTextEdit, LineEditECM): # {{{
self.readonly = what
def focus_self(self):
self.setFocus(Qt.TabFocusReason)
self.setFocus(Qt.FocusReason.TabFocusReason)
def do_clear(self, *args):
c = self.textCursor()
c.beginEditBlock()
c.movePosition(QTextCursor.Start, QTextCursor.MoveAnchor)
c.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
c.movePosition(QTextCursor.MoveOperation.Start, QTextCursor.MoveMode.MoveAnchor)
c.movePosition(QTextCursor.MoveOperation.End, QTextCursor.MoveMode.KeepAnchor)
c.removeSelectedText()
c.endEditBlock()
self.focus_self()
@ -403,7 +403,7 @@ class EditorWidget(QTextEdit, LineEditECM): # {{{
with self.editing_cursor() as c:
fmt = QTextCharFormat()
fmt.setFontWeight(
QFont.Bold if c.charFormat().fontWeight() != QFont.Bold else QFont.Normal)
QFont.Weight.Bold if c.charFormat().fontWeight() != QFont.Weight.Bold else QFont.Weight.Normal)
c.mergeCharFormat(fmt)
def do_italic(self):
@ -431,10 +431,10 @@ class EditorWidget(QTextEdit, LineEditECM): # {{{
c.mergeCharFormat(fmt)
def do_superscript(self):
self.do_vertical_align(QTextCharFormat.AlignSuperScript)
self.do_vertical_align(QTextCharFormat.VerticalAlignment.AlignSuperScript)
def do_subscript(self):
self.do_vertical_align(QTextCharFormat.AlignSubScript)
self.do_vertical_align(QTextCharFormat.VerticalAlignment.AlignSubScript)
def do_list(self, fmt):
with self.editing_cursor() as c:
@ -450,10 +450,10 @@ class EditorWidget(QTextEdit, LineEditECM): # {{{
ls = c.createList(fmt)
def do_ordered_list(self):
self.do_list(QTextListFormat.ListDecimal)
self.do_list(QTextListFormat.Style.ListDecimal)
def do_unordered_list(self):
self.do_list(QTextListFormat.ListDisc)
self.do_list(QTextListFormat.Style.ListDisc)
def do_alignment(self, which):
with self.editing_cursor() as c:
@ -462,16 +462,16 @@ class EditorWidget(QTextEdit, LineEditECM): # {{{
c.setBlockFormat(fmt)
def do_align_left(self):
self.do_alignment(Qt.AlignLeft)
self.do_alignment(Qt.AlignmentFlag.AlignLeft)
def do_align_center(self):
self.do_alignment(Qt.AlignHCenter)
self.do_alignment(Qt.AlignmentFlag.AlignHCenter)
def do_align_right(self):
self.do_alignment(Qt.AlignRight)
self.do_alignment(Qt.AlignmentFlag.AlignRight)
def do_align_justified(self):
self.do_alignment(Qt.AlignJustify)
self.do_alignment(Qt.AlignmentFlag.AlignJustify)
def do_undo(self):
self.undo()
@ -517,8 +517,8 @@ class EditorWidget(QTextEdit, LineEditECM): # {{{
def do_select_all(self):
with self.editing_cursor() as c:
c.movePosition(QTextCursor.Start, QTextCursor.MoveAnchor)
c.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
c.movePosition(QTextCursor.MoveOperation.Start, QTextCursor.MoveMode.MoveAnchor)
c.movePosition(QTextCursor.MoveOperation.End, QTextCursor.MoveMode.KeepAnchor)
def level_for_block_type(self, name):
if name == 'blockquote':
@ -532,13 +532,13 @@ class EditorWidget(QTextEdit, LineEditECM): # {{{
cf = QTextCharFormat()
bcf = c.blockCharFormat()
lvl = self.level_for_block_type(name)
wt = QFont.Bold if lvl else None
wt = QFont.Weight.Bold if lvl else None
adjust = (0, 3, 2, 1, 0, -1, -1)[lvl]
pos = None
if not c.hasSelection():
pos = c.position()
c.movePosition(QTextCursor.StartOfBlock, QTextCursor.MoveAnchor)
c.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor)
c.movePosition(QTextCursor.MoveOperation.StartOfBlock, QTextCursor.MoveMode.MoveAnchor)
c.movePosition(QTextCursor.MoveOperation.EndOfBlock, QTextCursor.MoveMode.KeepAnchor)
# margin values are taken from qtexthtmlparser.cpp
hmargin = 0
if name == 'blockquote':
@ -570,8 +570,8 @@ class EditorWidget(QTextEdit, LineEditECM): # {{{
c.setPosition(pos)
def do_color(self):
col = QColorDialog.getColor(Qt.black, self,
_('Choose foreground color'), QColorDialog.ShowAlphaChannel)
col = QColorDialog.getColor(Qt.GlobalColor.black, self,
_('Choose foreground color'), QColorDialog.ColorDialogOption.ShowAlphaChannel)
if col.isValid():
fmt = QTextCharFormat()
fmt.setForeground(QBrush(col))
@ -579,8 +579,8 @@ class EditorWidget(QTextEdit, LineEditECM): # {{{
c.mergeCharFormat(fmt)
def do_background(self):
col = QColorDialog.getColor(Qt.white, self,
_('Choose background color'), QColorDialog.ShowAlphaChannel)
col = QColorDialog.getColor(Qt.GlobalColor.white, self,
_('Choose background color'), QColorDialog.ColorDialogOption.ShowAlphaChannel)
if col.isValid():
fmt = QTextCharFormat()
fmt.setBackground(QBrush(col))
@ -608,7 +608,7 @@ class EditorWidget(QTextEdit, LineEditECM): # {{{
fmt = QTextCharFormat()
fmt.setAnchor(True)
fmt.setAnchorHref(url)
fmt.setForeground(QBrush(self.palette().color(QPalette.Link)))
fmt.setForeground(QBrush(self.palette().color(QPalette.ColorRole.Link)))
if name or not c.hasSelection():
c.mergeCharFormat(fmt)
c.insertText(name or url)
@ -643,13 +643,13 @@ class EditorWidget(QTextEdit, LineEditECM): # {{{
d = Ask(self)
d.setWindowTitle(_('Create link'))
l = QFormLayout()
l.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow)
l.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow)
d.setLayout(l)
d.url = QLineEdit(d)
d.name = QLineEdit(d)
d.treat_as_image = QCheckBox(d)
d.setMinimumWidth(600)
d.bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
d.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel)
d.br = b = QPushButton(_('&Browse'))
b.setIcon(QIcon(I('document_open.png')))
@ -698,7 +698,7 @@ class EditorWidget(QTextEdit, LineEditECM): # {{{
return QUrl.fromLocalFile(link)
has_schema = re.match(r'^[a-zA-Z]+:', link)
if has_schema is not None:
url = QUrl(link, QUrl.TolerantMode)
url = QUrl(link, QUrl.ParsingMode.TolerantMode)
if url.isValid():
return url
if os.path.exists(link):
@ -709,11 +709,11 @@ class EditorWidget(QTextEdit, LineEditECM): # {{{
prefix = 'http'
if first == 'ftp':
prefix = 'ftp'
url = QUrl(prefix +'://'+link, QUrl.TolerantMode)
url = QUrl(prefix +'://'+link, QUrl.ParsingMode.TolerantMode)
if url.isValid():
return url
return QUrl(link, QUrl.TolerantMode)
return QUrl(link, QUrl.ParsingMode.TolerantMode)
def sizeHint(self):
return QSize(150, 150)
@ -785,8 +785,8 @@ class EditorWidget(QTextEdit, LineEditECM): # {{{
self.html = val
return
with self.editing_cursor() as c:
c.movePosition(QTextCursor.Start, QTextCursor.MoveAnchor)
c.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
c.movePosition(QTextCursor.MoveOperation.Start, QTextCursor.MoveMode.MoveAnchor)
c.movePosition(QTextCursor.MoveOperation.End, QTextCursor.MoveMode.KeepAnchor)
c.removeSelectedText()
c.insertHtml(val)
@ -801,7 +801,7 @@ class EditorWidget(QTextEdit, LineEditECM): # {{{
menu = self.createStandardContextMenu()
for action in menu.actions():
parts = action.text().split('\t')
if len(parts) == 2 and QKeySequence(QKeySequence.Paste).toString(QKeySequence.NativeText) in parts[-1]:
if len(parts) == 2 and QKeySequence(QKeySequence.StandardKey.Paste).toString(QKeySequence.SequenceFormat.NativeText) in parts[-1]:
menu.insertAction(action, self.action_paste_and_match_style)
break
else:

View File

@ -67,7 +67,7 @@ class CompleteModel(QAbstractListModel): # {{{
return len(self.current_items)
def data(self, index, role):
if role == Qt.DisplayRole:
if role == Qt.ItemDataRole.DisplayRole:
try:
return self.current_items[index.row()]
except IndexError:
@ -88,10 +88,10 @@ class Completer(QListView): # {{{
def __init__(self, completer_widget, max_visible_items=7, sort_func=sort_key, strip_completion_entries=True):
QListView.__init__(self, completer_widget)
self.disable_popup = False
self.setWindowFlags(Qt.Popup)
self.setWindowFlags(Qt.WindowType.Popup)
self.max_visible_items = max_visible_items
self.setEditTriggers(self.NoEditTriggers)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.setSelectionBehavior(self.SelectRows)
self.setSelectionMode(self.SingleSelection)
self.setUniformItemSizes(True)
@ -101,7 +101,7 @@ class Completer(QListView): # {{{
self.activated.connect(self.item_chosen)
self.pressed.connect(self.item_chosen)
self.installEventFilter(self)
self.setFocusPolicy(Qt.NoFocus)
self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
def hide(self):
self.setCurrentIndex(QModelIndex())
@ -111,7 +111,7 @@ class Completer(QListView): # {{{
if not self.isVisible():
return
self.hide()
text = self.model().data(index, Qt.DisplayRole)
text = self.model().data(index, Qt.ItemDataRole.DisplayRole)
self.item_selected.emit(unicode_type(text))
def set_items(self, items):
@ -211,15 +211,15 @@ class Completer(QListView): # {{{
key = e.key()
except AttributeError:
return QObject.eventFilter(self, obj, e)
if key == Qt.Key_Escape:
if key == Qt.Key.Key_Escape:
self.hide()
e.accept()
return True
if key == Qt.Key_F4 and e.modifiers() & Qt.AltModifier:
if key == Qt.Key.Key_F4 and e.modifiers() & Qt.KeyboardModifier.AltModifier:
self.hide()
e.accept()
return True
if key in (Qt.Key_Enter, Qt.Key_Return):
if key in (Qt.Key.Key_Enter, Qt.Key.Key_Return):
# We handle this explicitly because on OS X activated() is
# not emitted on pressing Enter.
idx = self.currentIndex()
@ -228,7 +228,7 @@ class Completer(QListView): # {{{
self.hide()
e.accept()
return True
if key == Qt.Key_Tab:
if key == Qt.Key.Key_Tab:
idx = self.currentIndex()
if idx.isValid():
self.item_chosen(idx)
@ -237,11 +237,11 @@ class Completer(QListView): # {{{
self.next_match()
e.accept()
return True
if key in (Qt.Key_PageUp, Qt.Key_PageDown):
if key in (Qt.Key.Key_PageUp, Qt.Key.Key_PageDown):
# Let the list view handle these keys
return False
if key in (Qt.Key_Up, Qt.Key_Down):
self.next_match(previous=key == Qt.Key_Up)
if key in (Qt.Key.Key_Up, Qt.Key.Key_Down):
self.next_match(previous=key == Qt.Key.Key_Up)
e.accept()
return True
# Send to widget
@ -253,7 +253,7 @@ class Completer(QListView): # {{{
self.hide()
if e.isAccepted():
return True
elif ismacos and etype == e.InputMethodQuery and e.queries() == (Qt.ImHints | Qt.ImEnabled) and self.isVisible():
elif ismacos and etype == e.InputMethodQuery and e.queries() == (Qt.InputMethodQuery.ImHints | Qt.InputMethodQuery.ImEnabled) and self.isVisible():
# In Qt 5 the Esc key causes this event and the line edit does not
# handle it, which causes the parent dialog to be closed
# See https://bugreports.qt-project.org/browse/QTBUG-41806
@ -266,8 +266,8 @@ class Completer(QListView): # {{{
# arrow of the combobox closes the popup
opt = QStyleOptionComboBox()
widget.initStyleOption(opt)
sc = widget.style().hitTestComplexControl(QStyle.CC_ComboBox, opt, widget.mapFromGlobal(e.globalPos()), widget)
if sc == QStyle.SC_ComboBoxArrow:
sc = widget.style().hitTestComplexControl(QStyle.ComplexControl.CC_ComboBox, opt, widget.mapFromGlobal(e.globalPos()), widget)
if sc == QStyle.SubControl.SC_ComboBoxArrow:
QTimer.singleShot(0, self.hide)
e.accept()
return True
@ -304,7 +304,7 @@ class LineEdit(QLineEdit, LineEditECM):
self.mcompleter = Completer(completer_widget, sort_func=sort_func, strip_completion_entries=strip_completion_entries)
self.mcompleter.item_selected.connect(self.completion_selected,
type=Qt.QueuedConnection)
type=Qt.ConnectionType.QueuedConnection)
self.mcompleter.relayout_needed.connect(self.relayout)
self.mcompleter.setFocusProxy(completer_widget)
self.textEdited.connect(self.text_edited)
@ -344,7 +344,7 @@ class LineEdit(QLineEdit, LineEditECM):
# See https://bugreports.qt.io/browse/QTBUG-46911
try:
if ev.type() == ev.ShortcutOverride and (
ev.key() in (Qt.Key_Left, Qt.Key_Right) and (ev.modifiers() & ~Qt.KeypadModifier) == Qt.ControlModifier):
ev.key() in (Qt.Key.Key_Left, Qt.Key.Key_Right) and (ev.modifiers() & ~Qt.KeyboardModifier.KeypadModifier) == Qt.KeyboardModifier.ControlModifier):
ev.accept()
except AttributeError:
pass
@ -359,12 +359,12 @@ class LineEdit(QLineEdit, LineEditECM):
self.mcompleter.hide()
return
self.mcompleter.popup(select_first=select_first)
self.setFocus(Qt.OtherFocusReason)
self.setFocus(Qt.FocusReason.OtherFocusReason)
self.mcompleter.scroll_to(orig)
def relayout(self):
self.mcompleter.popup()
self.setFocus(Qt.OtherFocusReason)
self.setFocus(Qt.FocusReason.OtherFocusReason)
def text_edited(self, *args):
if self.no_popup:

View File

@ -240,13 +240,13 @@ class Widget(QWidget):
else:
g.setCurrentIndex(0)
elif isinstance(g, QComboBox) and val:
idx = g.findText(val, Qt.MatchFixedString)
idx = g.findText(val, Qt.MatchFlag.MatchFixedString)
if idx < 0:
g.addItem(val)
idx = g.findText(val, Qt.MatchFixedString)
idx = g.findText(val, Qt.MatchFlag.MatchFixedString)
g.setCurrentIndex(idx)
elif isinstance(g, QCheckBox):
g.setCheckState(Qt.Checked if bool(val) else Qt.Unchecked)
g.setCheckState(Qt.CheckState.Checked if bool(val) else Qt.CheckState.Unchecked)
elif isinstance(g, (XPathEdit, RegexEdit)):
g.edit.setText(val if val else '')
else:

View File

@ -34,7 +34,7 @@ class PluginWidget(Widget):
self.opt_docx_page_size = QComboBox(self)
l.addRow(_('Paper si&ze:'), self.opt_docx_page_size)
self.opt_docx_custom_page_size = w = QLineEdit(self)
w.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
w.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
l.addRow(_('&Custom size:'), w)
for i, text in enumerate((_('Page &left margin'), _('Page &top margin'), _('Page &right margin'), _('Page &bottom margin'))):
m = 'left top right bottom'.split()[i]

View File

@ -101,11 +101,11 @@ class HeuristicsWidget(Widget, Ui_Form):
gprefs['replace_scene_breaks_history'] = rssb_history
def enable_heuristics(self, state):
state = state == Qt.Checked
state = state == Qt.CheckState.Checked
self.heuristic_options.setEnabled(state)
def enable_unwrap(self, state):
if state == Qt.Checked:
if state == Qt.CheckState.Checked:
state = True
else:
state = False

View File

@ -49,9 +49,9 @@ class LookAndFeelWidget(Widget, Ui_Form):
self.opt_remove_paragraph_spacing.toggle()
self.opt_remove_paragraph_spacing.toggle()
connect_lambda(self.opt_smarten_punctuation.stateChanged, self, lambda self, state:
state != Qt.Unchecked and self.opt_unsmarten_punctuation.setCheckState(Qt.Unchecked))
state != Qt.CheckState.Unchecked and self.opt_unsmarten_punctuation.setCheckState(Qt.CheckState.Unchecked))
connect_lambda(self.opt_unsmarten_punctuation.stateChanged, self, lambda self, state:
state != Qt.Unchecked and self.opt_smarten_punctuation.setCheckState(Qt.Unchecked))
state != Qt.CheckState.Unchecked and self.opt_smarten_punctuation.setCheckState(Qt.CheckState.Unchecked))
def get_value_handler(self, g):
if g is self.opt_change_justification:

View File

@ -26,11 +26,11 @@ class ProfileModel(QAbstractListModel):
def data(self, index, role):
profile = self.profiles[index.row()]
if role == Qt.DisplayRole:
if role == Qt.ItemDataRole.DisplayRole:
if profile.name.startswith('Default '):
return _('Default profile')
return profile.name
if role in (Qt.ToolTipRole, Qt.StatusTipRole, Qt.WhatsThisRole):
if role in (Qt.ItemDataRole.ToolTipRole, Qt.ItemDataRole.StatusTipRole, Qt.ItemDataRole.WhatsThisRole):
w, h = profile.screen_size
if w >= 10000:
ss = _('unlimited')
@ -69,7 +69,7 @@ class PageSetupWidget(Widget, Ui_Form):
self.opt_output_profile.setToolTip('<p>'+it.replace('t.','ce.\n<br>'))
def show_desc(self, index):
desc = unicode_type(index.model().data(index, Qt.StatusTipRole) or '')
desc = unicode_type(index.model().data(index, Qt.ItemDataRole.StatusTipRole) or '')
self.profile_description.setText(desc)
def connect_gui_obj_handler(self, g, slot):

View File

@ -31,7 +31,7 @@ class RegexBuilder(QDialog, Ui_RegexBuilder):
self.regex_valid()
if not db or not book_id:
button = self.button_box.addButton(QDialogButtonBox.Open)
button = self.button_box.addButton(QDialogButtonBox.StandardButton.Open)
button.clicked.connect(self.open_clicked)
elif not doc and not self.select_format(db, book_id):
self.cancelled = True
@ -88,12 +88,12 @@ class RegexBuilder(QDialog, Ui_RegexBuilder):
cursor = QTextCursor(self.preview.document())
extsel = QTextEdit.ExtraSelection()
extsel.cursor = cursor
extsel.format.setBackground(QBrush(Qt.yellow))
extsel.format.setBackground(QBrush(Qt.GlobalColor.yellow))
try:
for match in compile_regular_expression(regex).finditer(text):
es = QTextEdit.ExtraSelection(extsel)
es.cursor.setPosition(match.start(), QTextCursor.MoveAnchor)
es.cursor.setPosition(match.end(), QTextCursor.KeepAnchor)
es.cursor.setPosition(match.start(), QTextCursor.MoveMode.MoveAnchor)
es.cursor.setPosition(match.end(), QTextCursor.MoveMode.KeepAnchor)
selections.append(es)
self.match_locs.append((match.start(), match.end()))
except:
@ -113,7 +113,7 @@ class RegexBuilder(QDialog, Ui_RegexBuilder):
if pos > loc:
match_loc = i
break
self.goto_loc(self.match_locs[match_loc][1], operation=QTextCursor.Left, n=self.match_locs[match_loc][1] - self.match_locs[match_loc][0])
self.goto_loc(self.match_locs[match_loc][1], operation=QTextCursor.MoveOperation.Left, n=self.match_locs[match_loc][1] - self.match_locs[match_loc][0])
def goto_next(self):
pos = self.preview.textCursor().position()
@ -126,7 +126,7 @@ class RegexBuilder(QDialog, Ui_RegexBuilder):
break
self.goto_loc(self.match_locs[match_loc][0], n=self.match_locs[match_loc][1] - self.match_locs[match_loc][0])
def goto_loc(self, loc, operation=QTextCursor.Right, mode=QTextCursor.KeepAnchor, n=0):
def goto_loc(self, loc, operation=QTextCursor.MoveOperation.Right, mode=QTextCursor.MoveMode.KeepAnchor, n=0):
cursor = QTextCursor(self.preview.document())
cursor.setPosition(loc)
if n:
@ -141,7 +141,7 @@ class RegexBuilder(QDialog, Ui_RegexBuilder):
elif len(formats) > 1:
d = ChooseFormatDialog(self, _('Choose the format to view'), formats)
d.exec_()
if d.result() == QDialog.Accepted:
if d.result() == QDialog.DialogCode.Accepted:
format = d.format()
else:
return False
@ -208,7 +208,7 @@ class RegexEdit(QWidget, Ui_Edit):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.setupUi(self)
self.edit.completer().setCaseSensitivity(Qt.CaseSensitive)
self.edit.completer().setCaseSensitivity(Qt.CaseSensitivity.CaseSensitive)
self.book_id = None
self.db = None

View File

@ -48,7 +48,7 @@ class SearchAndReplaceWidget(Widget, Ui_Form):
self.sr_search.doc_update.connect(self.update_doc)
proto = QTableWidgetItem()
proto.setFlags(Qt.ItemFlags(Qt.ItemIsSelectable + Qt.ItemIsEnabled))
proto.setFlags(Qt.ItemFlags(Qt.ItemFlag.ItemIsSelectable + Qt.ItemFlag.ItemIsEnabled))
self.search_replace.setItemPrototype(proto)
self.search_replace.setColumnCount(2)
self.search_replace.setColumnWidth(0, 320)

View File

@ -45,11 +45,11 @@ class GroupModel(QAbstractListModel):
widget = self.widgets[index.row()]
except:
return None
if role == Qt.DisplayRole:
if role == Qt.ItemDataRole.DisplayRole:
return (widget.config_title())
if role == Qt.DecorationRole:
if role == Qt.ItemDataRole.DecorationRole:
return (widget.config_icon())
if role == Qt.FontRole:
if role == Qt.ItemDataRole.FontRole:
f = QFont()
f.setBold(True)
return (f)
@ -109,26 +109,26 @@ class Config(QDialog):
self.input_label.setObjectName("input_label")
self.horizontalLayout.addWidget(self.input_label)
self.input_formats = QComboBox(self)
self.input_formats.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLengthWithIcon)
self.input_formats.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon)
self.input_formats.setMinimumContentsLength(5)
self.input_formats.setObjectName("input_formats")
self.horizontalLayout.addWidget(self.input_formats)
self.opt_individual_saved_settings = QCheckBox(self)
self.opt_individual_saved_settings.setObjectName("opt_individual_saved_settings")
self.horizontalLayout.addWidget(self.opt_individual_saved_settings)
spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
spacerItem = QSpacerItem(40, 20, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum)
self.horizontalLayout.addItem(spacerItem)
self.label_2 = QLabel(self)
self.label_2.setObjectName("label_2")
self.horizontalLayout.addWidget(self.label_2)
self.output_formats = QComboBox(self)
self.output_formats.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLengthWithIcon)
self.output_formats.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon)
self.output_formats.setMinimumContentsLength(5)
self.output_formats.setObjectName("output_formats")
self.horizontalLayout.addWidget(self.output_formats)
self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 2)
self.groups = QListView(self)
sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
sizePolicy = QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
sizePolicy.setHorizontalStretch(1)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groups.sizePolicy().hasHeightForWidth())
@ -139,12 +139,12 @@ class Config(QDialog):
self.groups.setObjectName("groups")
self.gridLayout.addWidget(self.groups, 1, 0, 3, 1)
self.scrollArea = QScrollArea(self)
sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
sizePolicy = QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
sizePolicy.setHorizontalStretch(4)
sizePolicy.setVerticalStretch(10)
sizePolicy.setHeightForWidth(self.scrollArea.sizePolicy().hasHeightForWidth())
self.scrollArea.setSizePolicy(sizePolicy)
self.scrollArea.setFrameShape(QFrame.NoFrame)
self.scrollArea.setFrameShape(QFrame.Shape.NoFrame)
self.scrollArea.setLineWidth(0)
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName("scrollArea")
@ -152,13 +152,13 @@ class Config(QDialog):
self.page.setObjectName("page")
self.gridLayout.addWidget(self.scrollArea, 1, 1, 1, 1)
self.buttonBox = QDialogButtonBox(self)
self.buttonBox.setOrientation(Qt.Horizontal)
self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok|QDialogButtonBox.RestoreDefaults)
self.buttonBox.setOrientation(Qt.Orientation.Horizontal)
self.buttonBox.setStandardButtons(QDialogButtonBox.StandardButton.Cancel|QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.RestoreDefaults)
self.buttonBox.setObjectName("buttonBox")
self.gridLayout.addWidget(self.buttonBox, 3, 1, 1, 1)
self.help = QTextEdit(self)
self.help.setReadOnly(True)
sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
sizePolicy = QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.help.sizePolicy().hasHeightForWidth())

View File

@ -31,8 +31,8 @@ class PluginWidget(Widget, Ui_Form):
self.md_map = {}
for name, text in iteritems(MD_EXTENSIONS):
i = QListWidgetItem('%s - %s' % (name, text), self.opt_markdown_extensions)
i.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
i.setData(Qt.UserRole, name)
i.setFlags(Qt.ItemFlag.ItemIsUserCheckable | Qt.ItemFlag.ItemIsEnabled)
i.setData(Qt.ItemDataRole.UserRole, name)
self.md_map[name] = i
self.initialize_options(get_option, get_help, db, book_id)
@ -40,17 +40,17 @@ class PluginWidget(Widget, Ui_Form):
def set_value_handler(self, g, val):
if g is self.opt_markdown_extensions:
for i in itervalues(self.md_map):
i.setCheckState(Qt.Unchecked)
i.setCheckState(Qt.CheckState.Unchecked)
for x in val.split(','):
x = x.strip()
if x in self.md_map:
self.md_map[x].setCheckState(Qt.Checked)
self.md_map[x].setCheckState(Qt.CheckState.Checked)
return True
def get_value_handler(self, g):
if g is not self.opt_markdown_extensions:
return Widget.get_value_handler(self, g)
return ', '.join(unicode_type(i.data(Qt.UserRole) or '') for i in itervalues(self.md_map) if i.checkState())
return ', '.join(unicode_type(i.data(Qt.ItemDataRole.UserRole) or '') for i in itervalues(self.md_map) if i.checkState())
def connect_gui_obj_handler(self, g, f):
if g is not self.opt_markdown_extensions:

View File

@ -53,13 +53,13 @@ class Wizard(QDialog):
self.widget = WizardWidget(self)
self.verticalLayout.addWidget(self.widget)
self.buttonBox = QDialogButtonBox(self)
self.buttonBox.setOrientation(Qt.Horizontal)
self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
self.buttonBox.setOrientation(Qt.Orientation.Horizontal)
self.buttonBox.setStandardButtons(QDialogButtonBox.StandardButton.Cancel|QDialogButtonBox.StandardButton.Ok)
self.verticalLayout.addWidget(self.buttonBox)
self.buttonBox.accepted.connect(self.accept)
self.buttonBox.rejected.connect(self.reject)
self.setModal(Qt.WindowModal)
self.setModal(Qt.WindowModality.WindowModal)
@property
def xpath(self):

View File

@ -63,8 +63,8 @@ class DummyImageList(pictureflow.FlowImages):
def __init__(self):
pictureflow.FlowImages.__init__(self)
self.num = 40000
i1, i2 = QImage(300, 400, QImage.Format_RGB32), QImage(300, 400, QImage.Format_RGB32)
i1.fill(Qt.green), i2.fill(Qt.blue)
i1, i2 = QImage(300, 400, QImage.Format.Format_RGB32), QImage(300, 400, QImage.Format.Format_RGB32)
i1.fill(Qt.GlobalColor.green), i2.fill(Qt.GlobalColor.blue)
self.images = [i1, i2]
def count(self):
@ -86,7 +86,7 @@ class DatabaseImages(pictureflow.FlowImages):
pictureflow.FlowImages.__init__(self)
self.model = model
self.is_cover_browser_visible = is_cover_browser_visible
self.model.modelReset.connect(self.reset, type=Qt.QueuedConnection)
self.model.modelReset.connect(self.reset, type=Qt.ConnectionType.QueuedConnection)
self.ignore_image_requests = True
self.template_inited = False
self.subtitle_error_reported = False
@ -179,13 +179,13 @@ class CoverFlow(pictureflow.PictureFlow):
pictureflow.PictureFlow.__init__(self, parent,
config['cover_flow_queue_length']+1)
self.setMinimumSize(QSize(300, 150))
self.setFocusPolicy(Qt.WheelFocus)
self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding,
QSizePolicy.Expanding))
self.setFocusPolicy(Qt.FocusPolicy.WheelFocus)
self.setSizePolicy(QSizePolicy(QSizePolicy.Policy.Expanding,
QSizePolicy.Policy.Expanding))
self.dc_signal.connect(self._data_changed,
type=Qt.QueuedConnection)
type=Qt.ConnectionType.QueuedConnection)
self.context_menu = None
self.setContextMenuPolicy(Qt.DefaultContextMenu)
self.setContextMenuPolicy(Qt.ContextMenuPolicy.DefaultContextMenu)
self.setPreserveAspectRatio(gprefs['cb_preserve_aspect_ratio'])
if not gprefs['cover_browser_reflections']:
self.setShowReflections(False)
@ -243,21 +243,21 @@ class CBDialog(QDialog):
self.resize(w, h)
self.action_fs_toggle = a = QAction(self)
self.addAction(a)
a.setShortcuts([QKeySequence('F11', QKeySequence.PortableText),
QKeySequence('Ctrl+Shift+F', QKeySequence.PortableText)])
a.setShortcuts([QKeySequence('F11', QKeySequence.SequenceFormat.PortableText),
QKeySequence('Ctrl+Shift+F', QKeySequence.SequenceFormat.PortableText)])
a.triggered.connect(self.toggle_fullscreen)
self.action_esc_fs = a = QAction(self)
a.triggered.connect(self.show_normal)
self.addAction(a)
a.setShortcuts([QKeySequence('Esc', QKeySequence.PortableText)])
a.setShortcuts([QKeySequence('Esc', QKeySequence.SequenceFormat.PortableText)])
self.pre_fs_geom = None
cover_flow.setFocus(Qt.OtherFocusReason)
cover_flow.setFocus(Qt.FocusReason.OtherFocusReason)
self.view_action = a = QAction(self)
iactions = parent.iactions
self.addAction(a)
a.setShortcuts(list(iactions['View'].menuless_qaction.shortcuts())+
[QKeySequence(Qt.Key_Space)])
[QKeySequence(Qt.Key.Key_Space)])
a.triggered.connect(iactions['View'].menuless_qaction.trigger)
self.sd_action = a = QAction(self)
self.addAction(a)
@ -321,7 +321,7 @@ class CoverFlowMixin(object):
self.cb_splitter.insertWidget(self.cb_splitter.side_index, self.cover_flow)
if CoverFlow is not None:
self.cover_flow.stop.connect(self.cb_splitter.hide_side_pane)
self.cb_splitter.button.toggled.connect(self.cover_browser_toggled, type=Qt.QueuedConnection)
self.cb_splitter.button.toggled.connect(self.cover_browser_toggled, type=Qt.ConnectionType.QueuedConnection)
def update_cover_flow_subtitle_font(self):
db = self.current_db.new_api
@ -347,7 +347,7 @@ class CoverFlowMixin(object):
self.cover_browser_hidden()
def cover_browser_shown(self):
self.cover_flow.setFocus(Qt.OtherFocusReason)
self.cover_flow.setFocus(Qt.FocusReason.OtherFocusReason)
if CoverFlow is not None:
if self.db_images.ignore_image_requests:
self.db_images.ignore_image_requests = False
@ -373,7 +373,7 @@ class CoverFlowMixin(object):
d = CBDialog(self, self.cover_flow)
d.addAction(self.cb_splitter.action_toggle)
self.cover_flow.setVisible(True)
self.cover_flow.setFocus(Qt.OtherFocusReason)
self.cover_flow.setFocus(Qt.FocusReason.OtherFocusReason)
d.show_fullscreen() if gprefs['cb_fullscreen'] else d.show()
self.cb_splitter.button.set_state_to_hide()
d.closed.connect(self.cover_browser_closed)
@ -456,7 +456,7 @@ def test():
w.setCentralWidget(cf)
w.show()
cf.setFocus(Qt.OtherFocusReason)
cf.setFocus(Qt.FocusReason.OtherFocusReason)
sys.exit(app.exec_())
@ -478,5 +478,5 @@ if __name__ == '__main__':
w.setCentralWidget(cf)
w.show()
cf.setFocus(Qt.OtherFocusReason)
cf.setFocus(Qt.FocusReason.OtherFocusReason)
sys.exit(app.exec_())

View File

@ -25,7 +25,7 @@ class Preview(QLabel):
def __init__(self, parent=None):
QLabel.__init__(self, parent)
self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Minimum)
self.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Minimum)
def sizeHint(self):
return QSize(300, 400)
@ -44,7 +44,7 @@ class ColorButton(QToolButton):
@property
def color(self):
return self._color.name(QColor.HexRgb)[1:]
return self._color.name(QColor.NameFormat.HexRgb)[1:]
@color.setter
def color(self, val):
@ -78,7 +78,7 @@ class CreateColorScheme(QDialog):
l.addRow(_('Color &2:'), self.color2)
l.addRow(_('Contrast color &1 (mainly for text):'), self.contrast_color1)
l.addRow(_('Contrast color &2 (mainly for text):'), self.contrast_color2)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
bb.accepted.connect(self.accept)
bb.rejected.connect(self.reject)
l.addRow(bb)
@ -227,7 +227,7 @@ class CoverSettingsWidget(QWidget):
' in the templates for bold, italic and line breaks, respectively. The'
' default templates use the title, series and authors. You can change them to use'
' whatever metadata you like.'))
la.setWordWrap(True), la.setTextFormat(Qt.PlainText)
la.setWordWrap(True), la.setTextFormat(Qt.TextFormat.PlainText)
l.addWidget(la)
def create_template_widget(title, which, button):
@ -237,16 +237,16 @@ class CoverSettingsWidget(QWidget):
l.addWidget(heading)
la = QLabel()
setattr(self, attr, la)
l.addWidget(la), la.setTextFormat(Qt.PlainText), la.setStyleSheet('QLabel {font-family: monospace}')
l.addWidget(la), la.setTextFormat(Qt.TextFormat.PlainText), la.setStyleSheet('QLabel {font-family: monospace}')
la.setWordWrap(True)
b = QPushButton(button)
b.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
b.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
connect_lambda(b.clicked, self, lambda self: self.change_template(which))
setattr(self, attr + '_button', b)
l.addWidget(b)
if which != 'footer':
f = QFrame(tp)
setattr(tp, attr + '_sep', f), f.setFrameShape(QFrame.HLine)
setattr(tp, attr + '_sep', f), f.setFrameShape(QFrame.Shape.HLine)
l.addWidget(f)
l.addSpacing(10)
@ -297,15 +297,15 @@ class CoverSettingsWidget(QWidget):
self.colors_map = {}
for name in sorted(color_themes, key=sort_key):
self.colors_map[name] = li = QListWidgetItem(name, self.colors_list)
li.setFlags(li.flags() | Qt.ItemIsUserCheckable)
li.setCheckState(Qt.Unchecked if name in disabled else Qt.Checked)
li.setData(Qt.UserRole, color_themes[name])
li.setFlags(li.flags() | Qt.ItemFlag.ItemIsUserCheckable)
li.setCheckState(Qt.CheckState.Unchecked if name in disabled else Qt.CheckState.Checked)
li.setData(Qt.ItemDataRole.UserRole, color_themes[name])
lu = prefs.get('last_used_colors')
if not self.for_global_prefs and lu in self.colors_map and self.colors_map[lu].checkState() == Qt.Checked:
if not self.for_global_prefs and lu in self.colors_map and self.colors_map[lu].checkState() == Qt.CheckState.Checked:
self.colors_map[lu].setSelected(True)
else:
for name, li in iteritems(self.colors_map):
if li.checkState() == Qt.Checked:
if li.checkState() == Qt.CheckState.Checked:
li.setSelected(True)
break
else:
@ -316,14 +316,14 @@ class CoverSettingsWidget(QWidget):
self.style_map.clear()
for name in sorted(all_styles(), key=sort_key):
self.style_map[name] = li = QListWidgetItem(name, self.styles_list)
li.setFlags(li.flags() | Qt.ItemIsUserCheckable)
li.setCheckState(Qt.Unchecked if name in disabled else Qt.Checked)
li.setFlags(li.flags() | Qt.ItemFlag.ItemIsUserCheckable)
li.setCheckState(Qt.CheckState.Unchecked if name in disabled else Qt.CheckState.Checked)
lu = prefs.get('last_used_style')
if not self.for_global_prefs and lu in self.style_map and self.style_map[lu].checkState() == Qt.Checked:
if not self.for_global_prefs and lu in self.style_map and self.style_map[lu].checkState() == Qt.CheckState.Checked:
self.style_map[lu].setSelected(True)
else:
for name, li in iteritems(self.style_map):
if li.checkState() == Qt.Checked:
if li.checkState() == Qt.CheckState.Checked:
li.setSelected(True)
break
else:
@ -338,7 +338,7 @@ class CoverSettingsWidget(QWidget):
@property
def disabled_colors(self):
for name, li in iteritems(self.colors_map):
if li.checkState() == Qt.Unchecked:
if li.checkState() == Qt.CheckState.Unchecked:
yield name
@property
@ -346,7 +346,7 @@ class CoverSettingsWidget(QWidget):
ans = {}
for name, li in iteritems(self.colors_map):
if name.startswith('#'):
ans[name] = li.data(Qt.UserRole)
ans[name] = li.data(Qt.ItemDataRole.UserRole)
return ans
@property
@ -358,7 +358,7 @@ class CoverSettingsWidget(QWidget):
@property
def disabled_styles(self):
for name, li in iteritems(self.style_map):
if li.checkState() == Qt.Unchecked:
if li.checkState() == Qt.CheckState.Unchecked:
yield name
@property
@ -393,12 +393,12 @@ class CoverSettingsWidget(QWidget):
self.colors_list.item(i).setSelected(False)
def create_color_scheme(self):
scheme = self.colors_map[self.current_colors].data(Qt.UserRole)
scheme = self.colors_map[self.current_colors].data(Qt.ItemDataRole.UserRole)
d = CreateColorScheme('#' + _('My Color Scheme'), scheme, set(self.colors_map), parent=self)
if d.exec_() == d.Accepted:
name, scheme = d.data
li = QListWidgetItem(name)
li.setData(Qt.UserRole, scheme), li.setFlags(li.flags() | Qt.ItemIsUserCheckable), li.setCheckState(Qt.Checked)
li.setData(Qt.ItemDataRole.UserRole, scheme), li.setFlags(li.flags() | Qt.ItemFlag.ItemIsUserCheckable), li.setCheckState(Qt.CheckState.Checked)
self.insert_scheme(name, li)
self.emit_changed()
self.original_prefs['color_themes'] = self.current_prefs['color_themes']
@ -410,11 +410,11 @@ class CoverSettingsWidget(QWidget):
'Cannot edit a builtin color scheme. Create a new'
' color scheme instead.'), show=True)
li = self.colors_map[cs]
d = CreateColorScheme(cs, li.data(Qt.UserRole), set(self.colors_map), edit_scheme=True, parent=self)
d = CreateColorScheme(cs, li.data(Qt.ItemDataRole.UserRole), set(self.colors_map), edit_scheme=True, parent=self)
if d.exec_() == d.Accepted:
name, scheme = d.data
li.setText(name)
li.setData(Qt.UserRole, scheme)
li.setData(Qt.ItemDataRole.UserRole, scheme)
if name != cs:
self.colors_map.pop(cs, None)
self.insert_scheme(name, li)
@ -517,7 +517,7 @@ class CoverSettingsDialog(QDialog):
self.save_settings = ss = QCheckBox(_('Save these settings as the &defaults for future use'))
ss.setChecked(gprefs.get('cover_generation_save_settings_for_future', True))
l.addWidget(ss)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
l.addWidget(bb)
bb.accepted.connect(self.accept), bb.rejected.connect(self.reject)
bb.b = b = bb.addButton(_('Restore &defaults'), bb.ActionRole)

View File

@ -152,7 +152,7 @@ class LongText(Base):
self._box.setTitle(label_string(self.col_metadata['name']))
self._layout = QVBoxLayout()
self._tb = QPlainTextEdit(self._box)
self._tb.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)
self._tb.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum)
self._layout.addWidget(self._tb)
self._box.setLayout(self._layout)
self.widgets = [self._box]
@ -387,7 +387,7 @@ class Comments(Base):
self._box.setTitle(label_string(self.col_metadata['name']))
self._layout = QVBoxLayout()
self._tb = CommentsEditor(self._box, toolbar_prefs_name='metadata-comments-editor-widget-hidden-toolbars')
self._tb.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)
self._tb.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum)
# self._tb.setTabChangesFocus(True)
self._layout.addWidget(self._tb)
self._box.setLayout(self._layout)
@ -480,7 +480,7 @@ def _save_dialog(parent, title, msg, det_msg=''):
d = QMessageBox(parent)
d.setWindowTitle(title)
d.setText(msg)
d.setStandardButtons(QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)
d.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No | QMessageBox.StandardButton.Cancel)
return d.exec_()
@ -499,7 +499,7 @@ class Text(Base):
w.set_space_before_sep(True)
w.set_add_separator(tweaks['authors_completer_append_separator'])
w.get_editor_button().clicked.connect(self.edit)
w.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
w.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Preferred)
self.set_to_undefined = w.clear
else:
w = EditWithComplete(parent)
@ -552,9 +552,9 @@ class Text(Base):
_('You have changed the values. In order to use this '
'editor, you must either discard or apply these '
'changes. Apply changes?'))
if d == QMessageBox.Cancel:
if d == QMessageBox.StandardButton.Cancel:
return
if d == QMessageBox.Yes:
if d == QMessageBox.StandardButton.Yes:
self.commit(self.book_id)
self.db.commit()
self.initial_val = self.current_val
@ -791,7 +791,7 @@ def populate_metadata_page(layout, db, book_id, bulk=False, two_column=False, pa
elide_pos = tweaks['metadata_edit_elision_point']
elide_pos = elide_pos if elide_pos in {'left', 'middle', 'right'} else 'right'
# make room on the right side for the scrollbar
sb_width = QApplication.instance().style().pixelMetric(QStyle.PM_ScrollBarExtent)
sb_width = QApplication.instance().style().pixelMetric(QStyle.PixelMetric.PM_ScrollBarExtent)
layout.setContentsMargins(0, 0, sb_width, 0)
for key in cols:
if not fm[key]['is_editable']:
@ -841,9 +841,9 @@ def populate_metadata_page(layout, db, book_id, bulk=False, two_column=False, pa
tweaks['metadata_edit_single_cc_label_length']) - colon_width
wij.setMaximumWidth(label_width)
if c == 0:
wij.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Preferred)
wij.setSizePolicy(QSizePolicy.Policy.Maximum, QSizePolicy.Policy.Preferred)
l.setColumnMinimumWidth(0, label_width)
wij.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
wij.setAlignment(Qt.AlignmentFlag.AlignRight|Qt.AlignmentFlag.AlignVCenter)
t = unicode_type(wij.text())
if t:
if do_elision:
@ -865,8 +865,8 @@ def populate_metadata_page(layout, db, book_id, bulk=False, two_column=False, pa
items = []
if len(ans) > 0:
items.append(QSpacerItem(10, 10, QSizePolicy.Minimum,
QSizePolicy.Expanding))
items.append(QSpacerItem(10, 10, QSizePolicy.Policy.Minimum,
QSizePolicy.Policy.Expanding))
layout.addItem(items[-1], layout.rowCount(), 0, 1, 1)
layout.setRowStretch(layout.rowCount()-1, 100)
return ans, items
@ -1186,7 +1186,7 @@ class BulkSeries(BulkBase):
'force series numbers.') + '</p>')
self.series_increment.setPrefix('+')
layout.addWidget(self.series_increment)
layout.addItem(QSpacerItem(20, 10, QSizePolicy.Expanding, QSizePolicy.Minimum))
layout.addItem(QSpacerItem(20, 10, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum))
self.widgets.append(w)
self.idx_widget.stateChanged.connect(self.a_c_checkbox_changed)
self.force_number.stateChanged.connect(self.a_c_checkbox_changed)
@ -1363,7 +1363,7 @@ class BulkText(BulkBase):
if self.col_metadata['is_multiple']:
is_tags = not self.col_metadata['display'].get('is_names', False)
self.make_widgets(parent, EditWithComplete, add_tags_edit_button=is_tags)
self.main_widget.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
self.main_widget.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Preferred)
self.adding_widget = self.main_widget
if is_tags:
@ -1464,7 +1464,7 @@ class BulkText(BulkBase):
_('You have entered values. In order to use this '
'editor you must first discard them. '
'Discard the values?'))
if d == QMessageBox.Cancel or d == QMessageBox.No:
if d == QMessageBox.StandardButton.Cancel or d == QMessageBox.StandardButton.No:
return
widget.setText('')
d = TagEditor(self.parent, self.db, key=('#'+self.col_metadata['label']))

View File

@ -41,19 +41,19 @@ class MainWindow(QMainWindow):
m.aboutToShow.connect(self.about_to_show_one)
s = self.style()
self.q = q = QAction('&Quit', self)
q.setShortcut(QKeySequence.Quit), q.setIcon(s.standardIcon(s.SP_DialogCancelButton))
q.setShortcut(QKeySequence.StandardKey.Quit), q.setIcon(s.standardIcon(s.SP_DialogCancelButton))
q.triggered.connect(QApplication.quit)
self.addAction(q)
QApplication.instance().setWindowIcon(s.standardIcon(s.SP_ComputerIcon))
for i, icon in zip(range(3), map(s.standardIcon, (s.SP_DialogOkButton, s.SP_DialogHelpButton, s.SP_ArrowUp))):
ac = m.addAction('One - &%d' % (i + 1))
ac.setShortcut(QKeySequence(Qt.CTRL | (Qt.Key_1 + i), Qt.SHIFT | (Qt.Key_1 + i)))
ac.setShortcut(QKeySequence(Qt.Modifier.CTRL | (Qt.Key.Key_1 + i), Qt.Modifier.SHIFT | (Qt.Key.Key_1 + i)))
ac.setIcon(icon)
m.addSeparator()
self.menu_two = m2 = m.addMenu('A &submenu')
for i, icon in zip(range(3), map(s.standardIcon, (s.SP_DialogOkButton, s.SP_DialogCancelButton, s.SP_ArrowUp))):
ac = m2.addAction('Two - &%d' % (i + 1))
ac.setShortcut(QKeySequence(Qt.CTRL | (Qt.Key_A + i)))
ac.setShortcut(QKeySequence(Qt.Modifier.CTRL | (Qt.Key.Key_A + i)))
ac.setIcon(icon)
m2.aboutToShow.connect(self.about_to_show_two)
m2.addSeparator(), m.addSeparator()
@ -162,7 +162,7 @@ class MainWindow(QMainWindow):
app=QApplication([])
app.setAttribute(Qt.AA_DontUseNativeMenuBar, False)
app.setAttribute(Qt.ApplicationAttribute.AA_DontUseNativeMenuBar, False)
app.setApplicationName('com.calibre-ebook.DBusExportDemo')
mw=MainWindow()
mw.show()

View File

@ -83,7 +83,7 @@ class DBusMenu(QObject):
QObject.__init__(self, parent)
# Unity barfs is the Event DBUS method does not return immediately, so
# handle it asynchronously
self.handle_event_signal.connect(self.handle_event, type=Qt.QueuedConnection)
self.handle_event_signal.connect(self.handle_event, type=Qt.ConnectionType.QueuedConnection)
self.dbus_api = DBusMenuAPI(self, object_path, bus=bus)
self.set_status = self.dbus_api.set_status
self._next_id = 0
@ -169,15 +169,15 @@ class DBusMenu(QObject):
ac_id = self.action_to_id(ac)
if ac_id is not None and hasattr(ev, 'action'):
etype = ev.type()
if etype == QEvent.ActionChanged:
if etype == QEvent.Type.ActionChanged:
ac_id = self.action_to_id(ev.action())
self.action_changes.add(ac_id)
self.action_changed_timer.start()
elif etype == QEvent.ActionAdded:
elif etype == QEvent.Type.ActionAdded:
self.layout_changes.add(ac_id)
self.layout_changed_timer.start()
self.add_action(ev.action())
elif etype == QEvent.ActionRemoved:
elif etype == QEvent.Type.ActionRemoved:
self.layout_changes.add(ac_id)
self.layout_changed_timer.start()
self.action_removed(ev.action())

View File

@ -36,7 +36,7 @@ class DBusMenu(QObject):
QObject.__init__(self, parent)
# Unity barfs is the Event DBUS method does not return immediately, so
# handle it asynchronously
self.handle_event_signal.connect(self.handle_event, type=Qt.QueuedConnection)
self.handle_event_signal.connect(self.handle_event, type=Qt.ConnectionType.QueuedConnection)
self.dbus_api = DBusMenuAPI(self, object_path, bus=bus)
self.set_status = self.dbus_api.set_status
self._next_id = 0

View File

@ -43,7 +43,7 @@ class StatusNotifierItem(QObject):
self._icon = QIcon(path)
else:
self._icon = QApplication.instance().windowIcon()
self.show_menu.connect(self._show_menu, type=Qt.QueuedConnection)
self.show_menu.connect(self._show_menu, type=Qt.ConnectionType.QueuedConnection)
_sni_count += 1
kw['num'] = _sni_count
self.dbus_api = StatusNotifierItemAPI(self, **kw)
@ -99,7 +99,7 @@ class StatusNotifierItem(QObject):
return False
def emit_activated(self):
self.activated.emit(QSystemTrayIcon.Trigger)
self.activated.emit(QSystemTrayIcon.ActivationReason.Trigger)
_status_item_menu_count = 0
@ -201,16 +201,16 @@ class StatusNotifierItemAPI(Object):
@dbus_method(IFACE, in_signature='ii', out_signature='')
def Activate(self, x, y):
self.notifier.activated.emit(QSystemTrayIcon.Trigger)
self.notifier.activated.emit(QSystemTrayIcon.ActivationReason.Trigger)
@dbus_method(IFACE, in_signature='u', out_signature='')
def XAyatanaSecondaryActivate(self, timestamp):
# This is called when the user middle clicks the icon in Unity
self.notifier.activated.emit(QSystemTrayIcon.MiddleClick)
self.notifier.activated.emit(QSystemTrayIcon.ActivationReason.MiddleClick)
@dbus_method(IFACE, in_signature='ii', out_signature='')
def SecondaryActivate(self, x, y):
self.notifier.activated.emit(QSystemTrayIcon.MiddleClick)
self.notifier.activated.emit(QSystemTrayIcon.ActivationReason.MiddleClick)
@dbus_method(IFACE, in_signature='is', out_signature='')
def Scroll(self, delta, orientation):

View File

@ -81,7 +81,7 @@ def qicon_to_sni_image_list(qicon):
for size in sizes:
# Convert to DBUS struct of width, height, and image data in ARGB32
# in network endianness
i = qicon.pixmap(size).toImage().convertToFormat(QImage.Format_ARGB32)
i = qicon.pixmap(size).toImage().convertToFormat(QImage.Format.Format_ARGB32)
w, h = i.width(), i.height()
data = i.constBits().asstring(4 * w * h)
if socket.htonl(1) != 1:
@ -106,13 +106,13 @@ def swap_mnemonic_char(text, from_char='&', to_char='_'):
def key_sequence_to_dbus_shortcut(qks):
for key in qks:
if key == -1 or key == Qt.Key_unknown:
if key == -1 or key == Qt.Key.Key_unknown:
continue
items = []
for mod, name in iteritems({Qt.META:'Super', Qt.CTRL:'Control', Qt.ALT:'Alt', Qt.SHIFT:'Shift'}):
for mod, name in iteritems({Qt.Modifier.META:'Super', Qt.Modifier.CTRL:'Control', Qt.Modifier.ALT:'Alt', Qt.Modifier.SHIFT:'Shift'}):
if key & mod == mod:
items.append(name)
key &= int(~(Qt.ShiftModifier | Qt.ControlModifier | Qt.AltModifier | Qt.MetaModifier | Qt.KeypadModifier))
key &= int(~(Qt.KeyboardModifier.ShiftModifier | Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.AltModifier | Qt.KeyboardModifier.MetaModifier | Qt.KeyboardModifier.KeypadModifier))
text = QKeySequence(key).toString()
if text:
text = {'+':'plus', '-':'minus'}.get(text, text)

View File

@ -100,11 +100,11 @@ class ExportedMenuBar(QMenuBar): # {{{
def eventFilter(self, obj, ev):
etype = ev.type()
if etype == QEvent.Show:
if etype == QEvent.Type.Show:
# Hiding a window causes the registrar to auto-unregister it, so we
# have to re-register it on show events.
self.register()
elif etype == QEvent.WinIdChange:
elif etype == QEvent.Type.WinIdChange:
self.unregister()
self.register()
return False
@ -206,7 +206,7 @@ class Factory(QObject):
self.status_notifier = bool(self.bus.call_blocking(*args, timeout=0.1))
def create_window_menubar(self, parent):
if not QApplication.instance().testAttribute(Qt.AA_DontUseNativeMenuBar) and self.has_global_menu:
if not QApplication.instance().testAttribute(Qt.ApplicationAttribute.AA_DontUseNativeMenuBar) and self.has_global_menu:
ans = ExportedMenuBar(parent, self.menu_registrar, self.bus)
self.prune_dead_refs()
self.window_menus.append(weakref.ref(ans))

View File

@ -128,7 +128,7 @@ def device_name_for_plugboards(device_class):
class BusyCursor(object):
def __enter__(self):
QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
QApplication.setOverrideCursor(QCursor(Qt.CursorShape.WaitCursor))
def __exit__(self, *args):
QApplication.restoreOverrideCursor()
@ -893,7 +893,7 @@ class DeviceMixin(object): # {{{
def init_device_mixin(self):
self.device_error_dialog = error_dialog(self, _('Error'),
_('Error communicating with device'), ' ')
self.device_error_dialog.setModal(Qt.NonModal)
self.device_error_dialog.setModal(Qt.WindowModality.NonModal)
self.device_manager = DeviceManager(FunctionDispatcher(self.device_detected),
self.job_manager, Dispatcher(self.status_bar.show_message),
Dispatcher(self.show_open_feedback),
@ -973,7 +973,7 @@ class DeviceMixin(object): # {{{
config_dialog.setWindowIcon(QIcon(I('config.png')))
l = QVBoxLayout(config_dialog)
config_dialog.setLayout(l)
bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel)
bb.accepted.connect(config_dialog.accept)
bb.rejected.connect(config_dialog.reject)
l.addWidget(cw)
@ -1259,7 +1259,7 @@ class DeviceMixin(object): # {{{
elif f in aval_out_formats:
formats.append((f, _('0 of %i books') % len(rows), True))
d = ChooseFormatDeviceDialog(self, _('Choose format to send to device'), formats)
if d.exec_() != QDialog.Accepted:
if d.exec_() != QDialog.DialogCode.Accepted:
return
if d.format():
fmt = d.format().lower()
@ -1891,7 +1891,7 @@ class DeviceMixin(object): # {{{
# loop with preventing App Not Responding errors
if current_book_count % 10 == 0:
QCoreApplication.processEvents(
flags=QEventLoop.ExcludeUserInputEvents|QEventLoop.ExcludeSocketNotifiers)
flags=QEventLoop.ProcessEventsFlag.ExcludeUserInputEvents|QEventLoop.ProcessEventsFlag.ExcludeSocketNotifiers)
current_book_count += 1
book.in_library = None
if getattr(book, 'uuid', None) in self.db_book_uuid_cache:

View File

@ -42,9 +42,9 @@ class ConfigWidget(QWidget, Ui_ConfigWidget):
disabled_formats = all_formats.difference(format_map)
for format in format_map + sorted(disabled_formats):
item = QListWidgetItem(format, self.columns)
item.setData(Qt.UserRole, (format))
item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable|Qt.ItemIsSelectable)
item.setCheckState(Qt.Checked if format in format_map else Qt.Unchecked)
item.setData(Qt.ItemDataRole.UserRole, (format))
item.setFlags(Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsUserCheckable|Qt.ItemFlag.ItemIsSelectable)
item.setCheckState(Qt.CheckState.Checked if format in format_map else Qt.CheckState.Unchecked)
self.column_up.clicked.connect(self.up_column)
self.column_down.clicked.connect(self.down_column)
@ -138,9 +138,9 @@ class ConfigWidget(QWidget, Ui_ConfigWidget):
def format_map(self):
formats = [
unicode_type(self.columns.item(i).data(Qt.UserRole) or '')
unicode_type(self.columns.item(i).data(Qt.ItemDataRole.UserRole) or '')
for i in range(self.columns.count())
if self.columns.item(i).checkState()==Qt.Checked
if self.columns.item(i).checkState()==Qt.CheckState.Checked
]
return formats

View File

@ -34,9 +34,9 @@ class FormatsConfig(QWidget): # {{{
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)
item.setData(Qt.ItemDataRole.UserRole, fmt)
item.setFlags(Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsUserCheckable|Qt.ItemFlag.ItemIsSelectable)
item.setCheckState(Qt.CheckState.Checked if fmt in format_map else Qt.CheckState.Unchecked)
self.button_up = b = QToolButton(self)
b.setIcon(QIcon(I('arrow-up.png')))
@ -50,8 +50,8 @@ class FormatsConfig(QWidget): # {{{
@property
def format_map(self):
return [unicode_type(self.f.item(i).data(Qt.UserRole) or '') for i in
range(self.f.count()) if self.f.item(i).checkState()==Qt.Checked]
return [unicode_type(self.f.item(i).data(Qt.ItemDataRole.UserRole) or '') for i in
range(self.f.count()) if self.f.item(i).checkState()==Qt.CheckState.Checked]
def validate(self):
if not self.format_map:
@ -181,21 +181,21 @@ class IgnoredDevices(QWidget): # {{{
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)
item.setData(Qt.ItemDataRole.UserRole, dev)
item.setFlags(Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsUserCheckable|Qt.ItemFlag.ItemIsSelectable)
item.setCheckState(Qt.CheckState.Checked if dev in blacklist else Qt.CheckState.Unchecked)
@property
def blacklist(self):
return [unicode_type(self.f.item(i).data(Qt.UserRole) or '') for i in
range(self.f.count()) if self.f.item(i).checkState()==Qt.Checked]
return [unicode_type(self.f.item(i).data(Qt.ItemDataRole.UserRole) or '') for i in
range(self.f.count()) if self.f.item(i).checkState()==Qt.CheckState.Checked]
def ignore_device(self, snum):
for i in range(self.f.count()):
i = self.f.item(i)
c = unicode_type(i.data(Qt.UserRole) or '')
c = unicode_type(i.data(Qt.ItemDataRole.UserRole) or '')
if c == snum:
i.setCheckState(Qt.Checked)
i.setCheckState(Qt.CheckState.Checked)
break
# }}}
@ -306,7 +306,7 @@ class FormatRules(QGroupBox):
self.b = b = QPushButton(QIcon(I('plus.png')), _('Add a &new rule'))
l.addWidget(b)
b.clicked.connect(self.add_rule)
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Ignored)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Ignored)
@property
def device(self):
@ -421,7 +421,7 @@ class MTPConfig(QTabWidget):
v.setMinimumWidth(400)
v.setMinimumHeight(350)
l.addWidget(v)
bb = d.bb = QDialogButtonBox(QDialogButtonBox.Close)
bb = d.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close)
bb.accepted.connect(d.accept)
bb.rejected.connect(d.reject)
l.addWidget(bb)
@ -509,7 +509,7 @@ class SendError(QDialog):
la.setWordWrap(True)
la.setMinimumWidth(500)
l.addWidget(la)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.Close)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close)
self.b = bb.addButton(_('Configure'), bb.AcceptRole)
bb.accepted.connect(self.accept)
bb.rejected.connect(self.reject)
@ -543,7 +543,7 @@ if __name__ == '__main__':
d.l = QVBoxLayout()
d.setLayout(d.l)
d.l.addWidget(cw)
bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel)
d.l.addWidget(bb)
bb.accepted.connect(d.accept)
bb.rejected.connect(d.reject)

View File

@ -20,12 +20,12 @@ def browser_item(f, parent):
if not f.is_folder:
name += ' [%s]'%f.last_mod_string
ans = QTreeWidgetItem(parent, [name])
ans.setData(0, Qt.UserRole, f.full_path)
ans.setData(0, Qt.ItemDataRole.UserRole, f.full_path)
if f.is_folder:
ext = 'dir'
else:
ext = f.name.rpartition('.')[-1]
ans.setData(0, Qt.DecorationRole, file_icon_provider().icon_from_ext(ext))
ans.setData(0, Qt.ItemDataRole.DecorationRole, file_icon_provider().icon_from_ext(ext))
return ans
@ -55,7 +55,7 @@ class Storage(QTreeWidget):
def current_item(self):
item = self.currentItem()
if item is not None:
return (self.object_id, item.data(0, Qt.UserRole))
return (self.object_id, item.data(0, Qt.ItemDataRole.UserRole))
return None
@ -88,7 +88,7 @@ class Browser(QDialog):
self.setLayout(l)
self.folders = cw = Folders(filesystem_cache, show_files=show_files)
l.addWidget(cw)
bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel)
l.addWidget(bb)
bb.accepted.connect(self.accept)
bb.rejected.connect(self.reject)
@ -131,8 +131,8 @@ class IgnoredFolders(QDialog):
l.addWidget(la)
la.setWordWrap(True)
self.bb = QDialogButtonBox(QDialogButtonBox.Ok |
QDialogButtonBox.Cancel)
self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok |
QDialogButtonBox.StandardButton.Cancel)
self.bb.accepted.connect(self.accept)
self.bb.rejected.connect(self.reject)
self.sab = self.bb.addButton(_('Select &all'), self.bb.ActionRole)
@ -150,11 +150,11 @@ class IgnoredFolders(QDialog):
root = w.invisibleRootItem()
w.itemChanged.disconnect(self.item_changed)
try:
if item.checkState(0) == Qt.Checked:
if item.checkState(0) == Qt.CheckState.Checked:
# Ensure that the parents of this item are checked
p = item.parent()
while p is not None and p is not root:
p.setCheckState(0, Qt.Checked)
p.setCheckState(0, Qt.CheckState.Checked)
p = p.parent()
# Set the state of all descendants to the same state as this item
for child in self.iterchildren(item):
@ -173,24 +173,24 @@ class IgnoredFolders(QDialog):
def create_item(self, f, parent):
name = f.name
ans = QTreeWidgetItem(parent, [name])
ans.setData(0, Qt.UserRole, '/'.join(f.full_path[1:]))
ans.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
ans.setData(0, Qt.ItemDataRole.UserRole, '/'.join(f.full_path[1:]))
ans.setFlags(Qt.ItemFlag.ItemIsUserCheckable | Qt.ItemFlag.ItemIsEnabled)
ans.setCheckState(0,
Qt.Unchecked if self.dev.is_folder_ignored(f.storage_id, f.full_path[1:]) else Qt.Checked)
ans.setData(0, Qt.DecorationRole, file_icon_provider().icon_from_ext('dir'))
Qt.CheckState.Unchecked if self.dev.is_folder_ignored(f.storage_id, f.full_path[1:]) else Qt.CheckState.Checked)
ans.setData(0, Qt.ItemDataRole.DecorationRole, file_icon_provider().icon_from_ext('dir'))
return ans
def select_all(self):
w = self.tabs.currentWidget()
for i in range(w.invisibleRootItem().childCount()):
c = w.invisibleRootItem().child(i)
c.setCheckState(0, Qt.Checked)
c.setCheckState(0, Qt.CheckState.Checked)
def select_none(self):
w = self.tabs.currentWidget()
for i in range(w.invisibleRootItem().childCount()):
c = w.invisibleRootItem().child(i)
c.setCheckState(0, Qt.Unchecked)
c.setCheckState(0, Qt.CheckState.Unchecked)
@property
def ignored_folders(self):
@ -198,9 +198,9 @@ class IgnoredFolders(QDialog):
for w in self.widgets:
folders = set()
for node in self.iterchildren(w.invisibleRootItem()):
if node.checkState(0) == Qt.Checked:
if node.checkState(0) == Qt.CheckState.Checked:
continue
path = unicode_type(node.data(0, Qt.UserRole) or '')
path = unicode_type(node.data(0, Qt.ItemDataRole.UserRole) or '')
parent = path.rpartition('/')[0]
if '/' not in path or icu_lower(parent) not in folders:
folders.add(icu_lower(path))

View File

@ -311,7 +311,7 @@ class ExtraCustomization(DeviceConfigTab): # {{{
self.extra_layout.addWidget(l, row_func(i + 2, 0), col_func(i))
self.extra_layout.addWidget(self.opt_extra_customization[i],
row_func(i + 2, 1), col_func(i))
spacerItem1 = QSpacerItem(10, 10, QSizePolicy.Minimum, QSizePolicy.Expanding)
spacerItem1 = QSpacerItem(10, 10, QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Expanding)
self.extra_layout.addItem(spacerItem1, row_func(i + 2 + 2, 1), 0, 1, 2)
self.extra_layout.setRowStretch(row_func(i + 2 + 2, 1), 2)
else:
@ -386,7 +386,7 @@ if __name__ == '__main__':
d.l = QVBoxLayout()
d.setLayout(d.l)
d.l.addWidget(cw)
bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel)
d.l.addWidget(bb)
bb.accepted.connect(d.accept)
bb.rejected.connect(d.reject)

View File

@ -105,7 +105,7 @@ class AddEmptyBookDialog(QDialog):
cf.setChecked(gprefs.get('create_empty_copy_dup_formats', False))
self._layout.addWidget(cf, 10, 0, 1, -1)
button_box = self.bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
button_box = self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
button_box.accepted.connect(self.accept)
button_box.rejected.connect(self.reject)
self._layout.addWidget(button_box, 11, 0, 1, -1)

View File

@ -40,13 +40,13 @@ class AddFromISBN(QDialog):
self.l = l = QVBoxLayout(self)
self.h = h = QHBoxLayout()
l.addLayout(h)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel, self)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel, self)
bb.button(bb.Ok).setText(_('&OK'))
l.addWidget(bb), bb.accepted.connect(self.accept), bb.rejected.connect(self.reject)
self.ll = l = QVBoxLayout()
h.addLayout(l)
self.isbn_box = i = QPlainTextEdit(self)
i.setFocus(Qt.OtherFocusReason)
i.setFocus(Qt.FocusReason.OtherFocusReason)
l.addWidget(i)
self.paste_button = b = QPushButton(_("&Paste from clipboard"), self)
l.addWidget(b), b.clicked.connect(self.paste)

View File

@ -30,7 +30,7 @@ class ItemDelegate(QStyledItemDelegate):
return QStyledItemDelegate.sizeHint(self, *args) + QSize(0, 15)
def setEditorData(self, editor, index):
name = unicode_type(index.data(Qt.DisplayRole) or '')
name = unicode_type(index.data(Qt.ItemDataRole.DisplayRole) or '')
editor.setText(name)
editor.lineEdit().selectAll()
@ -41,7 +41,7 @@ class ItemDelegate(QStyledItemDelegate):
def createEditor(self, parent, option, index):
self.ed = EditWithComplete(parent)
self.ed.setFocusPolicy(Qt.StrongFocus)
self.ed.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
init_line_edit(self.ed, self.all_authors)
return self.ed
@ -56,7 +56,7 @@ class List(QListWidget):
self.setDragDropMode(self.InternalMove)
self.setAlternatingRowColors(True)
self.d = ItemDelegate(all_authors, self)
self.d.edited.connect(self.edited, type=Qt.QueuedConnection)
self.d.edited.connect(self.edited, type=Qt.ConnectionType.QueuedConnection)
self.setItemDelegate(self.d)
def delete_selected(self):
@ -64,7 +64,7 @@ class List(QListWidget):
self.takeItem(self.row(item))
def keyPressEvent(self, ev):
if ev.key() == Qt.Key_Delete:
if ev.key() == Qt.Key.Key_Delete:
self.delete_selected()
ev.accept()
return
@ -85,7 +85,7 @@ class List(QListWidget):
def mark_as_editable(self):
for i in range(self.count()):
item = self.item(i)
item.setFlags(item.flags() | Qt.ItemIsEditable)
item.setFlags(item.flags() | Qt.ItemFlag.ItemIsEditable)
def edited(self, i):
item = self.item(i)
@ -103,7 +103,7 @@ class Edit(EditWithComplete):
returnPressed = pyqtSignal()
def keyPressEvent(self, ev):
if ev.key() in (Qt.Key_Return, Qt.Key_Enter):
if ev.key() in (Qt.Key.Key_Return, Qt.Key.Key_Enter):
ev.accept()
self.returnPressed.emit()
return
@ -150,7 +150,7 @@ class AuthorsEdit(QDialog):
b.setIcon(QIcon(I('minus.png')))
b.clicked.connect(self.al.delete_selected)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
bb.accepted.connect(self.accept)
bb.rejected.connect(self.reject)
l.addWidget(bb, 3, 0, 1, 3)
@ -160,7 +160,7 @@ class AuthorsEdit(QDialog):
geom = gprefs.get('authors-edit-geometry', None)
if geom is not None:
QApplication.instance().safe_restore_geometry(self, geom)
self.author.setFocus(Qt.OtherFocusReason)
self.author.setFocus(Qt.FocusReason.OtherFocusReason)
def save_geometry(self):
gprefs.set('authors-edit-geometry', bytearray(self.saveGeometry()))

View File

@ -125,8 +125,8 @@ class BookInfo(QDialog):
def __init__(self, parent, view, row, link_delegate):
QDialog.__init__(self, parent)
self.normal_brush = QBrush(Qt.white)
self.marked_brush = QBrush(Qt.lightGray)
self.normal_brush = QBrush(Qt.GlobalColor.white)
self.marked_brush = QBrush(Qt.GlobalColor.lightGray)
self.marked = None
self.gui = parent
self.splitter = QSplitter(self)
@ -146,10 +146,10 @@ class BookInfo(QDialog):
self.details = Details(parent.book_details.book_info, self)
self.details.anchor_clicked.connect(self.on_link_clicked)
self.link_delegate = link_delegate
self.details.setAttribute(Qt.WA_OpaquePaintEvent, False)
self.details.setAttribute(Qt.WidgetAttribute.WA_OpaquePaintEvent, False)
palette = self.details.palette()
self.details.setAcceptDrops(False)
palette.setBrush(QPalette.Base, Qt.transparent)
palette.setBrush(QPalette.ColorRole.Base, Qt.GlobalColor.transparent)
self.details.setPalette(palette)
self.c = QWidget(self)
@ -187,9 +187,9 @@ class BookInfo(QDialog):
self.ps = QShortcut(QKeySequence('Alt+Left'), self)
self.ps.activated.connect(self.previous)
self.next_button.setToolTip(_('Next [%s]')%
unicode_type(self.ns.key().toString(QKeySequence.NativeText)))
unicode_type(self.ns.key().toString(QKeySequence.SequenceFormat.NativeText)))
self.previous_button.setToolTip(_('Previous [%s]')%
unicode_type(self.ps.key().toString(QKeySequence.NativeText)))
unicode_type(self.ps.key().toString(QKeySequence.SequenceFormat.NativeText)))
geom = QCoreApplication.instance().desktop().availableGeometry(self)
screen_height = geom.height() - 100
@ -287,7 +287,7 @@ class BookInfo(QDialog):
except AttributeError:
dpr = self.devicePixelRatio()
pixmap = pixmap.scaled(int(dpr * new_width), int(dpr * new_height),
Qt.KeepAspectRatio, Qt.SmoothTransformation)
Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)
pixmap.setDevicePixelRatio(dpr)
self.cover.set_pixmap(pixmap)
self.update_cover_tooltip()

View File

@ -34,7 +34,7 @@ class DBCheck(QDialog): # {{{
self.l1.setWordWrap(True)
self.l.addWidget(self.l1)
self.msg = QLabel('')
self.update_msg.connect(self.msg.setText, type=Qt.QueuedConnection)
self.update_msg.connect(self.msg.setText, type=Qt.ConnectionType.QueuedConnection)
self.l.addWidget(self.msg)
self.msg.setWordWrap(True)
self.resize(self.sizeHint() + QSize(100, 50))
@ -264,33 +264,33 @@ class CheckLibraryDialog(QDialog):
tl = Item()
tl.setText(0, h)
if fixable and list:
tl.setData(1, Qt.UserRole, self.is_fixable)
tl.setData(1, Qt.ItemDataRole.UserRole, self.is_fixable)
tl.setText(1, _('(fixable)'))
tl.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
tl.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsUserCheckable)
tl.setCheckState(1, False)
else:
tl.setData(1, Qt.UserRole, self.is_deletable)
tl.setData(2, Qt.UserRole, self.is_deletable)
tl.setData(1, Qt.ItemDataRole.UserRole, self.is_deletable)
tl.setData(2, Qt.ItemDataRole.UserRole, self.is_deletable)
tl.setText(1, _('(deletable)'))
tl.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
tl.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsUserCheckable)
tl.setCheckState(1, False)
if attr == 'extra_covers':
tl.setData(2, Qt.UserRole, self.is_deletable)
tl.setData(2, Qt.ItemDataRole.UserRole, self.is_deletable)
tl.setText(2, _('(deletable)'))
tl.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
tl.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsUserCheckable)
tl.setCheckState(2, False)
self.top_level_items[attr] = tl
for problem in list_:
it = Item()
if checkable:
it.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
it.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsUserCheckable)
it.setCheckState(2, False)
it.setData(2, Qt.UserRole, self.is_deletable)
it.setData(2, Qt.ItemDataRole.UserRole, self.is_deletable)
else:
it.setFlags(Qt.ItemIsEnabled)
it.setFlags(Qt.ItemFlag.ItemIsEnabled)
it.setText(0, problem[0])
it.setData(0, Qt.UserRole, problem[2])
it.setData(0, Qt.ItemDataRole.UserRole, problem[2])
it.setText(2, problem[1])
tl.addChild(it)
self.all_items.append(it)
@ -331,8 +331,8 @@ class CheckLibraryDialog(QDialog):
all_checked = True
for i in range(0, node.childCount()):
c = node.child(i).checkState(2)
checked = checked or c == Qt.Checked
all_checked = all_checked and c == Qt.Checked
checked = checked or c == Qt.CheckState.Checked
all_checked = all_checked and c == Qt.CheckState.Checked
return (checked, all_checked)
def any_child_delete_checked():
@ -344,15 +344,15 @@ class CheckLibraryDialog(QDialog):
def any_fix_checked():
for parent in self.top_level_items.values():
if (parent.data(1, Qt.UserRole) == self.is_fixable and
parent.checkState(1) == Qt.Checked):
if (parent.data(1, Qt.ItemDataRole.UserRole) == self.is_fixable and
parent.checkState(1) == Qt.CheckState.Checked):
return True
return False
if item in self.top_level_items.values():
if item.childCount() > 0:
if item.data(1, Qt.UserRole) == self.is_fixable and column == 1:
if item.data(2, Qt.UserRole) == self.is_deletable:
if item.data(1, Qt.ItemDataRole.UserRole) == self.is_fixable and column == 1:
if item.data(2, Qt.ItemDataRole.UserRole) == self.is_deletable:
set_delete_boxes(item, 2, False)
else:
set_delete_boxes(item, column, item.checkState(column))
@ -361,40 +361,40 @@ class CheckLibraryDialog(QDialog):
item.setCheckState(1, False)
self.log.blockSignals(False)
else:
item.setCheckState(column, Qt.Unchecked)
item.setCheckState(column, Qt.CheckState.Unchecked)
else:
for parent in self.top_level_items.values():
if parent.data(2, Qt.UserRole) == self.is_deletable:
if parent.data(2, Qt.ItemDataRole.UserRole) == self.is_deletable:
(child_chkd, all_chkd) = is_child_delete_checked(parent)
if all_chkd and child_chkd:
check_state = Qt.Checked
check_state = Qt.CheckState.Checked
elif child_chkd:
check_state = Qt.PartiallyChecked
check_state = Qt.CheckState.PartiallyChecked
else:
check_state = Qt.Unchecked
check_state = Qt.CheckState.Unchecked
self.log.blockSignals(True)
if parent.data(1, Qt.UserRole) == self.is_fixable:
if parent.data(1, Qt.ItemDataRole.UserRole) == self.is_fixable:
parent.setCheckState(2, check_state)
else:
parent.setCheckState(1, check_state)
if child_chkd and parent.data(1, Qt.UserRole) == self.is_fixable:
parent.setCheckState(1, Qt.Unchecked)
if child_chkd and parent.data(1, Qt.ItemDataRole.UserRole) == self.is_fixable:
parent.setCheckState(1, Qt.CheckState.Unchecked)
self.log.blockSignals(False)
self.delete_button.setEnabled(any_child_delete_checked())
self.fix_button.setEnabled(any_fix_checked())
def mark_for_fix(self):
for it in self.top_level_items.values():
if (it.flags() & Qt.ItemIsUserCheckable and
it.data(1, Qt.UserRole) == self.is_fixable and
if (it.flags() & Qt.ItemFlag.ItemIsUserCheckable and
it.data(1, Qt.ItemDataRole.UserRole) == self.is_fixable and
it.childCount() > 0):
it.setCheckState(1, Qt.Checked)
it.setCheckState(1, Qt.CheckState.Checked)
def mark_for_delete(self):
for it in self.all_items:
if (it.flags() & Qt.ItemIsUserCheckable and
it.data(2, Qt.UserRole) == self.is_deletable):
it.setCheckState(2, Qt.Checked)
if (it.flags() & Qt.ItemFlag.ItemIsUserCheckable and
it.data(2, Qt.ItemDataRole.UserRole) == self.is_deletable):
it.setCheckState(2, Qt.CheckState.Checked)
def delete_marked(self):
if not confirm('<p>'+_('The marked files and folders will be '
@ -407,7 +407,7 @@ class CheckLibraryDialog(QDialog):
key=lambda x: len(x.text(1)),
reverse=True)
for it in items:
if it.checkState(2) == Qt.Checked:
if it.checkState(2) == Qt.CheckState.Checked:
try:
p = os.path.join(self.db.library_path, unicode_type(it.text(2)))
if os.path.isdir(p):
@ -425,7 +425,7 @@ class CheckLibraryDialog(QDialog):
child_count = tl.childCount()
for i in range(0, child_count):
item = tl.child(i)
id = int(item.data(0, Qt.UserRole))
id = int(item.data(0, Qt.ItemDataRole.UserRole))
all = self.db.formats(id, index_is_id=True, verify_formats=False)
all = {f.strip() for f in all.split(',')} if all else set()
valid = self.db.formats(id, index_is_id=True, verify_formats=True)
@ -438,7 +438,7 @@ class CheckLibraryDialog(QDialog):
child_count = tl.childCount()
for i in range(0, child_count):
item = tl.child(i)
id = int(item.data(0, Qt.UserRole))
id = int(item.data(0, Qt.ItemDataRole.UserRole))
self.db.set_has_cover(id, False)
def fix_extra_covers(self):
@ -446,7 +446,7 @@ class CheckLibraryDialog(QDialog):
child_count = tl.childCount()
for i in range(0, child_count):
item = tl.child(i)
id = int(item.data(0, Qt.UserRole))
id = int(item.data(0, Qt.ItemDataRole.UserRole))
self.db.set_has_cover(id, True)
def fix_items(self):

View File

@ -37,7 +37,7 @@ class ChooseFormatDialog(QDialog):
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.setStandardButtons(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel)
bb.accepted.connect(self.accept), bb.rejected.connect(self.reject)
h.addStretch(10), h.addWidget(self.buttonBox)

View File

@ -27,8 +27,8 @@ class ProgressDialog(PD):
def __init__(self, *args, **kwargs):
PD.__init__(self, *args, **kwargs)
self.on_progress_update.connect(self.progressed, type=Qt.QueuedConnection)
self.finished_moving.connect(self.accept, type=Qt.QueuedConnection)
self.on_progress_update.connect(self.progressed, type=Qt.ConnectionType.QueuedConnection)
self.finished_moving.connect(self.accept, type=Qt.ConnectionType.QueuedConnection)
def reject(self):
return

View File

@ -29,8 +29,8 @@ class ChoosePluginToolbarsDialog(QDialog):
self._layout.addWidget(self._header_label)
self._locations_list = QListWidget(self)
self._locations_list.setSelectionMode(QAbstractItemView.MultiSelection)
sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum)
self._locations_list.setSelectionMode(QAbstractItemView.SelectionMode.MultiSelection)
sizePolicy = QSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
self._locations_list.setSizePolicy(sizePolicy)
@ -46,8 +46,8 @@ class ChoosePluginToolbarsDialog(QDialog):
'using <b>Preferences -> Interface -> Toolbars</b>'))
self._layout.addWidget(self._footer_label)
button_box = QDialogButtonBox(QDialogButtonBox.Ok |
QDialogButtonBox.Cancel)
button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok |
QDialogButtonBox.StandardButton.Cancel)
button_box.accepted.connect(self.accept)
button_box.rejected.connect(self.reject)
self._layout.addWidget(button_box)

View File

@ -21,14 +21,14 @@ class CommentsDialog(QDialog, Ui_CommentsDialog):
self.setupUi(self)
# Remove help icon on title bar
icon = self.windowIcon()
self.setWindowFlags(self.windowFlags()&(~Qt.WindowContextHelpButtonHint))
self.setWindowFlags(self.windowFlags()&(~Qt.WindowType.WindowContextHelpButtonHint))
self.setWindowIcon(icon)
self.textbox.html = comments_to_html(text) if text else ''
self.textbox.wyswyg_dirtied()
# self.textbox.setTabChangesFocus(True)
self.buttonBox.button(QDialogButtonBox.Ok).setText(_('O&K'))
self.buttonBox.button(QDialogButtonBox.Cancel).setText(_('&Cancel'))
self.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setText(_('O&K'))
self.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setText(_('&Cancel'))
if column_name:
self.setWindowTitle(_('Edit "{0}"').format(column_name))

View File

@ -41,14 +41,14 @@ class Dialog(QDialog):
l.addWidget(a)
if show_cancel_button:
buttons = QDialogButtonBox.Yes | QDialogButtonBox.No
standard_button = QDialogButtonBox.Yes
buttons = QDialogButtonBox.StandardButton.Yes | QDialogButtonBox.StandardButton.No
standard_button = QDialogButtonBox.StandardButton.Yes
else:
buttons = QDialogButtonBox.Ok
standard_button = QDialogButtonBox.Ok
buttons = QDialogButtonBox.StandardButton.Ok
standard_button = QDialogButtonBox.StandardButton.Ok
self.buttonBox = bb = QDialogButtonBox(buttons, self)
bb.setObjectName("buttonBox")
bb.setFocus(Qt.OtherFocusReason)
bb.setFocus(Qt.FocusReason.OtherFocusReason)
bb.accepted.connect(self.accept), bb.rejected.connect(self.reject)
l.addWidget(bb)
@ -56,7 +56,7 @@ class Dialog(QDialog):
self.config_set = config_set
self.resize(self.sizeHint())
bb.button(standard_button).setFocus(Qt.OtherFocusReason)
bb.button(standard_button).setFocus(Qt.FocusReason.OtherFocusReason)
def toggle(self, *args):
self.config_set[confirm_config_name(self.name)] = self.again.isChecked()

View File

@ -19,7 +19,7 @@ class Dialog(QDialog, Ui_Dialog):
self.loc = None
self.msg.setText(msg)
self.name = name
self.buttonBox.setFocus(Qt.OtherFocusReason)
self.buttonBox.setFocus(Qt.FocusReason.OtherFocusReason)
connect_lambda(self.button_lib.clicked, self, lambda self: self.set_loc('lib'))
connect_lambda(self.button_device.clicked, self, lambda self: self.set_loc('dev'))
connect_lambda(self.button_both.clicked, self, lambda self: self.set_loc('both'))

View File

@ -114,7 +114,7 @@ class ChooseMerge(Dialog):
l.addWidget(ans)
prefs_key = ans.prefs_key = 'choose-merge-cb-' + name
ans.setChecked(gprefs.get(prefs_key, True))
connect_lambda(ans.stateChanged, self, lambda self, state: self.state_changed(getattr(self, name), state), type=Qt.QueuedConnection)
connect_lambda(ans.stateChanged, self, lambda self, state: self.state_changed(getattr(self, name), state), type=Qt.ConnectionType.QueuedConnection)
if tt:
ans.setToolTip(tt)
setattr(self, name, ans)

View File

@ -64,7 +64,7 @@ class CustomRecipeModel(QAbstractListModel): # {{{
return 0
def data(self, index, role):
if role == Qt.DisplayRole:
if role == Qt.ItemDataRole.DisplayRole:
return self.title(index)
def update(self, row, title, script):
@ -175,7 +175,7 @@ class RecipeList(QWidget): # {{{
l.addWidget(v)
self.stacks = s = QStackedWidget(self)
l.addWidget(s, stretch=10, alignment=Qt.AlignTop)
l.addWidget(s, stretch=10, alignment=Qt.AlignmentFlag.AlignTop)
self.first_msg = la = QLabel(_(
'Create a new news source by clicking one of the buttons below'))
@ -188,25 +188,25 @@ class RecipeList(QWidget): # {{{
s.addWidget(w)
self.title = la = QLabel(w)
la.setAlignment(Qt.AlignHCenter | Qt.AlignTop)
la.setAlignment(Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop)
l.addWidget(la)
l.setSpacing(20)
self.edit_button = b = QPushButton(QIcon(I('modified.png')), _('&Edit this recipe'), w)
b.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))
b.setSizePolicy(QSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed))
b.clicked.connect(self.edit_requested)
l.addWidget(b)
self.remove_button = b = QPushButton(QIcon(I('list_remove.png')), _('&Remove this recipe'), w)
b.clicked.connect(self.remove)
b.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))
b.setSizePolicy(QSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed))
l.addWidget(b)
self.export_button = b = QPushButton(QIcon(I('save.png')), _('S&ave recipe as file'), w)
b.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))
b.setSizePolicy(QSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed))
b.clicked.connect(self.save_recipe)
l.addWidget(b)
self.download_button = b = QPushButton(QIcon(I('download-metadata.png')), _('&Download this recipe'), w)
b.clicked.connect(self.download)
b.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))
b.setSizePolicy(QSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed))
l.addWidget(b)
self.select_row()
@ -394,7 +394,7 @@ class BasicRecipe(QWidget): # {{{
if not title:
return error_dialog(self, _('No feed URL'), _(
'You must specify a URL for the feed'), show=True)
QListWidgetItem('%s - %s' % (title, url), self.feeds).setData(Qt.UserRole, (title, url))
QListWidgetItem('%s - %s' % (title, url), self.feeds).setData(Qt.ItemDataRole.UserRole, (title, url))
self.feed_title.clear(), self.feed_url.clear()
def validate(self):
@ -419,7 +419,7 @@ class BasicRecipe(QWidget): # {{{
def recipe_source(self):
title = self.title.text().strip()
feeds = [self.feeds.item(i).data(Qt.UserRole) for i in range(self.feeds.count())]
feeds = [self.feeds.item(i).data(Qt.ItemDataRole.UserRole) for i in range(self.feeds.count())]
return options_to_recipe_source(title, self.oldest_article.value(), self.max_articles.value(), feeds)
@recipe_source.setter
@ -438,7 +438,7 @@ class BasicRecipe(QWidget): # {{{
self.max_articles.setValue(recipe.max_articles_per_feed)
for x in (recipe.feeds or ()):
title, url = ('', x) if len(x) == 1 else x
QListWidgetItem('%s - %s' % (title, url), self.feeds).setData(Qt.UserRole, (title, url))
QListWidgetItem('%s - %s' % (title, url), self.feeds).setData(Qt.ItemDataRole.UserRole, (title, url))
# }}}
@ -484,7 +484,7 @@ class ChooseBuiltinRecipeModel(QSortFilterProxyModel):
def filterAcceptsRow(self, source_row, source_parent):
idx = self.sourceModel().index(source_row, 0, source_parent)
urn = idx.data(Qt.UserRole)
urn = idx.data(Qt.ItemDataRole.UserRole)
if not urn or urn in ('::category::0', '::category::1'):
return False
return True
@ -509,7 +509,7 @@ class ChooseBuiltinRecipe(Dialog): # {{{
self.search.initialize('scheduler_search_history')
self.search.setMinimumContentsLength(15)
self.search.search.connect(self.recipe_model.search)
self.recipe_model.searched.connect(self.search.search_done, type=Qt.QueuedConnection)
self.recipe_model.searched.connect(self.search.search_done, type=Qt.ConnectionType.QueuedConnection)
self.recipe_model.searched.connect(self.search_done)
self.go_button = b = QToolButton(self)
b.setText(_("Go"))
@ -519,7 +519,7 @@ class ChooseBuiltinRecipe(Dialog): # {{{
l.addLayout(h)
l.addWidget(self.recipes)
l.addWidget(self.bb)
self.search.setFocus(Qt.OtherFocusReason)
self.search.setFocus(Qt.FocusReason.OtherFocusReason)
def search_done(self, *args):
if self.recipe_model.showing_count < 10:
@ -531,7 +531,7 @@ class ChooseBuiltinRecipe(Dialog): # {{{
@property
def selected_recipe(self):
for idx in self.recipes.selectedIndexes():
urn = idx.data(Qt.UserRole)
urn = idx.data(Qt.ItemDataRole.UserRole)
if urn and not urn.startswith('::category::'):
return urn

View File

@ -20,7 +20,7 @@ class tableItem(QTableWidgetItem):
def __init__(self, text):
QTableWidgetItem.__init__(self, text)
self.setFlags(Qt.ItemIsEnabled)
self.setFlags(Qt.ItemFlag.ItemIsEnabled)
self.sort = text.lower()
def __ge__(self, other):
@ -34,7 +34,7 @@ class centeredTableItem(tableItem):
def __init__(self, text):
tableItem.__init__(self, text)
self.setTextAlignment(Qt.AlignCenter)
self.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
class titleTableItem(tableItem):
@ -78,7 +78,7 @@ class DeleteMatchingFromDeviceDialog(QDialog, Ui_DeleteMatchingFromDeviceDialog)
self.buttonBox.accepted.connect(self.accepted)
self.buttonBox.rejected.connect(self.rejected)
self.table.cellClicked.connect(self.cell_clicked)
self.table.setSelectionMode(QAbstractItemView.NoSelection)
self.table.setSelectionMode(QAbstractItemView.SelectionMode.NoSelection)
self.table.setColumnCount(7)
self.table.setHorizontalHeaderLabels(
['', _('Location'), _('Title'), _('Author'),
@ -92,9 +92,9 @@ class DeleteMatchingFromDeviceDialog(QDialog, Ui_DeleteMatchingFromDeviceDialog)
(model,books) = items[card]
for (id,book) in books:
item = QTableWidgetItem()
item.setFlags(Qt.ItemIsUserCheckable|Qt.ItemIsEnabled)
item.setCheckState(Qt.Checked)
item.setData(Qt.UserRole, (model, id, book.path))
item.setFlags(Qt.ItemFlag.ItemIsUserCheckable|Qt.ItemFlag.ItemIsEnabled)
item.setCheckState(Qt.CheckState.Checked)
item.setData(Qt.ItemDataRole.UserRole, (model, id, book.path))
self.table.setItem(row, 0, item)
self.table.setItem(row, 1, tableItem(card))
self.table.setItem(row, 2, titleTableItem(book.title))
@ -106,7 +106,7 @@ class DeleteMatchingFromDeviceDialog(QDialog, Ui_DeleteMatchingFromDeviceDialog)
self.table.setCurrentCell(0, 1)
self.table.resizeColumnsToContents()
self.table.setSortingEnabled(True)
self.table.sortByColumn(2, Qt.AscendingOrder)
self.table.sortByColumn(2, Qt.SortOrder.AscendingOrder)
self.table.setCurrentCell(0, 1)
def cell_clicked(self, row, col):
@ -116,9 +116,9 @@ class DeleteMatchingFromDeviceDialog(QDialog, Ui_DeleteMatchingFromDeviceDialog)
def accepted(self):
self.result = []
for row in range(self.table.rowCount()):
if self.table.item(row, 0).checkState() == Qt.Unchecked:
if self.table.item(row, 0).checkState() == Qt.CheckState.Unchecked:
continue
(model, id, path) = self.table.item(row, 0).data(Qt.UserRole)
(model, id, path) = self.table.item(row, 0).data(Qt.ItemDataRole.UserRole)
path = unicode_type(path)
self.result.append((model, id, path))
return

View File

@ -19,19 +19,19 @@ class ListWidgetItem(QListWidgetItem):
self.previous_value = txt
def data(self, role):
if role == Qt.DisplayRole:
if role == Qt.ItemDataRole.DisplayRole:
if self.initial_value != self.current_value:
return _('%(curr)s (was %(initial)s)')%dict(
curr=self.current_value, initial=self.initial_value)
else:
return self.current_value
elif role == Qt.EditRole:
elif role == Qt.ItemDataRole.EditRole:
return self.current_value
else:
return QListWidgetItem.data(self, role)
def setData(self, role, data):
if role == Qt.EditRole:
if role == Qt.ItemDataRole.EditRole:
self.previous_value = self.current_value
self.current_value = data
QListWidgetItem.setData(self, role, data)
@ -58,7 +58,7 @@ class DeviceCategoryEditor(QDialog, Ui_DeviceCategoryEditor):
self.setupUi(self)
# Remove help icon on title bar
icon = self.windowIcon()
self.setWindowFlags(self.windowFlags()&(~Qt.WindowContextHelpButtonHint))
self.setWindowFlags(self.windowFlags()&(~Qt.WindowType.WindowContextHelpButtonHint))
self.setWindowIcon(icon)
self.to_rename = {}
@ -71,12 +71,12 @@ class DeviceCategoryEditor(QDialog, Ui_DeviceCategoryEditor):
self.original_names[k] = v
for tag in sorted(self.all_tags.keys(), key=key):
item = ListWidgetItem(tag)
item.setData(Qt.UserRole, self.all_tags[tag])
item.setFlags(item.flags() | Qt.ItemIsEditable)
item.setData(Qt.ItemDataRole.UserRole, self.all_tags[tag])
item.setFlags(item.flags() | Qt.ItemFlag.ItemIsEditable)
self.available_tags.addItem(item)
if tag_to_match is not None:
items = self.available_tags.findItems(tag_to_match, Qt.MatchExactly)
items = self.available_tags.findItems(tag_to_match, Qt.MatchFlag.MatchExactly)
if len(items) == 1:
self.available_tags.setCurrentItem(items[0])
@ -92,7 +92,7 @@ class DeviceCategoryEditor(QDialog, Ui_DeviceCategoryEditor):
item.setText(item.previous_text())
return
if item.text() != item.initial_text():
id_ = int(item.data(Qt.UserRole))
id_ = int(item.data(Qt.ItemDataRole.UserRole))
self.to_rename[id_] = unicode_type(item.text())
def rename_tag(self):
@ -118,7 +118,7 @@ class DeviceCategoryEditor(QDialog, Ui_DeviceCategoryEditor):
return
row = self.available_tags.row(deletes[0])
for item in deletes:
id = int(item.data(Qt.UserRole))
id = int(item.data(Qt.ItemDataRole.UserRole))
self.to_delete.add(id)
self.available_tags.takeItem(self.available_tags.row(item))

View File

@ -47,7 +47,7 @@ class DuplicatesQuestion(QDialog):
dl.expandAll()
dl.setIndentation(30)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel)
bb.accepted.connect(self.accept)
bb.rejected.connect(self.reject)
l.addWidget(bb, 2, 0, 1, 2)
@ -72,12 +72,12 @@ class DuplicatesQuestion(QDialog):
def select_all(self):
for i in range(self.dup_list.topLevelItemCount()):
x = self.dup_list.topLevelItem(i)
x.setCheckState(0, Qt.Checked)
x.setCheckState(0, Qt.CheckState.Checked)
def select_none(self):
for i in range(self.dup_list.topLevelItemCount()):
x = self.dup_list.topLevelItem(i)
x.setCheckState(0, Qt.Unchecked)
x.setCheckState(0, Qt.CheckState.Unchecked)
def reject(self):
self.save_geometry()
@ -106,19 +106,19 @@ class DuplicatesQuestion(QDialog):
item = QTreeWidgetItem([ta%dict(
title=mi.title, author=mi.format_field('authors')[1],
formats=incoming_formats)] , 0)
item.setCheckState(0, Qt.Checked)
item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable)
item.setData(0, Qt.FontRole, bf)
item.setData(0, Qt.UserRole, (mi, cover, formats))
item.setCheckState(0, Qt.CheckState.Checked)
item.setFlags(Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsUserCheckable)
item.setData(0, Qt.ItemDataRole.FontRole, bf)
item.setData(0, Qt.ItemDataRole.UserRole, (mi, cover, formats))
matching_books = db.books_with_same_title(mi)
def add_child(text):
c = QTreeWidgetItem([text], 1)
c.setFlags(Qt.ItemIsEnabled)
c.setFlags(Qt.ItemFlag.ItemIsEnabled)
item.addChild(c)
return c
add_child(_('Already in calibre:')).setData(0, Qt.FontRole, itf)
add_child(_('Already in calibre:')).setData(0, Qt.ItemDataRole.FontRole, itf)
author_text = {}
for book_id in matching_books:
@ -142,15 +142,15 @@ class DuplicatesQuestion(QDialog):
def duplicates(self):
for i in range(self.dup_list.topLevelItemCount()):
x = self.dup_list.topLevelItem(i)
if x.checkState(0) == Qt.Checked:
yield x.data(0, Qt.UserRole)
if x.checkState(0) == Qt.CheckState.Checked:
yield x.data(0, Qt.ItemDataRole.UserRole)
@property
def as_text(self):
entries = []
for i in range(self.dup_list.topLevelItemCount()):
x = self.dup_list.topLevelItem(i)
check = '' if x.checkState(0) == Qt.Checked else ''
check = '' if x.checkState(0) == Qt.CheckState.Checked else ''
title = '%s %s' % (check, unicode_type(x.text(0)))
dups = []
for child in (x.child(j) for j in range(x.childCount())):

View File

@ -72,7 +72,7 @@ class EditAuthorsDialog(QDialog, Ui_EditAuthorsDialog):
# Remove help icon on title bar
icon = self.windowIcon()
self.setWindowFlags(self.windowFlags()&(~Qt.WindowContextHelpButtonHint))
self.setWindowFlags(self.windowFlags()&(~Qt.WindowType.WindowContextHelpButtonHint))
self.setWindowIcon(icon)
try:
@ -84,13 +84,13 @@ class EditAuthorsDialog(QDialog, Ui_EditAuthorsDialog):
except Exception:
pass
self.buttonBox.button(QDialogButtonBox.Ok).setText(_('&OK'))
self.buttonBox.button(QDialogButtonBox.Cancel).setText(_('&Cancel'))
self.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setText(_('&OK'))
self.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setText(_('&Cancel'))
self.buttonBox.accepted.connect(self.accepted)
self.apply_vl_checkbox.stateChanged.connect(self.use_vl_changed)
# Set up the heading for sorting
self.table.setSelectionMode(QAbstractItemView.SingleSelection)
self.table.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
self.find_aut_func = find_aut_func
self.table.resizeColumnsToContents()
@ -130,19 +130,19 @@ class EditAuthorsDialog(QDialog, Ui_EditAuthorsDialog):
self.filter_button.clicked.connect(self.do_filter)
self.not_found_label = l = QLabel(self.table)
l.setFrameStyle(QFrame.StyledPanel)
l.setFrameStyle(QFrame.Shape.StyledPanel)
l.setAutoFillBackground(True)
l.setText(_('No matches found'))
l.setAlignment(Qt.AlignVCenter)
l.setAlignment(Qt.AlignmentFlag.AlignVCenter)
l.resize(l.sizeHint())
l.move(10, 2)
l.setVisible(False)
self.not_found_label_timer = QTimer()
self.not_found_label_timer.setSingleShot(True)
self.not_found_label_timer.timeout.connect(
self.not_found_label_timer_event, type=Qt.QueuedConnection)
self.not_found_label_timer_event, type=Qt.ConnectionType.QueuedConnection)
self.table.setContextMenuPolicy(Qt.CustomContextMenu)
self.table.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.table.customContextMenuRequested.connect(self.show_context_menu)
# Fetch the data
@ -202,7 +202,7 @@ class EditAuthorsDialog(QDialog, Ui_EditAuthorsDialog):
name = name.replace('|', ',')
name_item = tableItem(name)
name_item.setData(Qt.UserRole, id_)
name_item.setData(Qt.ItemDataRole.UserRole, id_)
sort_item = tableItem(sort)
link_item = tableItem(link)
@ -239,7 +239,7 @@ class EditAuthorsDialog(QDialog, Ui_EditAuthorsDialog):
if primary_startswith(item_txt, id_to_select):
select_item = self.table.item(row, 1 if use_as else 0)
break
elif id_to_select == self.table.item(row, 0).data(Qt.UserRole):
elif id_to_select == self.table.item(row, 0).data(Qt.ItemDataRole.UserRole):
if select_sort:
select_item = self.table.item(row, 1)
elif select_link:
@ -307,7 +307,7 @@ class EditAuthorsDialog(QDialog, Ui_EditAuthorsDialog):
m = self.au_context_menu = QMenu(self)
idx = self.table.indexAt(point)
id_ = int(self.table.item(idx.row(), 0).data(Qt.UserRole))
id_ = int(self.table.item(idx.row(), 0).data(Qt.ItemDataRole.UserRole))
sub = self.get_column_name(idx.column())
if self.context_item.text() != self.original_authors[id_][sub]:
ca = m.addAction(_('Undo'))
@ -390,10 +390,10 @@ class EditAuthorsDialog(QDialog, Ui_EditAuthorsDialog):
self.not_found_label.setVisible(False)
# For some reason the button box keeps stealing the RETURN shortcut.
# Steal it back
self.buttonBox.button(QDialogButtonBox.Ok).setDefault(False)
self.buttonBox.button(QDialogButtonBox.Ok).setAutoDefault(False)
self.buttonBox.button(QDialogButtonBox.Cancel).setDefault(False)
self.buttonBox.button(QDialogButtonBox.Cancel).setAutoDefault(False)
self.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setDefault(False)
self.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setAutoDefault(False)
self.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setDefault(False)
self.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setAutoDefault(False)
st = icu_lower(unicode_type(self.find_box.currentText()))
if not st:
@ -442,7 +442,7 @@ class EditAuthorsDialog(QDialog, Ui_EditAuthorsDialog):
self.table.cellChanged.disconnect()
for row in range(0,self.table.rowCount()):
item_aut = self.table.item(row, 0)
id_ = int(item_aut.data(Qt.UserRole))
id_ = int(item_aut.data(Qt.ItemDataRole.UserRole))
aut = unicode_type(item_aut.text()).strip()
item_aus = self.table.item(row, 1)
# Sometimes trailing commas are left by changing between copy algs
@ -450,7 +450,7 @@ class EditAuthorsDialog(QDialog, Ui_EditAuthorsDialog):
item_aus.setText(aus)
self.authors[id_]['sort'] = aus
self.set_icon(item_aus, id_)
self.table.setFocus(Qt.OtherFocusReason)
self.table.setFocus(Qt.FocusReason.OtherFocusReason)
self.table.cellChanged.connect(self.cell_changed)
def do_auth_sort_to_author(self):
@ -458,11 +458,11 @@ class EditAuthorsDialog(QDialog, Ui_EditAuthorsDialog):
for row in range(0,self.table.rowCount()):
aus = unicode_type(self.table.item(row, 1).text()).strip()
item_aut = self.table.item(row, 0)
id_ = int(item_aut.data(Qt.UserRole))
id_ = int(item_aut.data(Qt.ItemDataRole.UserRole))
item_aut.setText(aus)
self.authors[id_]['name'] = aus
self.set_icon(item_aut, id_)
self.table.setFocus(Qt.OtherFocusReason)
self.table.setFocus(Qt.FocusReason.OtherFocusReason)
self.table.cellChanged.connect(self.cell_changed)
def set_icon(self, item, id_):
@ -473,7 +473,7 @@ class EditAuthorsDialog(QDialog, Ui_EditAuthorsDialog):
item.setIcon(self.empty_icon)
def cell_changed(self, row, col):
id_ = int(self.table.item(row, 0).data(Qt.UserRole))
id_ = int(self.table.item(row, 0).data(Qt.ItemDataRole.UserRole))
if col == 0:
item = self.table.item(row, 0)
aut = unicode_type(item.text()).strip()

View File

@ -52,7 +52,7 @@ class EnumValuesEdit(QDialog):
t.setColumnCount(2)
t.setRowCount(1)
t.setHorizontalHeaderLabels([_('Value'), _('Color')])
t.setSelectionMode(QAbstractItemView.SingleSelection)
t.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
tl.addWidget(t)
self.fm = fm = db.field_metadata[key]
@ -67,11 +67,11 @@ class EnumValuesEdit(QDialog):
else:
c.setCurrentIndex(0)
t.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
t.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
self.setLayout(l)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
bb.accepted.connect(self.accept)
bb.rejected.connect(self.reject)
l.addWidget(bb, 1, 0, 1, 2)

View File

@ -111,9 +111,9 @@ class RunAction(QDialog):
la.setMaximumWidth(450)
l.addWidget(la, l.rowCount(), 1)
l.addWidget(self.bb, l.rowCount(), 0, 1, -1)
self.update_current_signal.connect(self.update_current, type=Qt.QueuedConnection)
self.update_overall_signal.connect(self.update_overall, type=Qt.QueuedConnection)
self.finish_signal.connect(self.finish_processing, type=Qt.QueuedConnection)
self.update_current_signal.connect(self.update_current, type=Qt.ConnectionType.QueuedConnection)
self.update_overall_signal.connect(self.update_overall, type=Qt.ConnectionType.QueuedConnection)
self.finish_signal.connect(self.finish_processing, type=Qt.ConnectionType.QueuedConnection)
def update_overall(self, msg, count, total):
self.overall.setMaximum(total), self.overall.setValue(count)
@ -206,16 +206,16 @@ class EximDialog(Dialog):
lpaths = all_known_libraries()
for lpath in sorted(lpaths, key=lambda x:numeric_sort_key(os.path.basename(x))):
i = QListWidgetItem(self.export_lib_text(lpath), ll)
i.setData(Qt.UserRole, lpath)
i.setData(Qt.UserRole+1, lpaths[lpath])
i.setData(Qt.ItemDataRole.UserRole, lpath)
i.setData(Qt.ItemDataRole.UserRole+1, lpaths[lpath])
i.setIcon(QIcon(I('lt.png')))
i.setSelected(True)
self.update_disk_usage.connect((
lambda i, sz: self.lib_list.item(i).setText(self.export_lib_text(self.lib_list.item(i).data(Qt.UserRole), sz))), type=Qt.QueuedConnection)
lambda i, sz: self.lib_list.item(i).setText(self.export_lib_text(self.lib_list.item(i).data(Qt.ItemDataRole.UserRole), sz))), type=Qt.ConnectionType.QueuedConnection)
def get_lib_sizes(self):
for i in range(self.lib_list.count()):
path = self.lib_list.item(i).data(Qt.UserRole)
path = self.lib_list.item(i).data(Qt.ItemDataRole.UserRole)
try:
sz = disk_usage(path, abort=self.abort_disk_usage)
except Exception:
@ -353,7 +353,7 @@ class EximDialog(Dialog):
def run_export_action(self):
from calibre.gui2.ui import get_gui
library_paths = {i.data(Qt.UserRole):i.data(Qt.UserRole+1) for i in self.lib_list.selectedItems()}
library_paths = {i.data(Qt.ItemDataRole.UserRole):i.data(Qt.ItemDataRole.UserRole+1) for i in self.lib_list.selectedItems()}
dbmap = {}
gui = get_gui()
if gui is not None:

View File

@ -25,7 +25,7 @@ class TableItem(QTableWidgetItem):
self.sort = sort
self.sort_idx = idx
QTableWidgetItem.__init__(self, val)
self.setFlags(Qt.ItemIsEnabled|Qt.ItemIsSelectable)
self.setFlags(Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsSelectable)
def __ge__(self, other):
l = sort_key(self.sort)
@ -49,7 +49,7 @@ class TableItem(QTableWidgetItem):
class MatchBooks(QDialog, Ui_MatchBooks):
def __init__(self, gui, view, id_, row_index):
QDialog.__init__(self, gui, flags=Qt.Window)
QDialog.__init__(self, gui, flags=Qt.WindowType.Window)
Ui_MatchBooks.__init__(self)
self.setupUi(self)
self.isClosed = False
@ -68,7 +68,7 @@ class MatchBooks(QDialog, Ui_MatchBooks):
# Remove the help button from the window title bar
icon = self.windowIcon()
self.setWindowFlags(self.windowFlags()&(~Qt.WindowContextHelpButtonHint))
self.setWindowFlags(self.windowFlags()&(~Qt.WindowType.WindowContextHelpButtonHint))
self.setWindowIcon(icon)
self.device_db = view.model().db
@ -80,8 +80,8 @@ class MatchBooks(QDialog, Ui_MatchBooks):
self.current_library_book_id = None
# Set up the books table columns
self.books_table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.books_table.setSelectionMode(QAbstractItemView.SingleSelection)
self.books_table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
self.books_table.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
self.books_table.setColumnCount(3)
t = QTableWidgetItem(_('Title'))
self.books_table.setHorizontalHeaderItem(0, t)
@ -92,7 +92,7 @@ class MatchBooks(QDialog, Ui_MatchBooks):
self.books_table_header_height = self.books_table.height()
self.books_table.cellDoubleClicked.connect(self.book_doubleclicked)
self.books_table.cellClicked.connect(self.book_clicked)
self.books_table.sortByColumn(0, Qt.AscendingOrder)
self.books_table.sortByColumn(0, Qt.SortOrder.AscendingOrder)
# get the standard table row height. Do this here because calling
# resizeRowsToContents can word wrap long cell contents, creating
@ -134,7 +134,7 @@ class MatchBooks(QDialog, Ui_MatchBooks):
return
try:
self.search_button.setEnabled(False)
QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
QApplication.setOverrideCursor(QCursor(Qt.CursorShape.WaitCursor))
books = self.library_db.data.search(query, return_matches=True)
self.books_table.setRowCount(len(books))
@ -142,7 +142,7 @@ class MatchBooks(QDialog, Ui_MatchBooks):
for row, b in enumerate(books):
mi = self.library_db.get_metadata(b, index_is_id=True, get_user_categories=False)
a = TableItem(mi.title, mi.title_sort)
a.setData(Qt.UserRole, b)
a.setData(Qt.ItemDataRole.UserRole, b)
self.books_table.setItem(row, 0, a)
a = TableItem(' & '.join(mi.authors), mi.author_sort)
self.books_table.setItem(row, 1, a)
@ -177,7 +177,7 @@ class MatchBooks(QDialog, Ui_MatchBooks):
def book_clicked(self, row, column):
self.book_selected = True
id_ = int(self.books_table.item(row, 0).data(Qt.UserRole))
id_ = int(self.books_table.item(row, 0).data(Qt.ItemDataRole.UserRole))
self.current_library_book_id = id_
def book_doubleclicked(self, row, column):

View File

@ -24,7 +24,7 @@ class Icon(QWidget):
def __init__(self, parent=None, size=None):
QWidget.__init__(self, parent)
self.pixmap = None
self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
self.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
self.size = size or 64
def set_icon(self, qicon):
@ -68,7 +68,7 @@ class MessageBox(QDialog): # {{{
dm.setObjectName("det_msg")
l.addWidget(dm, 1, 0, 1, 2)
self.bb = bb = QDialogButtonBox(self)
bb.setStandardButtons(QDialogButtonBox.Ok)
bb.setStandardButtons(QDialogButtonBox.StandardButton.Ok)
bb.setObjectName("bb")
bb.accepted.connect(self.accept)
bb.rejected.connect(self.reject)
@ -119,7 +119,7 @@ class MessageBox(QDialog): # {{{
self.copy_action = QAction(self)
self.addAction(self.copy_action)
self.copy_action.setShortcuts(QKeySequence.Copy)
self.copy_action.setShortcuts(QKeySequence.StandardKey.Copy)
self.copy_action.triggered.connect(self.copy_to_clipboard)
self.is_question = type_ == self.QUESTION
@ -142,7 +142,7 @@ class MessageBox(QDialog): # {{{
if not det_msg:
self.det_msg_toggle.setVisible(False)
self.resize_needed.connect(self.do_resize, type=Qt.QueuedConnection)
self.resize_needed.connect(self.do_resize, type=Qt.ConnectionType.QueuedConnection)
self.do_resize()
def sizeHint(self):
@ -174,11 +174,11 @@ class MessageBox(QDialog): # {{{
if self.is_question:
try:
self.bb.button(self.bb.Yes if self.default_yes else self.bb.No
).setFocus(Qt.OtherFocusReason)
).setFocus(Qt.FocusReason.OtherFocusReason)
except:
pass # Buttons were changed
else:
self.bb.button(self.bb.Ok).setFocus(Qt.OtherFocusReason)
self.bb.button(self.bb.Ok).setFocus(Qt.FocusReason.OtherFocusReason)
return ret
def set_details(self, msg):
@ -203,7 +203,7 @@ class ViewLog(QDialog): # {{{
self.tb.setHtml('<pre style="font-family: monospace">%s</pre>' % html)
l.addWidget(self.tb)
self.bb = QDialogButtonBox(QDialogButtonBox.Ok)
self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok)
self.bb.accepted.connect(self.accept)
self.bb.rejected.connect(self.reject)
self.copy_button = self.bb.addButton(_('Copy to clipboard'),
@ -327,7 +327,7 @@ class ErrorNotification(MessageBox): # {{{
parent=parent)
self.html_log = html_log
self.log_viewer_title = log_viewer_title
self.finished.connect(self.do_close, type=Qt.QueuedConnection)
self.finished.connect(self.do_close, type=Qt.ConnectionType.QueuedConnection)
self.vlb = self.bb.addButton(_('&View log'), self.bb.ActionRole)
self.vlb.setIcon(QIcon(I('debug.png')))
@ -356,9 +356,9 @@ class JobError(QDialog): # {{{
def __init__(self, parent):
QDialog.__init__(self, parent)
self.setAttribute(Qt.WA_DeleteOnClose, False)
self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, False)
self.queue = []
self.do_pop.connect(self.pop, type=Qt.QueuedConnection)
self.do_pop.connect(self.pop, type=Qt.ConnectionType.QueuedConnection)
self._layout = l = QGridLayout()
self.setLayout(l)
@ -369,11 +369,11 @@ class JobError(QDialog): # {{{
self.msg_label = QLabel('<p>&nbsp;')
self.msg_label.setStyleSheet('QLabel { margin-top: 1ex; }')
self.msg_label.setWordWrap(True)
self.msg_label.setTextFormat(Qt.RichText)
self.msg_label.setTextFormat(Qt.TextFormat.RichText)
self.det_msg = QPlainTextEdit(self)
self.det_msg.setVisible(False)
self.bb = QDialogButtonBox(QDialogButtonBox.Close, parent=self)
self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close, parent=self)
self.bb.accepted.connect(self.accept)
self.bb.rejected.connect(self.reject)
self.ctc_button = self.bb.addButton(_('&Copy to clipboard'),
@ -393,8 +393,8 @@ class JobError(QDialog): # {{{
l.addWidget(self.icon_widget, 0, 0, 1, 1)
l.addWidget(self.msg_label, 0, 1, 1, 1)
l.addWidget(self.det_msg, 1, 0, 1, 2)
l.addWidget(self.suppress, 2, 0, 1, 2, Qt.AlignLeft|Qt.AlignBottom)
l.addWidget(self.bb, 3, 0, 1, 2, Qt.AlignRight|Qt.AlignBottom)
l.addWidget(self.suppress, 2, 0, 1, 2, Qt.AlignmentFlag.AlignLeft|Qt.AlignmentFlag.AlignBottom)
l.addWidget(self.bb, 3, 0, 1, 2, Qt.AlignmentFlag.AlignRight|Qt.AlignmentFlag.AlignBottom)
l.setColumnStretch(1, 100)
self.setModal(False)
@ -441,7 +441,7 @@ class JobError(QDialog): # {{{
def showEvent(self, ev):
ret = QDialog.showEvent(self, ev)
self.bb.button(self.bb.Close).setFocus(Qt.OtherFocusReason)
self.bb.button(self.bb.Close).setFocus(Qt.FocusReason.OtherFocusReason)
return ret
def show_error(self, title, msg, det_msg='', retry_func=None):

View File

@ -108,15 +108,15 @@ class MyBlockingBusy(QDialog): # {{{
self.current_step_value = 0
self._layout.addWidget(self.current_step_pb)
self._layout.addSpacing(15)
self._layout.addWidget(self.msg, 0, Qt.AlignHCenter)
self._layout.addWidget(self.msg, 0, Qt.AlignmentFlag.AlignHCenter)
self.setWindowTitle(window_title + '...')
self.setMinimumWidth(200)
self.resize(self.sizeHint())
self.error = None
self.all_done.connect(self.on_all_done, type=Qt.QueuedConnection)
self.progress_update.connect(self.on_progress_update, type=Qt.QueuedConnection)
self.progress_finished_cur_step.connect(self.on_progress_finished_cur_step, type=Qt.QueuedConnection)
self.progress_next_step_range.connect(self.on_progress_next_step_range, type=Qt.QueuedConnection)
self.all_done.connect(self.on_all_done, type=Qt.ConnectionType.QueuedConnection)
self.progress_update.connect(self.on_progress_update, type=Qt.ConnectionType.QueuedConnection)
self.progress_finished_cur_step.connect(self.on_progress_finished_cur_step, type=Qt.ConnectionType.QueuedConnection)
self.progress_next_step_range.connect(self.on_progress_next_step_range, type=Qt.ConnectionType.QueuedConnection)
self.args, self.ids = args, ids
self.db, self.cc_widgets = db, cc_widgets
self.s_r_func = FunctionDispatcher(s_r_func)
@ -539,7 +539,7 @@ class MetadataBulkDialog(QDialog, Ui_MetadataBulkDialog):
self.prepare_search_and_replace()
self.button_box.clicked.connect(self.button_clicked)
self.button_box.button(QDialogButtonBox.Apply).setToolTip(_(
self.button_box.button(QDialogButtonBox.StandardButton.Apply).setToolTip(_(
'Immediately make all changes without closing the dialog. '
'This operation cannot be canceled or undone'))
self.do_again = False
@ -553,7 +553,7 @@ class MetadataBulkDialog(QDialog, Ui_MetadataBulkDialog):
self.central_widget.setCurrentIndex(ct)
self.languages.init_langs(self.db)
self.languages.setEditText('')
self.authors.setFocus(Qt.OtherFocusReason)
self.authors.setFocus(Qt.FocusReason.OtherFocusReason)
self.generate_cover_settings = None
self.button_config_cover_gen.clicked.connect(self.customize_cover_generation)
self.exec_()
@ -601,7 +601,7 @@ class MetadataBulkDialog(QDialog, Ui_MetadataBulkDialog):
self.adddate.setDateTime(UNDEFINED_QDATETIME)
def button_clicked(self, which):
if which == self.button_box.button(QDialogButtonBox.Apply):
if which == self.button_box.button(QDialogButtonBox.StandardButton.Apply):
self.do_again = True
self.accept()
@ -721,9 +721,9 @@ class MetadataBulkDialog(QDialog, Ui_MetadataBulkDialog):
self.s_r_template.lost_focus.connect(self.s_r_template_changed)
self.central_widget.setCurrentIndex(0)
self.search_for.completer().setCaseSensitivity(Qt.CaseSensitive)
self.replace_with.completer().setCaseSensitivity(Qt.CaseSensitive)
self.s_r_template.completer().setCaseSensitivity(Qt.CaseSensitive)
self.search_for.completer().setCaseSensitivity(Qt.CaseSensitivity.CaseSensitive)
self.replace_with.completer().setCaseSensitivity(Qt.CaseSensitivity.CaseSensitive)
self.s_r_template.completer().setCaseSensitivity(Qt.CaseSensitivity.CaseSensitive)
self.s_r_search_mode_changed(self.search_mode.currentIndex())
self.multiple_separator.setFixedWidth(30)
@ -1111,7 +1111,7 @@ class MetadataBulkDialog(QDialog, Ui_MetadataBulkDialog):
def tag_editor(self, *args):
d = TagEditor(self, self.db, None)
d.exec_()
if d.result() == QDialog.Accepted:
if d.result() == QDialog.DialogCode.Accepted:
tag_string = ', '.join(d.tags)
self.tags.setText(tag_string)
all_tags = self.db.new_api.all_field_names('tags')

View File

@ -74,7 +74,7 @@ class ImportOPML(QDialog):
h.addWidget(b)
l.addRow(_('&OPML file:'), h)
l.labelForField(h).setBuddy(p)
b.setFocus(Qt.OtherFocusReason)
b.setFocus(Qt.FocusReason.OtherFocusReason)
self._articles_per_feed = a = QSpinBox(self)
a.setMinimum(1), a.setMaximum(1000), a.setValue(100)
@ -100,7 +100,7 @@ class ImportOPML(QDialog):
r.setChecked(True)
l.addRow(r)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel)
bb.accepted.connect(self.accept), bb.rejected.connect(self.reject)
l.addRow(bb)

View File

@ -32,10 +32,10 @@ class PasswordDialog(QDialog, Ui_Dialog):
self.show_password.stateChanged[(int)].connect(self.toggle_password)
def toggle_password(self, state):
if state == Qt.Unchecked:
self.gui_password.setEchoMode(QLineEdit.Password)
if state == Qt.CheckState.Unchecked:
self.gui_password.setEchoMode(QLineEdit.EchoMode.Password)
else:
self.gui_password.setEchoMode(QLineEdit.Normal)
self.gui_password.setEchoMode(QLineEdit.EchoMode.Normal)
def username(self):
return unicode_type(self.gui_username.text())

View File

@ -231,8 +231,8 @@ class DisplayPluginSortFilterModel(QSortFilterProxyModel):
def __init__(self, parent):
QSortFilterProxyModel.__init__(self, parent)
self.setSortRole(Qt.UserRole)
self.setSortCaseSensitivity(Qt.CaseInsensitive)
self.setSortRole(Qt.ItemDataRole.UserRole)
self.setSortCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
self.filter_criteria = FILTER_ALL
self.filter_text = ""
@ -273,7 +273,7 @@ class DisplayPluginModel(QAbstractTableModel):
return len(self.headers)
def headerData(self, section, orientation, role):
if role == Qt.DisplayRole and orientation == Qt.Horizontal:
if role == Qt.ItemDataRole.DisplayRole and orientation == Qt.Orientation.Horizontal:
return self.headers[section]
return None
@ -284,7 +284,7 @@ class DisplayPluginModel(QAbstractTableModel):
if row < 0 or row >= self.rowCount():
return None
display_plugin = self.display_plugins[row]
if role in [Qt.DisplayRole, Qt.UserRole]:
if role in [Qt.ItemDataRole.DisplayRole, Qt.ItemDataRole.UserRole]:
if col == 0:
return display_plugin.name
if col == 1:
@ -297,7 +297,7 @@ class DisplayPluginModel(QAbstractTableModel):
if col == 4:
return self._get_display_version(display_plugin.available_version)
if col == 5:
if role == Qt.UserRole:
if role == Qt.ItemDataRole.UserRole:
return self._get_display_release_date(display_plugin.release_date, 'yyyyMMdd')
else:
return self._get_display_release_date(display_plugin.release_date)
@ -305,25 +305,25 @@ class DisplayPluginModel(QAbstractTableModel):
return self._get_display_version(display_plugin.calibre_required_version)
if col == 7:
return display_plugin.author
elif role == Qt.DecorationRole:
elif role == Qt.ItemDataRole.DecorationRole:
if col == 0:
return self._get_status_icon(display_plugin)
if col == 1:
if display_plugin.donation_link:
return QIcon(I('donate.png'))
elif role == Qt.ToolTipRole:
elif role == Qt.ItemDataRole.ToolTipRole:
if col == 1 and display_plugin.donation_link:
return _('This plugin is FREE but you can reward the developer for their effort\n'
'by donating to them via PayPal.\n\n'
'Right-click and choose Donate to reward: ')+display_plugin.author
else:
return self._get_status_tooltip(display_plugin)
elif role == Qt.ForegroundRole:
elif role == Qt.ItemDataRole.ForegroundRole:
if col != 1: # Never change colour of the donation column
if display_plugin.is_deprecated:
return QBrush(Qt.blue)
return QBrush(Qt.GlobalColor.blue)
if display_plugin.is_disabled():
return QBrush(Qt.gray)
return QBrush(Qt.GlobalColor.gray)
return None
def plugin_to_index(self, display_plugin):
@ -483,8 +483,8 @@ class PluginUpdaterDialog(SizePersistedDialog):
self.plugin_view = QTableView(self)
self.plugin_view.horizontalHeader().setStretchLastSection(True)
self.plugin_view.setSelectionBehavior(QAbstractItemView.SelectRows)
self.plugin_view.setSelectionMode(QAbstractItemView.SingleSelection)
self.plugin_view.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
self.plugin_view.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
self.plugin_view.setAlternatingRowColors(True)
self.plugin_view.setSortingEnabled(True)
self.plugin_view.setIconSize(QSize(28, 28))
@ -493,26 +493,26 @@ class PluginUpdaterDialog(SizePersistedDialog):
details_layout = QHBoxLayout()
layout.addLayout(details_layout)
forum_label = self.forum_label = QLabel('')
forum_label.setTextInteractionFlags(Qt.LinksAccessibleByMouse | Qt.LinksAccessibleByKeyboard)
forum_label.setTextInteractionFlags(Qt.TextInteractionFlag.LinksAccessibleByMouse | Qt.TextInteractionFlag.LinksAccessibleByKeyboard)
forum_label.linkActivated.connect(self._forum_label_activated)
details_layout.addWidget(QLabel(_('Description')+':', self), 0, Qt.AlignLeft)
details_layout.addWidget(forum_label, 1, Qt.AlignRight)
details_layout.addWidget(QLabel(_('Description')+':', self), 0, Qt.AlignmentFlag.AlignLeft)
details_layout.addWidget(forum_label, 1, Qt.AlignmentFlag.AlignRight)
self.description = QLabel(self)
self.description.setFrameStyle(QFrame.Panel | QFrame.Sunken)
self.description.setAlignment(Qt.AlignTop | Qt.AlignLeft)
self.description.setFrameStyle(QFrame.Shape.Panel | QFrame.Shadow.Sunken)
self.description.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft)
self.description.setMinimumHeight(40)
self.description.setWordWrap(True)
layout.addWidget(self.description)
self.button_box = QDialogButtonBox(QDialogButtonBox.Close)
self.button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Close)
self.button_box.rejected.connect(self.reject)
self.finished.connect(self._finished)
self.install_button = self.button_box.addButton(_('&Install'), QDialogButtonBox.AcceptRole)
self.install_button = self.button_box.addButton(_('&Install'), QDialogButtonBox.ButtonRole.AcceptRole)
self.install_button.setToolTip(_('Install the selected plugin'))
self.install_button.clicked.connect(self._install_clicked)
self.install_button.setEnabled(False)
self.configure_button = self.button_box.addButton(' '+_('&Customize plugin ')+' ', QDialogButtonBox.ResetRole)
self.configure_button = self.button_box.addButton(' '+_('&Customize plugin ')+' ', QDialogButtonBox.ButtonRole.ResetRole)
self.configure_button.setToolTip(_('Customize the options for this plugin'))
self.configure_button.clicked.connect(self._configure_clicked)
self.configure_button.setEnabled(False)
@ -525,7 +525,7 @@ class PluginUpdaterDialog(SizePersistedDialog):
self.forum_label.setText(txt)
def _create_context_menu(self):
self.plugin_view.setContextMenuPolicy(Qt.ActionsContextMenu)
self.plugin_view.setContextMenuPolicy(Qt.ContextMenuPolicy.ActionsContextMenu)
self.install_action = QAction(QIcon(I('plugins/plugin_upgrade_ok.png')), _('&Install'), self)
self.install_action.setToolTip(_('Install the selected plugin'))
self.install_action.triggered.connect(self._install_clicked)
@ -622,9 +622,9 @@ class PluginUpdaterDialog(SizePersistedDialog):
self.filter_by_name_lineedit.setText("") # clear the name filter text when a different group was selected
self.proxy_model.set_filter_criteria(idx)
if idx == FILTER_NOT_INSTALLED:
self.plugin_view.sortByColumn(5, Qt.DescendingOrder)
self.plugin_view.sortByColumn(5, Qt.SortOrder.DescendingOrder)
else:
self.plugin_view.sortByColumn(0, Qt.AscendingOrder)
self.plugin_view.sortByColumn(0, Qt.SortOrder.AscendingOrder)
self._select_and_focus_view()
def _filter_name_lineedit_changed(self, text):

View File

@ -28,14 +28,14 @@ class ProgressDialog(QDialog):
if not isinstance(icon, QIcon):
icon = QIcon(I(icon))
i.setPixmap(icon.pixmap(64))
h.addWidget(i, alignment=Qt.AlignTop | Qt.AlignHCenter)
h.addWidget(i, alignment=Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignHCenter)
self.l = l = QVBoxLayout()
h.addLayout(l)
self.setWindowIcon(icon)
self.title_label = t = QLabel(title)
self.setWindowTitle(title)
t.setStyleSheet('QLabel { font-weight: bold }'), t.setAlignment(Qt.AlignCenter), t.setTextFormat(Qt.PlainText)
t.setStyleSheet('QLabel { font-weight: bold }'), t.setAlignment(Qt.AlignmentFlag.AlignCenter), t.setTextFormat(Qt.TextFormat.PlainText)
l.addWidget(t)
self.bar = b = QProgressBar(self)
@ -44,15 +44,15 @@ class ProgressDialog(QDialog):
self.message = m = QLabel(self)
fm = QFontMetrics(self.font())
m.setAlignment(Qt.AlignCenter), m.setMinimumWidth(fm.averageCharWidth() * 80), m.setTextFormat(Qt.PlainText)
m.setAlignment(Qt.AlignmentFlag.AlignCenter), m.setMinimumWidth(fm.averageCharWidth() * 80), m.setTextFormat(Qt.TextFormat.PlainText)
l.addWidget(m)
self.msg = msg
self.button_box = bb = QDialogButtonBox(QDialogButtonBox.Abort, self)
self.button_box = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Abort, self)
bb.rejected.connect(self._canceled)
l.addWidget(bb)
self.setWindowModality(Qt.ApplicationModal)
self.setWindowModality(Qt.WindowModality.ApplicationModal)
self.canceled = False
if not cancelable:
@ -125,7 +125,7 @@ class ProgressDialog(QDialog):
QDialog.reject(self)
def keyPressEvent(self, ev):
if ev.key() == Qt.Key_Escape:
if ev.key() == Qt.Key.Key_Escape:
if self.cancelable:
self._canceled()
else:
@ -146,9 +146,9 @@ class BlockingBusy(QDialog):
self.msg.setFont(self.font)
self.pi = ProgressIndicator(self)
self.pi.setDisplaySize(QSize(100, 100))
self._layout.addWidget(self.pi, 0, Qt.AlignHCenter)
self._layout.addWidget(self.pi, 0, Qt.AlignmentFlag.AlignHCenter)
self._layout.addSpacing(15)
self._layout.addWidget(self.msg, 0, Qt.AlignHCenter)
self._layout.addWidget(self.msg, 0, Qt.AlignmentFlag.AlignHCenter)
self.start()
self.setWindowTitle(window_title)
self.resize(self.sizeHint())

View File

@ -33,7 +33,7 @@ class TableItem(QTableWidgetItem):
self.sort = sort
self.sort_idx = idx
QTableWidgetItem.__init__(self, val)
self.setFlags(Qt.ItemIsEnabled|Qt.ItemIsSelectable)
self.setFlags(Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsSelectable)
def __ge__(self, other):
if self.sort is None:
@ -95,7 +95,7 @@ class BooksTableFilter(QObject):
return_pressed_signal = pyqtSignal()
def eventFilter(self, obj, event):
if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Return:
if event.type() == QEvent.Type.KeyPress and event.key() == Qt.Key.Key_Return:
self.return_pressed_signal.emit()
return True
return False
@ -106,7 +106,7 @@ class WidgetFocusFilter(QObject):
focus_entered_signal = pyqtSignal(object)
def eventFilter(self, obj, event):
if event.type() == QEvent.FocusIn:
if event.type() == QEvent.Type.FocusIn:
self.focus_entered_signal.emit(obj)
return False
@ -119,11 +119,11 @@ class WidgetTabFilter(QObject):
self.which_widget = which_widget
def eventFilter(self, obj, event):
if event.type() == QEvent.KeyPress:
if event.key() == Qt.Key_Tab:
if event.type() == QEvent.Type.KeyPress:
if event.key() == Qt.Key.Key_Tab:
self.tab_signal.emit(self.which_widget, True)
return True
if event.key() == Qt.Key_Backtab:
if event.key() == Qt.Key.Key_Backtab:
self.tab_signal.emit(self.which_widget, False)
return True
return False
@ -139,7 +139,7 @@ class Quickview(QDialog, Ui_Quickview):
self.is_pane = gprefs.get('quickview_is_pane', False)
if not self.is_pane:
QDialog.__init__(self, gui, flags=Qt.Widget)
QDialog.__init__(self, gui, flags=Qt.WindowType.Widget)
else:
QDialog.__init__(self, gui)
Ui_Quickview.__init__(self)
@ -175,17 +175,17 @@ class Quickview(QDialog, Ui_Quickview):
self.no_valid_items = False
self.follow_library_view = True
self.apply_vls.setCheckState(Qt.Checked if gprefs['qv_respects_vls']
else Qt.Unchecked)
self.apply_vls.setCheckState(Qt.CheckState.Checked if gprefs['qv_respects_vls']
else Qt.CheckState.Unchecked)
self.apply_vls.stateChanged.connect(self.vl_box_changed)
self.fm = self.db.field_metadata
self.items.setSelectionMode(QAbstractItemView.SingleSelection)
self.items.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
self.items.currentTextChanged.connect(self.item_selected)
self.items.setProperty('highlight_current_item', 150)
self.items.itemDoubleClicked.connect(self.item_doubleclicked)
self.items.setContextMenuPolicy(Qt.CustomContextMenu)
self.items.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.items.customContextMenuRequested.connect(self.show_item_context_menu)
focus_filter = WidgetFocusFilter(self.items)
@ -210,8 +210,8 @@ class Quickview(QDialog, Ui_Quickview):
for idx,widget in enumerate(self.tab_order_widgets):
widget.installEventFilter(WidgetTabFilter(widget, idx, self.tab_pressed_signal))
self.books_table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.books_table.setSelectionMode(QAbstractItemView.SingleSelection)
self.books_table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
self.books_table.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
self.books_table.setProperty('highlight_current_item', 150)
# Set up the books table columns
@ -222,7 +222,7 @@ class Quickview(QDialog, Ui_Quickview):
self.books_table.currentCellChanged.connect(self.books_table_cell_changed)
self.books_table.cellClicked.connect(self.books_table_set_search_string)
self.books_table.cellActivated.connect(self.books_table_set_search_string)
self.books_table.sortByColumn(0, Qt.AscendingOrder)
self.books_table.sortByColumn(0, Qt.SortOrder.AscendingOrder)
# get the standard table row height. Do this here because calling
# resizeRowsToContents can word wrap long cell contents, creating
@ -271,7 +271,7 @@ class Quickview(QDialog, Ui_Quickview):
self.quickview_icon = QIcon(I('quickview.png'))
self.select_book_icon = QIcon(I('library.png'))
self.search_icon = QIcon(I('search.png'))
self.books_table.setContextMenuPolicy(Qt.CustomContextMenu)
self.books_table.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.books_table.customContextMenuRequested.connect(self.show_context_menu)
# Add the quickview toggle as a shortcut for the close button
@ -308,7 +308,7 @@ class Quickview(QDialog, Ui_Quickview):
item = self.books_table.item(index.row(), 0)
if item is None:
return False
book_id = int(item.data(Qt.UserRole))
book_id = int(item.data(Qt.ItemDataRole.UserRole))
book_displayed = self.book_displayed_in_library_view(book_id)
m = self.context_menu = QMenu(self)
a = m.addAction(self.select_book_icon, _('Select this book in the library'),
@ -373,7 +373,7 @@ class Quickview(QDialog, Ui_Quickview):
current = self.books_table.item(current_row, current_col)
if current is None:
return
book_id = current.data(Qt.UserRole)
book_id = current.data(Qt.ItemDataRole.UserRole)
if current is None:
return
@ -409,7 +409,7 @@ class Quickview(QDialog, Ui_Quickview):
in_widget -= 1
if in_widget < 0:
in_widget = len(self.tab_order_widgets) - 1
self.tab_order_widgets[in_widget].setFocus(Qt.TabFocusReason)
self.tab_order_widgets[in_widget].setFocus(Qt.FocusReason.TabFocusReason)
def show(self):
QDialog.show(self)
@ -620,7 +620,7 @@ class Quickview(QDialog, Ui_Quickview):
v = mi.get('book_size')
if v is not None:
a = TableItem('{:n}'.format(v), v)
a.setTextAlignment(Qt.AlignRight)
a.setTextAlignment(Qt.AlignmentFlag.AlignRight)
else:
a = TableItem(' ', None)
elif self.fm[col]['datatype'] == 'series':
@ -642,7 +642,7 @@ class Quickview(QDialog, Ui_Quickview):
except:
traceback.print_exc()
a = TableItem(_('Something went wrong while filling in the table'), '')
a.setData(Qt.UserRole, b)
a.setData(Qt.ItemDataRole.UserRole, b)
a.setToolTip(tt)
self.books_table.setItem(row, self.key_to_table_widget_column(col), a)
self.books_table.setRowHeight(row, self.books_table_row_height)
@ -650,7 +650,7 @@ class Quickview(QDialog, Ui_Quickview):
self.books_table.setSortingEnabled(True)
if select_item is not None:
self.books_table.setCurrentItem(select_item)
self.books_table.scrollToItem(select_item, QAbstractItemView.PositionAtCenter)
self.books_table.scrollToItem(select_item, QAbstractItemView.ScrollHint.PositionAtCenter)
self.set_search_text(sv)
# Deal with sizing the table columns. Done here because the numbers are not
@ -744,13 +744,13 @@ class Quickview(QDialog, Ui_Quickview):
item = self.books_table.item(row, column)
if item is None:
return
book_id = int(self.books_table.item(row, column).data(Qt.UserRole))
book_id = int(self.books_table.item(row, column).data(Qt.ItemDataRole.UserRole))
if not self.book_displayed_in_library_view(book_id):
self.book_not_in_view_error()
return
key = self.column_order[column]
modifiers = int(QApplication.keyboardModifiers())
if modifiers in (Qt.CTRL, Qt.SHIFT):
if modifiers in (Qt.Modifier.CTRL, Qt.Modifier.SHIFT):
self.edit_metadata(book_id)
else:
self.view.select_cell(self.db.data.id_to_index(book_id),
@ -808,7 +808,7 @@ class Quickview(QDialog, Ui_Quickview):
def _reject(self):
if self.is_pane:
self.gui.quickview_splitter.hide_quickview_widget()
self.gui.library_view.setFocus(Qt.ActiveWindowFocusReason)
self.gui.library_view.setFocus(Qt.FocusReason.ActiveWindowFocusReason)
self._close()
QDialog.reject(self)

View File

@ -31,14 +31,14 @@ class DBRestore(QDialog):
self.msg = QLabel('')
self.l.addWidget(self.msg)
self.msg.setWordWrap(True)
self.bb = QDialogButtonBox(QDialogButtonBox.Cancel)
self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel)
self.l.addWidget(self.bb)
self.bb.rejected.connect(self.confirm_cancel)
self.resize(self.sizeHint() + QSize(100, 50))
self.error = None
self.rejected = False
self.library_path = library_path
self.update_signal.connect(self.do_update, type=Qt.QueuedConnection)
self.update_signal.connect(self.do_update, type=Qt.ConnectionType.QueuedConnection)
from calibre.db.restore import Restore
self.restorer = Restore(library_path, self)

View File

@ -57,7 +57,7 @@ class AddSavedSearch(Dialog):
s.setPlaceholderText(_('The search expression'))
if self.initial_search:
s.setText(self.initial_search)
n.setFocus(Qt.OtherFocusReason)
n.setFocus(Qt.FocusReason.OtherFocusReason)
l.addRow(self.bb)
def accept(self):
@ -142,7 +142,7 @@ class SavedSearchEditor(Dialog):
return ans
def keyPressEvent(self, ev):
if ev.key() == Qt.Key_Delete:
if ev.key() == Qt.Key.Key_Delete:
self.del_search()
return
return Dialog.keyPressEvent(self, ev)
@ -202,7 +202,7 @@ class SavedSearchEditor(Dialog):
return _('A saved search with the name {} already exists. Choose another name').format(name)
def select_search(self, name):
items = self.slist.findItems(name, Qt.MatchFixedString | Qt.MatchCaseSensitive)
items = self.slist.findItems(name, Qt.MatchFlag.MatchFixedString | Qt.MatchFlag.MatchCaseSensitive)
if items:
self.slist.setCurrentItem(items[0])

View File

@ -44,7 +44,7 @@ class RecipesView(QTreeView):
self.setAnimated(True)
self.setHeaderHidden(True)
self.setObjectName('recipes')
self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding)
self.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Expanding)
def currentChanged(self, current, previous):
QTreeView.currentChanged(self, current, previous)
@ -240,10 +240,10 @@ class SchedulerDialog(QDialog):
self.recipe_model = recipe_model
self.recipe_model.do_refresh()
self.recipes.setModel(self.recipe_model)
self.recipes.setFocus(Qt.OtherFocusReason)
self.recipes.setFocus(Qt.FocusReason.OtherFocusReason)
self.setWindowTitle(_("Schedule news download [{} sources]").format(self.recipe_model.showing_count))
self.search.search.connect(self.recipe_model.search)
self.recipe_model.searched.connect(self.search.search_done, type=Qt.QueuedConnection)
self.recipe_model.searched.connect(self.search.search_done, type=Qt.ConnectionType.QueuedConnection)
self.recipe_model.searched.connect(self.search_done)
# Right Panel
@ -255,7 +255,7 @@ class SchedulerDialog(QDialog):
self.detail_box.setVisible(False)
self.detail_box.setCurrentIndex(0)
v.addWidget(self.detail_box)
v.addItem(QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding))
v.addItem(QSpacerItem(20, 40, QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Expanding))
# First Tab (scheduling)
self.tab = QWidget()
@ -299,7 +299,7 @@ class SchedulerDialog(QDialog):
g.addWidget(la), g.addWidget(un, 0, 1)
acc.pwla = la = QLabel(_("&Password:"))
self.password = pw = QLineEdit(self)
pw.setEchoMode(QLineEdit.Password), la.setBuddy(pw)
pw.setEchoMode(QLineEdit.EchoMode.Password), la.setBuddy(pw)
g.addWidget(la), g.addWidget(pw, 1, 1)
self.show_password = spw = QCheckBox(_("&Show password"), self.account)
spw.stateChanged[int].connect(self.set_pw_echo_mode)
@ -335,7 +335,7 @@ class SchedulerDialog(QDialog):
" older than a number of days, below, takes priority over this setting."))
ki.setSpecialValueText(_("all issues")), ki.setSuffix(_(" issues"))
g.addWidget(la), g.addWidget(ki, 2, 1)
si = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
si = QSpacerItem(20, 40, QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Expanding)
g.addItem(si, 3, 1, 1, 1)
# Bottom area
@ -355,7 +355,7 @@ class SchedulerDialog(QDialog):
b.setToolTip(_("Download all scheduled news sources at once"))
b.clicked.connect(self.download_all_clicked)
self.l.addWidget(b, 3, 0, 1, 1)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, self)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel, self)
bb.accepted.connect(self.accept), bb.rejected.connect(self.reject)
self.download_button = b = bb.addButton(_('&Download now'), bb.ActionRole)
b.setIcon(QIcon(I('arrow-down.png'))), b.setVisible(False)
@ -371,7 +371,7 @@ class SchedulerDialog(QDialog):
def set_pw_echo_mode(self, state):
self.password.setEchoMode(self.password.Normal
if state == Qt.Checked else self.password.Password)
if state == Qt.CheckState.Checked else self.password.Password)
def schedule_type_selected(self, *args):
for i, st in enumerate(self.SCHEDULE_TYPES):
@ -380,7 +380,7 @@ class SchedulerDialog(QDialog):
break
def keyPressEvent(self, ev):
if ev.key() not in (Qt.Key_Enter, Qt.Key_Return):
if ev.key() not in (Qt.Key.Key_Enter, Qt.Key.Key_Return):
return QDialog.keyPressEvent(self, ev)
def break_cycles(self):
@ -578,7 +578,7 @@ class Scheduler(QObject):
self.recipe_model = RecipeModel()
self.db = db
self.lock = QMutex(QMutex.Recursive)
self.lock = QMutex(QMutex.RecursionMode.Recursive)
self.download_queue = set()
self.news_menu = QMenu()

View File

@ -44,8 +44,8 @@ def current_dateop(cb):
def create_msg_label(self):
self.frame = f = QFrame(self)
f.setFrameShape(QFrame.StyledPanel)
f.setFrameShadow(QFrame.Raised)
f.setFrameShape(QFrame.Shape.StyledPanel)
f.setFrameShadow(QFrame.Shadow.Raised)
f.l = l = QVBoxLayout(f)
f.um_label = la = QLabel(_(
"<p>You can also perform other kinds of advanced searches, for example checking"
@ -74,8 +74,8 @@ def create_match_kind(self):
def create_button_box(self):
self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
self.clear_button = bb.addButton(_('&Clear'), QDialogButtonBox.ResetRole)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
self.clear_button = bb.addButton(_('&Clear'), QDialogButtonBox.ButtonRole.ResetRole)
self.clear_button.clicked.connect(self.clear_button_pushed)
bb.accepted.connect(self.accept)
bb.rejected.connect(self.reject)
@ -308,7 +308,7 @@ class SearchDialog(QDialog):
focused_field = gprefs.get('advanced_search_simple_tab_focused_field', 'title_box')
w = getattr(self, focused_field, None)
if w is not None:
w.setFocus(Qt.OtherFocusReason)
w.setFocus(Qt.FocusReason.OtherFocusReason)
elif current_tab == 3:
self.template_program_box.setText(
gprefs.get('advanced_search_template_tab_program_field', ''))

View File

@ -26,13 +26,13 @@ class Formats(QAbstractListModel):
def data(self, index, role):
row = index.row()
if role == Qt.DisplayRole:
if role == Qt.ItemDataRole.DisplayRole:
fmt = self.fmts[row]
count = self.counts[fmt]
return ('%s [%d]'%(fmt.upper(), count))
if role == Qt.DecorationRole:
if role == Qt.ItemDataRole.DecorationRole:
return (self.fi.icon_from_ext(self.fmts[row].lower()))
if role == Qt.ToolTipRole:
if role == Qt.ItemDataRole.ToolTipRole:
fmt = self.fmts[row]
count = self.counts[fmt]
return _('There is one book with the {} format').format(fmt.upper()) if count == 1 else _(
@ -41,7 +41,7 @@ class Formats(QAbstractListModel):
return None
def flags(self, index):
return Qt.ItemIsSelectable|Qt.ItemIsEnabled
return Qt.ItemFlag.ItemIsSelectable|Qt.ItemFlag.ItemIsEnabled
def fmt(self, idx):
return self.fmts[idx.row()]
@ -61,7 +61,7 @@ class SelectFormats(QDialog):
self.formats = Formats(fmt_count)
self.fview = QListView(self)
self.fview.doubleClicked.connect(self.double_clicked,
type=Qt.QueuedConnection)
type=Qt.ConnectionType.QueuedConnection)
if exclude:
if QApplication.instance().is_dark_theme:
sheet = 'background-color: #DAA520; color: black'
@ -73,8 +73,8 @@ class SelectFormats(QDialog):
self.fview.setSelectionMode(self.fview.SingleSelection if single else
self.fview.MultiSelection)
self.bbox = \
QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel,
Qt.Horizontal, self)
QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel,
Qt.Orientation.Horizontal, self)
self._l.addWidget(self.bbox)
self.bbox.accepted.connect(self.accept)
self.bbox.rejected.connect(self.reject)

View File

@ -100,11 +100,11 @@ class SmartdeviceDialog(QDialog, Ui_Dialog):
self.resize(self.sizeHint())
def use_fixed_port_changed(self, state):
self.fixed_port.setEnabled(state == Qt.Checked)
self.fixed_port.setEnabled(state == Qt.CheckState.Checked)
def toggle_password(self, state):
self.password_box.setEchoMode(QLineEdit.Password if state ==
Qt.Unchecked else QLineEdit.Normal)
self.password_box.setEchoMode(QLineEdit.EchoMode.Password if state ==
Qt.CheckState.Unchecked else QLineEdit.EchoMode.Normal)
def accept(self):
port = unicode_type(self.fixed_port.text())

Some files were not shown because too many files have changed in this diff Show More