diff --git a/src/calibre/customize/__init__.py b/src/calibre/customize/__init__.py index 95b259c8e2..8c689b9a76 100644 --- a/src/calibre/customize/__init__.py +++ b/src/calibre/customize/__init__.py @@ -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) diff --git a/src/calibre/devices/kobo/kobotouch_config.py b/src/calibre/devices/kobo/kobotouch_config.py index ca71964126..67dd48701b 100644 --- a/src/calibre/devices/kobo/kobotouch_config.py +++ b/src/calibre/devices/kobo/kobotouch_config.py @@ -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) diff --git a/src/calibre/ebooks/conversion/plugins/pdf_output.py b/src/calibre/ebooks/conversion/plugins/pdf_output.py index 09ba4c77fd..2345c2501f 100644 --- a/src/calibre/ebooks/conversion/plugins/pdf_output.py +++ b/src/calibre/ebooks/conversion/plugins/pdf_output.py @@ -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 diff --git a/src/calibre/ebooks/covers.py b/src/calibre/ebooks/covers.py index 3d401932f2..3faae54842 100644 --- a/src/calibre/ebooks/covers.py +++ b/src/calibre/ebooks/covers.py @@ -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 diff --git a/src/calibre/ebooks/html/to_zip.py b/src/calibre/ebooks/html/to_zip.py index c205e0cc8c..f5805136bd 100644 --- a/src/calibre/ebooks/html/to_zip.py +++ b/src/calibre/ebooks/html/to_zip.py @@ -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' diff --git a/src/calibre/ebooks/oeb/polish/check/css.py b/src/calibre/ebooks/oeb/polish/check/css.py index 74245a86c3..5ef001221b 100644 --- a/src/calibre/ebooks/oeb/polish/check/css.py +++ b/src/calibre/ebooks/oeb/polish/check/css.py @@ -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): diff --git a/src/calibre/ebooks/oeb/transforms/rasterize.py b/src/calibre/ebooks/oeb/transforms/rasterize.py index c500e7276e..ef4bfac94e 100644 --- a/src/calibre/ebooks/oeb/transforms/rasterize.py +++ b/src/calibre/ebooks/oeb/transforms/rasterize.py @@ -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 diff --git a/src/calibre/ebooks/pdf/develop.py b/src/calibre/ebooks/pdf/develop.py index eaae643668..ab9ff4db0c 100644 --- a/src/calibre/ebooks/pdf/develop.py +++ b/src/calibre/ebooks/pdf/develop.py @@ -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): diff --git a/src/calibre/ebooks/pdf/html_writer.py b/src/calibre/ebooks/pdf/html_writer.py index 1c03a9f742..d2886bfdf4 100644 --- a/src/calibre/ebooks/pdf/html_writer.py +++ b/src/calibre/ebooks/pdf/html_writer.py @@ -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 diff --git a/src/calibre/ebooks/pdf/image_writer.py b/src/calibre/ebooks/pdf/image_writer.py index d09413ac53..4ff0110ed7 100644 --- a/src/calibre/ebooks/pdf/image_writer.py +++ b/src/calibre/ebooks/pdf/image_writer.py @@ -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 # }}} diff --git a/src/calibre/ebooks/pdf/pageoptions.py b/src/calibre/ebooks/pdf/pageoptions.py index 6dccf2f14f..c78a58c0a3 100644 --- a/src/calibre/ebooks/pdf/pageoptions.py +++ b/src/calibre/ebooks/pdf/pageoptions.py @@ -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): diff --git a/src/calibre/ebooks/pdf/render/graphics.py b/src/calibre/ebooks/pdf/render/graphics.py index 0f641ceba5..14c33f5fe3 100644 --- a/src/calibre/ebooks/pdf/render/graphics.py +++ b/src/calibre/ebooks/pdf/render/graphics.py @@ -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): diff --git a/src/calibre/ebooks/pdf/render/serialize.py b/src/calibre/ebooks/pdf/render/serialize.py index 8d6a5cb9c1..e9fa01a56e 100644 --- a/src/calibre/ebooks/pdf/render/serialize.py +++ b/src/calibre/ebooks/pdf/render/serialize.py @@ -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() diff --git a/src/calibre/ebooks/render_html.py b/src/calibre/ebooks/render_html.py index f18eb3caab..e8dbafc843 100644 --- a/src/calibre/ebooks/render_html.py +++ b/src/calibre/ebooks/render_html.py @@ -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() diff --git a/src/calibre/gui2/__init__.py b/src/calibre/gui2/__init__.py index 51a2687e34..19fd86ecef 100644 --- a/src/calibre/gui2/__init__.py +++ b/src/calibre/gui2/__init__.py @@ -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 diff --git a/src/calibre/gui2/actions/__init__.py b/src/calibre/gui2/actions/__init__.py index d1e006fd1c..411660edb3 100644 --- a/src/calibre/gui2/actions/__init__.py +++ b/src/calibre/gui2/actions/__init__.py @@ -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: diff --git a/src/calibre/gui2/actions/annotate.py b/src/calibre/gui2/actions/annotate.py index eaa4ab9512..31151f3c94 100644 --- a/src/calibre/gui2/actions/annotate.py +++ b/src/calibre/gui2/actions/annotate.py @@ -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 diff --git a/src/calibre/gui2/actions/browse_annots.py b/src/calibre/gui2/actions/browse_annots.py index 88cd8e36f8..f055789ac3 100644 --- a/src/calibre/gui2/actions/browse_annots.py +++ b/src/calibre/gui2/actions/browse_annots.py @@ -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): diff --git a/src/calibre/gui2/actions/choose_library.py b/src/calibre/gui2/actions/choose_library.py index 9e61bd839c..70f53651ae 100644 --- a/src/calibre/gui2/actions/choose_library.py +++ b/src/calibre/gui2/actions/choose_library.py @@ -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',)) diff --git a/src/calibre/gui2/actions/copy_to_library.py b/src/calibre/gui2/actions/copy_to_library.py index a78582bd72..5a626dac42 100644 --- a/src/calibre/gui2/actions/copy_to_library.py +++ b/src/calibre/gui2/actions/copy_to_library.py @@ -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 {0} library are different from the ' 'custom columns in the {1} 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 diff --git a/src/calibre/gui2/actions/device.py b/src/calibre/gui2/actions/device.py index 09920d42b2..af8da7c7e9 100644 --- a/src/calibre/gui2/actions/device.py +++ b/src/calibre/gui2/actions/device.py @@ -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 diff --git a/src/calibre/gui2/actions/embed.py b/src/calibre/gui2/actions/embed.py index 65016db497..f1b54a13c1 100644 --- a/src/calibre/gui2/actions/embed.py +++ b/src/calibre/gui2/actions/embed.py @@ -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() diff --git a/src/calibre/gui2/actions/fetch_news.py b/src/calibre/gui2/actions/fetch_news.py index cfc860f0be..0db1590fdd 100644 --- a/src/calibre/gui2/actions/fetch_news.py +++ b/src/calibre/gui2/actions/fetch_news.py @@ -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} diff --git a/src/calibre/gui2/actions/mark_books.py b/src/calibre/gui2/actions/mark_books.py index 83f9841b66..2911f473b6 100644 --- a/src/calibre/gui2/actions/mark_books.py +++ b/src/calibre/gui2/actions/mark_books.py @@ -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 diff --git a/src/calibre/gui2/actions/plugin_updates.py b/src/calibre/gui2/actions/plugin_updates.py index d22c5a2693..f904970e5b 100644 --- a/src/calibre/gui2/actions/plugin_updates.py +++ b/src/calibre/gui2/actions/plugin_updates.py @@ -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) diff --git a/src/calibre/gui2/actions/polish.py b/src/calibre/gui2/actions/polish.py index 00a286b946..f0fce0242e 100644 --- a/src/calibre/gui2/actions/polish.py +++ b/src/calibre/gui2/actions/polish.py @@ -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.', diff --git a/src/calibre/gui2/actions/preferences.py b/src/calibre/gui2/actions/preferences.py index 8deefa5e27..a38f627b37 100644 --- a/src/calibre/gui2/actions/preferences.py +++ b/src/calibre/gui2/actions/preferences.py @@ -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) diff --git a/src/calibre/gui2/actions/show_book_details.py b/src/calibre/gui2/actions/show_book_details.py index 75d4eef7f2..8c66d3d88e 100644 --- a/src/calibre/gui2/actions/show_book_details.py +++ b/src/calibre/gui2/actions/show_book_details.py @@ -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): diff --git a/src/calibre/gui2/actions/similar_books.py b/src/calibre/gui2/actions/similar_books.py index c655f05700..24ce8942c1 100644 --- a/src/calibre/gui2/actions/similar_books.py +++ b/src/calibre/gui2/actions/similar_books.py @@ -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 diff --git a/src/calibre/gui2/actions/sort.py b/src/calibre/gui2/actions/sort.py index 99cd2a5c1a..7ae1295c2e 100644 --- a/src/calibre/gui2/actions/sort.py +++ b/src/calibre/gui2/actions/sort.py @@ -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', )) diff --git a/src/calibre/gui2/actions/toc_edit.py b/src/calibre/gui2/actions/toc_edit.py index 91819999cd..9e35fdb413 100644 --- a/src/calibre/gui2/actions/toc_edit.py +++ b/src/calibre/gui2/actions/toc_edit.py @@ -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) diff --git a/src/calibre/gui2/actions/tweak_epub.py b/src/calibre/gui2/actions/tweak_epub.py index 405b2eea5a..b167850090 100644 --- a/src/calibre/gui2/actions/tweak_epub.py +++ b/src/calibre/gui2/actions/tweak_epub.py @@ -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) diff --git a/src/calibre/gui2/actions/unpack_book.py b/src/calibre/gui2/actions/unpack_book.py index 08b14f1cdc..4f115b3a95 100644 --- a/src/calibre/gui2/actions/unpack_book.py +++ b/src/calibre/gui2/actions/unpack_book.py @@ -94,7 +94,7 @@ class UnpackBook(QDialog): ''')) 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) diff --git a/src/calibre/gui2/actions/view.py b/src/calibre/gui2/actions/view.py index 702d772459..fbabd3409a 100644 --- a/src/calibre/gui2/actions/view.py +++ b/src/calibre/gui2/actions/view.py @@ -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] diff --git a/src/calibre/gui2/actions/virtual_library.py b/src/calibre/gui2/actions/virtual_library.py index 517cbf70a2..08686907bd 100644 --- a/src/calibre/gui2/actions/virtual_library.py +++ b/src/calibre/gui2/actions/virtual_library.py @@ -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): diff --git a/src/calibre/gui2/add.py b/src/calibre/gui2/add.py index 592a60d6fa..3215e0e8f7 100644 --- a/src/calibre/gui2/add.py +++ b/src/calibre/gui2/add.py @@ -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) diff --git a/src/calibre/gui2/auto_add.py b/src/calibre/gui2/auto_add.py index ccd0f12d30..fc119a011d 100644 --- a/src/calibre/gui2/auto_add.py +++ b/src/calibre/gui2/auto_add.py @@ -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() diff --git a/src/calibre/gui2/bars.py b/src/calibre/gui2/bars.py index 17c4bf435a..42b992261c 100644 --- a/src/calibre/gui2/bars.py +++ b/src/calibre/gui2/bars.py @@ -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)) diff --git a/src/calibre/gui2/book_details.py b/src/calibre/gui2/book_details.py index 850b1edcce..3cff153eb3 100644 --- a/src/calibre/gui2/book_details.py +++ b/src/calibre/gui2/book_details.py @@ -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() diff --git a/src/calibre/gui2/catalog/catalog_csv_xml.py b/src/calibre/gui2/catalog/catalog_csv_xml.py index 2a7319830e..2b9e1cfdbb 100644 --- a/src/calibre/gui2/catalog/catalog_csv_xml.py +++ b/src/calibre/gui2/catalog/catalog_csv_xml.py @@ -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 diff --git a/src/calibre/gui2/catalog/catalog_epub_mobi.py b/src/calibre/gui2/catalog/catalog_epub_mobi.py index 0db35a4353..7e7be8cd84 100644 --- a/src/calibre/gui2/catalog/catalog_epub_mobi.py +++ b/src/calibre/gui2/catalog/catalog_epub_mobi.py @@ -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() diff --git a/src/calibre/gui2/comments_editor.py b/src/calibre/gui2/comments_editor.py index dc99fe095f..c4fb93a223 100644 --- a/src/calibre/gui2/comments_editor.py +++ b/src/calibre/gui2/comments_editor.py @@ -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: diff --git a/src/calibre/gui2/complete2.py b/src/calibre/gui2/complete2.py index 9412abea72..a3b4214699 100644 --- a/src/calibre/gui2/complete2.py +++ b/src/calibre/gui2/complete2.py @@ -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: diff --git a/src/calibre/gui2/convert/__init__.py b/src/calibre/gui2/convert/__init__.py index c66bc6ec89..6c18692df4 100644 --- a/src/calibre/gui2/convert/__init__.py +++ b/src/calibre/gui2/convert/__init__.py @@ -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: diff --git a/src/calibre/gui2/convert/docx_output.py b/src/calibre/gui2/convert/docx_output.py index f4a740b797..e1ac7b7c7d 100644 --- a/src/calibre/gui2/convert/docx_output.py +++ b/src/calibre/gui2/convert/docx_output.py @@ -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] diff --git a/src/calibre/gui2/convert/heuristics.py b/src/calibre/gui2/convert/heuristics.py index cd83dbfc86..a053c4655f 100644 --- a/src/calibre/gui2/convert/heuristics.py +++ b/src/calibre/gui2/convert/heuristics.py @@ -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 diff --git a/src/calibre/gui2/convert/look_and_feel.py b/src/calibre/gui2/convert/look_and_feel.py index dbc6c286fb..9c02da4fcf 100644 --- a/src/calibre/gui2/convert/look_and_feel.py +++ b/src/calibre/gui2/convert/look_and_feel.py @@ -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: diff --git a/src/calibre/gui2/convert/page_setup.py b/src/calibre/gui2/convert/page_setup.py index 1887e29458..42bfaff371 100644 --- a/src/calibre/gui2/convert/page_setup.py +++ b/src/calibre/gui2/convert/page_setup.py @@ -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('
'+it.replace('t.','ce.\n
'))
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):
diff --git a/src/calibre/gui2/convert/regex_builder.py b/src/calibre/gui2/convert/regex_builder.py
index 740986dff1..7f74558bd7 100644
--- a/src/calibre/gui2/convert/regex_builder.py
+++ b/src/calibre/gui2/convert/regex_builder.py
@@ -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
diff --git a/src/calibre/gui2/convert/search_and_replace.py b/src/calibre/gui2/convert/search_and_replace.py
index 0cce946ed7..db3e54af1e 100644
--- a/src/calibre/gui2/convert/search_and_replace.py
+++ b/src/calibre/gui2/convert/search_and_replace.py
@@ -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)
diff --git a/src/calibre/gui2/convert/single.py b/src/calibre/gui2/convert/single.py
index bba385a0b9..47948f74e8 100644
--- a/src/calibre/gui2/convert/single.py
+++ b/src/calibre/gui2/convert/single.py
@@ -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())
diff --git a/src/calibre/gui2/convert/txt_input.py b/src/calibre/gui2/convert/txt_input.py
index 1838b915e0..f51d6d9745 100644
--- a/src/calibre/gui2/convert/txt_input.py
+++ b/src/calibre/gui2/convert/txt_input.py
@@ -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:
diff --git a/src/calibre/gui2/convert/xpath_wizard.py b/src/calibre/gui2/convert/xpath_wizard.py
index b5a7ca05b2..1797bbcaa7 100644
--- a/src/calibre/gui2/convert/xpath_wizard.py
+++ b/src/calibre/gui2/convert/xpath_wizard.py
@@ -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):
diff --git a/src/calibre/gui2/cover_flow.py b/src/calibre/gui2/cover_flow.py
index 10125c5c03..cedc104ecc 100644
--- a/src/calibre/gui2/cover_flow.py
+++ b/src/calibre/gui2/cover_flow.py
@@ -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_())
diff --git a/src/calibre/gui2/covers.py b/src/calibre/gui2/covers.py
index a82c329766..c65a35c21b 100644
--- a/src/calibre/gui2/covers.py
+++ b/src/calibre/gui2/covers.py
@@ -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)
diff --git a/src/calibre/gui2/custom_column_widgets.py b/src/calibre/gui2/custom_column_widgets.py
index b9ef5b1807..9e4721043f 100644
--- a/src/calibre/gui2/custom_column_widgets.py
+++ b/src/calibre/gui2/custom_column_widgets.py
@@ -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.') + '
'+_('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): diff --git a/src/calibre/gui2/dialogs/choose_format.py b/src/calibre/gui2/dialogs/choose_format.py index b0eb82aa33..d8390e8114 100644 --- a/src/calibre/gui2/dialogs/choose_format.py +++ b/src/calibre/gui2/dialogs/choose_format.py @@ -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) diff --git a/src/calibre/gui2/dialogs/choose_library.py b/src/calibre/gui2/dialogs/choose_library.py index da2d51fcc6..45b1156749 100644 --- a/src/calibre/gui2/dialogs/choose_library.py +++ b/src/calibre/gui2/dialogs/choose_library.py @@ -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 diff --git a/src/calibre/gui2/dialogs/choose_plugin_toolbars.py b/src/calibre/gui2/dialogs/choose_plugin_toolbars.py index f9f49407d7..ddb24b9213 100644 --- a/src/calibre/gui2/dialogs/choose_plugin_toolbars.py +++ b/src/calibre/gui2/dialogs/choose_plugin_toolbars.py @@ -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 Preferences -> Interface -> Toolbars')) 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) diff --git a/src/calibre/gui2/dialogs/comments_dialog.py b/src/calibre/gui2/dialogs/comments_dialog.py index efa4833787..ae284cfa70 100644 --- a/src/calibre/gui2/dialogs/comments_dialog.py +++ b/src/calibre/gui2/dialogs/comments_dialog.py @@ -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)) diff --git a/src/calibre/gui2/dialogs/confirm_delete.py b/src/calibre/gui2/dialogs/confirm_delete.py index bfd5bec21b..d2ce4065da 100644 --- a/src/calibre/gui2/dialogs/confirm_delete.py +++ b/src/calibre/gui2/dialogs/confirm_delete.py @@ -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() diff --git a/src/calibre/gui2/dialogs/confirm_delete_location.py b/src/calibre/gui2/dialogs/confirm_delete_location.py index a605e56e81..790429a1f3 100644 --- a/src/calibre/gui2/dialogs/confirm_delete_location.py +++ b/src/calibre/gui2/dialogs/confirm_delete_location.py @@ -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')) diff --git a/src/calibre/gui2/dialogs/confirm_merge.py b/src/calibre/gui2/dialogs/confirm_merge.py index a3d7fa91bd..cc20730640 100644 --- a/src/calibre/gui2/dialogs/confirm_merge.py +++ b/src/calibre/gui2/dialogs/confirm_merge.py @@ -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) diff --git a/src/calibre/gui2/dialogs/custom_recipes.py b/src/calibre/gui2/dialogs/custom_recipes.py index 09d427525b..934c572c93 100644 --- a/src/calibre/gui2/dialogs/custom_recipes.py +++ b/src/calibre/gui2/dialogs/custom_recipes.py @@ -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 diff --git a/src/calibre/gui2/dialogs/delete_matching_from_device.py b/src/calibre/gui2/dialogs/delete_matching_from_device.py index 0d04650d2d..4ecf86e8c7 100644 --- a/src/calibre/gui2/dialogs/delete_matching_from_device.py +++ b/src/calibre/gui2/dialogs/delete_matching_from_device.py @@ -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 diff --git a/src/calibre/gui2/dialogs/device_category_editor.py b/src/calibre/gui2/dialogs/device_category_editor.py index c0edd8378b..1ed833b6be 100644 --- a/src/calibre/gui2/dialogs/device_category_editor.py +++ b/src/calibre/gui2/dialogs/device_category_editor.py @@ -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)) diff --git a/src/calibre/gui2/dialogs/duplicates.py b/src/calibre/gui2/dialogs/duplicates.py index 57c9402e1b..c253384f8e 100644 --- a/src/calibre/gui2/dialogs/duplicates.py +++ b/src/calibre/gui2/dialogs/duplicates.py @@ -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())): diff --git a/src/calibre/gui2/dialogs/edit_authors_dialog.py b/src/calibre/gui2/dialogs/edit_authors_dialog.py index a05fc7b369..e145756b52 100644 --- a/src/calibre/gui2/dialogs/edit_authors_dialog.py +++ b/src/calibre/gui2/dialogs/edit_authors_dialog.py @@ -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() diff --git a/src/calibre/gui2/dialogs/enum_values_edit.py b/src/calibre/gui2/dialogs/enum_values_edit.py index bae9f0eea1..80b98cf282 100644 --- a/src/calibre/gui2/dialogs/enum_values_edit.py +++ b/src/calibre/gui2/dialogs/enum_values_edit.py @@ -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) diff --git a/src/calibre/gui2/dialogs/exim.py b/src/calibre/gui2/dialogs/exim.py index 0509e6d844..a99cc0cb84 100644 --- a/src/calibre/gui2/dialogs/exim.py +++ b/src/calibre/gui2/dialogs/exim.py @@ -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: diff --git a/src/calibre/gui2/dialogs/match_books.py b/src/calibre/gui2/dialogs/match_books.py index 395f5da753..7801c7f931 100644 --- a/src/calibre/gui2/dialogs/match_books.py +++ b/src/calibre/gui2/dialogs/match_books.py @@ -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): diff --git a/src/calibre/gui2/dialogs/message_box.py b/src/calibre/gui2/dialogs/message_box.py index 0ba49cbe64..36ef547960 100644 --- a/src/calibre/gui2/dialogs/message_box.py +++ b/src/calibre/gui2/dialogs/message_box.py @@ -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('
%s' % 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('
') 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): diff --git a/src/calibre/gui2/dialogs/metadata_bulk.py b/src/calibre/gui2/dialogs/metadata_bulk.py index 3e5a01fbdf..1462a6f799 100644 --- a/src/calibre/gui2/dialogs/metadata_bulk.py +++ b/src/calibre/gui2/dialogs/metadata_bulk.py @@ -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') diff --git a/src/calibre/gui2/dialogs/opml.py b/src/calibre/gui2/dialogs/opml.py index ad384d2bf1..ccb810c760 100644 --- a/src/calibre/gui2/dialogs/opml.py +++ b/src/calibre/gui2/dialogs/opml.py @@ -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) diff --git a/src/calibre/gui2/dialogs/password.py b/src/calibre/gui2/dialogs/password.py index 585a00da63..91faf12c64 100644 --- a/src/calibre/gui2/dialogs/password.py +++ b/src/calibre/gui2/dialogs/password.py @@ -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()) diff --git a/src/calibre/gui2/dialogs/plugin_updater.py b/src/calibre/gui2/dialogs/plugin_updater.py index a22db89fab..f31c129329 100644 --- a/src/calibre/gui2/dialogs/plugin_updater.py +++ b/src/calibre/gui2/dialogs/plugin_updater.py @@ -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): diff --git a/src/calibre/gui2/dialogs/progress.py b/src/calibre/gui2/dialogs/progress.py index 35c5dfefbf..f466dba55b 100644 --- a/src/calibre/gui2/dialogs/progress.py +++ b/src/calibre/gui2/dialogs/progress.py @@ -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()) diff --git a/src/calibre/gui2/dialogs/quickview.py b/src/calibre/gui2/dialogs/quickview.py index 0e4612dfe9..97feb46dc5 100644 --- a/src/calibre/gui2/dialogs/quickview.py +++ b/src/calibre/gui2/dialogs/quickview.py @@ -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) diff --git a/src/calibre/gui2/dialogs/restore_library.py b/src/calibre/gui2/dialogs/restore_library.py index 52a6d8ecd9..71fde86e16 100644 --- a/src/calibre/gui2/dialogs/restore_library.py +++ b/src/calibre/gui2/dialogs/restore_library.py @@ -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) diff --git a/src/calibre/gui2/dialogs/saved_search_editor.py b/src/calibre/gui2/dialogs/saved_search_editor.py index d1b6810e12..f93fa5573c 100644 --- a/src/calibre/gui2/dialogs/saved_search_editor.py +++ b/src/calibre/gui2/dialogs/saved_search_editor.py @@ -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]) diff --git a/src/calibre/gui2/dialogs/scheduler.py b/src/calibre/gui2/dialogs/scheduler.py index 4dbc529e97..6cf993f60e 100644 --- a/src/calibre/gui2/dialogs/scheduler.py +++ b/src/calibre/gui2/dialogs/scheduler.py @@ -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() diff --git a/src/calibre/gui2/dialogs/search.py b/src/calibre/gui2/dialogs/search.py index a7a17bf715..58df42f8d5 100644 --- a/src/calibre/gui2/dialogs/search.py +++ b/src/calibre/gui2/dialogs/search.py @@ -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(_( "
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', '')) diff --git a/src/calibre/gui2/dialogs/select_formats.py b/src/calibre/gui2/dialogs/select_formats.py index 14b68282d6..d11ec3f6b1 100644 --- a/src/calibre/gui2/dialogs/select_formats.py +++ b/src/calibre/gui2/dialogs/select_formats.py @@ -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) diff --git a/src/calibre/gui2/dialogs/smartdevice.py b/src/calibre/gui2/dialogs/smartdevice.py index b79e899053..b28c467e5d 100644 --- a/src/calibre/gui2/dialogs/smartdevice.py +++ b/src/calibre/gui2/dialogs/smartdevice.py @@ -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()) diff --git a/src/calibre/gui2/dialogs/tag_categories.py b/src/calibre/gui2/dialogs/tag_categories.py index 3d7c861b27..4e209d1bd8 100644 --- a/src/calibre/gui2/dialogs/tag_categories.py +++ b/src/calibre/gui2/dialogs/tag_categories.py @@ -54,7 +54,7 @@ class TagCategories(QDialog, Ui_TagCategories): # 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.db = db @@ -169,7 +169,7 @@ class TagCategories(QDialog, Ui_TagCategories): def make_list_widget(self, item): n = item.name if item.exists else item.name + _(' (not on any book)') w = QListWidgetItem(item.icon, n) - w.setData(Qt.UserRole, item.index) + w.setData(Qt.ItemDataRole.UserRole, item.index) w.setToolTip(_('Category lookup name: ') + item.label) return w @@ -197,7 +197,7 @@ class TagCategories(QDialog, Ui_TagCategories): return nodes = self.available_items_box.selectedItems() if node is None else [node] for node in nodes: - index = self.all_items[node.data(Qt.UserRole)].index + index = self.all_items[node.data(Qt.ItemDataRole.UserRole)].index if index not in self.applied_items: self.applied_items.append(index) self.applied_items.sort(key=lambda x:sort_key(self.all_items[x].name)) @@ -209,7 +209,7 @@ class TagCategories(QDialog, Ui_TagCategories): def unapply_tags(self, node=None): nodes = self.applied_items_box.selectedItems() if node is None else [node] for node in nodes: - index = self.all_items[node.data(Qt.UserRole)].index + index = self.all_items[node.data(Qt.ItemDataRole.UserRole)].index self.applied_items.remove(index) self.display_filtered_categories(None) diff --git a/src/calibre/gui2/dialogs/tag_editor.py b/src/calibre/gui2/dialogs/tag_editor.py index f193775864..c2af157473 100644 --- a/src/calibre/gui2/dialogs/tag_editor.py +++ b/src/calibre/gui2/dialogs/tag_editor.py @@ -71,8 +71,8 @@ class TagEditor(QDialog, Ui_TagEditor): tags = [] if self.is_names: - self.applied_tags.setDragDropMode(QAbstractItemView.InternalMove) - self.applied_tags.setSelectionMode(QAbstractItemView.ExtendedSelection) + self.applied_tags.setDragDropMode(QAbstractItemView.DragDropMode.InternalMove) + self.applied_tags.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection) if key: all_tags = [tag for tag in self.db.all_custom(label=key)] @@ -215,7 +215,7 @@ class TagEditor(QDialog, Ui_TagEditor): tag = tag.strip() if not tag: continue - for item in self.available_tags.findItems(tag, Qt.MatchFixedString): + for item in self.available_tags.findItems(tag, Qt.MatchFlag.MatchFixedString): self.available_tags.takeItem(self.available_tags.row(item)) if tag not in tags_in_box: tags_in_box.append(tag) diff --git a/src/calibre/gui2/dialogs/tag_list_editor.py b/src/calibre/gui2/dialogs/tag_list_editor.py index c6b8ab7641..5eb4d1627f 100644 --- a/src/calibre/gui2/dialogs/tag_list_editor.py +++ b/src/calibre/gui2/dialogs/tag_list_editor.py @@ -34,11 +34,11 @@ class NameTableWidgetItem(QTableWidgetItem): self.sort_key = sort_key def data(self, role): - if role == Qt.DisplayRole: + if role == Qt.ItemDataRole.DisplayRole: if self.is_deleted: return '' return self.current_value - elif role == Qt.EditRole: + elif role == Qt.ItemDataRole.EditRole: return self.current_value else: return QTableWidgetItem.data(self, role) @@ -52,7 +52,7 @@ class NameTableWidgetItem(QTableWidgetItem): self.is_deleted = to_what def setData(self, role, data): - if role == Qt.EditRole: + if role == Qt.ItemDataRole.EditRole: self.current_value = data QTableWidgetItem.setData(self, role, data) @@ -144,7 +144,7 @@ class TagListEditor(QDialog, Ui_TagListEditor): QDialog.__init__(self, window) Ui_TagListEditor.__init__(self) self.setupUi(self) - self.verticalLayout_2.setAlignment(Qt.AlignCenter) + self.verticalLayout_2.setAlignment(Qt.AlignmentFlag.AlignCenter) self.search_box.setMinimumContentsLength(25) # Put the category name into the title bar @@ -154,7 +154,7 @@ class TagListEditor(QDialog, Ui_TagListEditor): self.setWindowTitle(t + ' (' + cat_name + ')') # 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) # Get saved geometry info @@ -204,8 +204,8 @@ class TagListEditor(QDialog, Ui_TagListEditor): self.table.itemDoubleClicked.connect(self._rename_tag) self.table.itemChanged.connect(self.finish_editing) - 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.search_box.initialize('tag_list_search_box_' + cat_name) @@ -218,17 +218,17 @@ class TagListEditor(QDialog, Ui_TagListEditor): self.search_button.setDefault(True) l = QLabel(self.table) self.not_found_label = l - 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, 0) 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.filter_box.initialize('tag_list_filter_box_' + cat_name) le = self.filter_box.lineEdit() @@ -260,7 +260,7 @@ class TagListEditor(QDialog, Ui_TagListEditor): self.search_item_row = -1 self.fill_in_table(None, tag_to_match, ttm_is_first_letter) - self.table.setContextMenuPolicy(Qt.CustomContextMenu) + self.table.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.table.customContextMenuRequested.connect(self.show_context_menu) def show_context_menu(self, point): @@ -283,7 +283,7 @@ class TagListEditor(QDialog, Ui_TagListEditor): ca.triggered.connect(self.undo_edit) ca.setEnabled(False) for item in self.table.selectedItems(): - if (item.text() != self.original_names[int(item.data(Qt.UserRole))] or item.is_deleted): + if (item.text() != self.original_names[int(item.data(Qt.ItemDataRole.UserRole))] or item.is_deleted): ca.setEnabled(True) break ca = m.addAction(_('Edit')) @@ -407,7 +407,7 @@ class TagListEditor(QDialog, Ui_TagListEditor): item = NameTableWidgetItem(self.sorter) item.set_is_deleted(self.all_tags[tag]['is_deleted']) _id = self.all_tags[tag]['key'] - item.setData(Qt.UserRole, _id) + item.setData(Qt.ItemDataRole.UserRole, _id) item.set_initial_text(tag) if _id in self.to_rename: item.setText(self.to_rename[_id]) @@ -419,7 +419,7 @@ class TagListEditor(QDialog, Ui_TagListEditor): '
' + _("This is not one of this column's permitted values ({0})" ).format(', '.join(self.enum_permitted_values)) + '
') - item.setFlags(item.flags() | Qt.ItemIsSelectable | Qt.ItemIsEditable) + item.setFlags(item.flags() | Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEditable) self.table.setItem(row, 0, item) if select_item is None: if ttm_is_first_letter: @@ -429,13 +429,13 @@ class TagListEditor(QDialog, Ui_TagListEditor): select_item = item item = CountTableWidgetItem(self.all_tags[tag]['count']) # only the name column can be selected - item.setFlags(item.flags() & ~(Qt.ItemIsSelectable|Qt.ItemIsEditable)) + item.setFlags(item.flags() & ~(Qt.ItemFlag.ItemIsSelectable|Qt.ItemFlag.ItemIsEditable)) self.table.setItem(row, 1, item) item = QTableWidgetItem() - item.setFlags(item.flags() & ~(Qt.ItemIsSelectable|Qt.ItemIsEditable)) + item.setFlags(item.flags() & ~(Qt.ItemFlag.ItemIsSelectable|Qt.ItemFlag.ItemIsEditable)) if _id in self.to_rename or _id in self.to_delete: - item.setData(Qt.DisplayRole, tag) + item.setData(Qt.ItemDataRole.DisplayRole, tag) self.table.setItem(row, 2, item) if self.last_sorted_by == 'name': @@ -528,11 +528,11 @@ class TagListEditor(QDialog, Ui_TagListEditor): items = self.table.selectedItems() self.table.blockSignals(True) for item in items: - id_ = int(item.data(Qt.UserRole)) + id_ = int(item.data(Qt.ItemDataRole.UserRole)) self.to_rename[id_] = new_text orig = self.table.item(item.row(), 2) item.setText(new_text) - orig.setData(Qt.DisplayRole, item.initial_text()) + orig.setData(Qt.ItemDataRole.DisplayRole, item.initial_text()) self.table.blockSignals(False) def undo_edit(self): @@ -552,9 +552,9 @@ class TagListEditor(QDialog, Ui_TagListEditor): item = self.table.item(row, 0) item.setText(item.initial_text()) item.set_is_deleted(False) - self.to_delete.discard(int(item.data(Qt.UserRole))) - self.to_rename.pop(int(item.data(Qt.UserRole)), None) - self.table.item(row, 2).setData(Qt.DisplayRole, '') + self.to_delete.discard(int(item.data(Qt.ItemDataRole.UserRole))) + self.to_rename.pop(int(item.data(Qt.ItemDataRole.UserRole)), None) + self.table.item(row, 2).setData(Qt.ItemDataRole.DisplayRole, '') self.table.blockSignals(False) def rename_tag(self): @@ -577,9 +577,9 @@ class TagListEditor(QDialog, Ui_TagListEditor): # undelete any deleted items if col_zero_item.is_deleted: col_zero_item.set_is_deleted(False) - self.to_delete.discard(int(col_zero_item.data(Qt.UserRole))) + self.to_delete.discard(int(col_zero_item.data(Qt.ItemDataRole.UserRole))) orig = self.table.item(col_zero_item.row(), 2) - orig.setData(Qt.DisplayRole, '') + orig.setData(Qt.ItemDataRole.DisplayRole, '') self.table.blockSignals(False) self.table.editItem(item) @@ -609,11 +609,11 @@ class TagListEditor(QDialog, Ui_TagListEditor): row = self.table.row(deletes[0]) self.table.blockSignals(True) for item in deletes: - id_ = int(item.data(Qt.UserRole)) + id_ = int(item.data(Qt.ItemDataRole.UserRole)) self.to_delete.add(id_) item.set_is_deleted(True) orig = self.table.item(item.row(), 2) - orig.setData(Qt.DisplayRole, item.initial_text()) + orig.setData(Qt.ItemDataRole.DisplayRole, item.initial_text()) self.table.blockSignals(False) if row >= self.table.rowCount(): row = self.table.rowCount() - 1 diff --git a/src/calibre/gui2/dialogs/tag_list_editor_table_widget.py b/src/calibre/gui2/dialogs/tag_list_editor_table_widget.py index 5bbcb41112..f894dfa7e6 100644 --- a/src/calibre/gui2/dialogs/tag_list_editor_table_widget.py +++ b/src/calibre/gui2/dialogs/tag_list_editor_table_widget.py @@ -14,7 +14,7 @@ class TleTableWidget(QTableWidget): QTableWidget.__init__(self, parent=parent) def keyPressEvent(self, event): - if event.key() == Qt.Key_Delete: + if event.key() == Qt.Key.Key_Delete: self.delete_pressed.emit() event.accept() return diff --git a/src/calibre/gui2/dialogs/template_dialog.py b/src/calibre/gui2/dialogs/template_dialog.py index 239a986a6e..f91c71bbe0 100644 --- a/src/calibre/gui2/dialogs/template_dialog.py +++ b/src/calibre/gui2/dialogs/template_dialog.py @@ -107,7 +107,7 @@ class TemplateHighlighter(QSyntaxHighlighter): if col: format.setForeground(QColor(col)) if Config["%sfontbold" % name]: - format.setFontWeight(QFont.Bold) + format.setFontWeight(QFont.Weight.Bold) format.setFontItalic(Config["%sfontitalic" % name]) self.Formats[name] = format @@ -166,7 +166,7 @@ class TemplateHighlighter(QSyntaxHighlighter): i += 1 def rehighlight(self): - QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) + QApplication.setOverrideCursor(QCursor(Qt.CursorShape.WaitCursor)) QSyntaxHighlighter.rehighlight(self) QApplication.restoreOverrideCursor() @@ -308,7 +308,7 @@ class TemplateDialog(QDialog, Ui_TemplateDialog): # 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.last_text = '' @@ -327,8 +327,8 @@ class TemplateDialog(QDialog, Ui_TemplateDialog): self.textbox.clear() else: self.textbox.setPlainText(text) - 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.color_copy_button.clicked.connect(self.color_to_clipboard) self.filename_button.clicked.connect(self.filename_button_clicked) self.icon_copy_button.clicked.connect(self.icon_to_clipboard) @@ -498,7 +498,7 @@ class EmbeddedTemplateDialog(TemplateDialog): TemplateDialog.__init__(self, parent, _('A General Program Mode Template'), text_is_placeholder=True, dialog_is_st_editor=True) self.setParent(parent) - self.setWindowFlags(Qt.Widget) + self.setWindowFlags(Qt.WindowType.Widget) if __name__ == '__main__': diff --git a/src/calibre/gui2/dialogs/trim_image.py b/src/calibre/gui2/dialogs/trim_image.py index 576faf4ea8..ae891985f1 100644 --- a/src/calibre/gui2/dialogs/trim_image.py +++ b/src/calibre/gui2/dialogs/trim_image.py @@ -25,7 +25,7 @@ class TrimImage(QDialog): self.bar = b = QToolBar(self) l.addWidget(b) - b.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) + b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) b.setIconSize(QSize(32, 32)) self.msg = la = QLabel('\xa0' + _( @@ -36,12 +36,12 @@ class TrimImage(QDialog): c.image_changed.connect(self.image_changed) c.load_image(img_data) self.undo_action = u = c.undo_action - u.setShortcut(QKeySequence(QKeySequence.Undo)) + u.setShortcut(QKeySequence(QKeySequence.StandardKey.Undo)) self.redo_action = r = c.redo_action - r.setShortcut(QKeySequence(QKeySequence.Redo)) + r.setShortcut(QKeySequence(QKeySequence.StandardKey.Redo)) self.trim_action = ac = self.bar.addAction(QIcon(I('trim.png')), _('&Trim'), self.do_trim) ac.setShortcut(QKeySequence('Ctrl+T')) - ac.setToolTip('%s [%s]' % (_('Trim image by removing borders outside the selected region'), ac.shortcut().toString(QKeySequence.NativeText))) + ac.setToolTip('%s [%s]' % (_('Trim image by removing borders outside the selected region'), ac.shortcut().toString(QKeySequence.SequenceFormat.NativeText))) ac.setEnabled(False) c.selection_state_changed.connect(self.selection_changed) l.addWidget(c) @@ -54,7 +54,7 @@ class TrimImage(QDialog): self.bar.addSeparator() self.bar.addWidget(self.sz) - 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) diff --git a/src/calibre/gui2/dnd.py b/src/calibre/gui2/dnd.py index 6cf3e0fdee..ae7178cb15 100644 --- a/src/calibre/gui2/dnd.py +++ b/src/calibre/gui2/dnd.py @@ -74,7 +74,7 @@ class DownloadDialog(QDialog): # {{{ self.pb.setMinimum(0) self.pb.setMaximum(0) self.l.addWidget(self.pb) - self.bb = QDialogButtonBox(QDialogButtonBox.Cancel, Qt.Horizontal, self) + self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel, Qt.Orientation.Horizontal, self) self.l.addWidget(self.bb) self.bb.rejected.connect(self.reject) sz = self.sizeHint() diff --git a/src/calibre/gui2/email.py b/src/calibre/gui2/email.py index d6dacc6a61..42b00235dd 100644 --- a/src/calibre/gui2/email.py +++ b/src/calibre/gui2/email.py @@ -223,7 +223,7 @@ class SelectRecipients(QDialog): # {{{ b.clicked.connect(self.add_recipient) l.addWidget(b, l.rowCount(), 0, 1, -1) - self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel) + self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel) l.addWidget(bb, l.rowCount(), 0, 1, -1) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) @@ -261,9 +261,9 @@ class SelectRecipients(QDialog): # {{{ def create_item(self, alias, key, checked=False): i = QListWidgetItem(alias, self.recipients) - i.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable) - i.setCheckState(Qt.Checked if checked else Qt.Unchecked) - i.setData(Qt.UserRole, key) + i.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsUserCheckable) + i.setCheckState(Qt.CheckState.Checked if checked else Qt.CheckState.Unchecked) + i.setData(Qt.ItemDataRole.UserRole, key) self.items.append(i) def init_list(self): @@ -287,8 +287,8 @@ class SelectRecipients(QDialog): # {{{ opts = email_config().parse() ans = [] for i in self.items: - if i.checkState() == Qt.Checked: - to = unicode_type(i.data(Qt.UserRole) or '') + if i.checkState() == Qt.CheckState.Checked: + to = unicode_type(i.data(Qt.ItemDataRole.UserRole) or '') fmts = tuple(x.strip().upper() for x in (opts.accounts[to][0] or '').split(',')) subject = opts.subjects.get(to, '') ans.append((to, fmts, subject)) diff --git a/src/calibre/gui2/font_family_chooser.py b/src/calibre/gui2/font_family_chooser.py index f92d998ad3..3a8f677546 100644 --- a/src/calibre/gui2/font_family_chooser.py +++ b/src/calibre/gui2/font_family_chooser.py @@ -54,34 +54,34 @@ def writing_system_for_font(font): # this just confuses the algorithm below. Vietnamese is Latin with lots of # special chars try: - systems.remove(QFontDatabase.Vietnamese) + systems.remove(QFontDatabase.WritingSystem.Vietnamese) except ValueError: pass - system = QFontDatabase.Any + system = QFontDatabase.WritingSystem.Any - if (QFontDatabase.Latin not in systems): + if (QFontDatabase.WritingSystem.Latin not in systems): has_latin = False # we need to show something if systems: system = systems[-1] else: - systems.remove(QFontDatabase.Latin) + systems.remove(QFontDatabase.WritingSystem.Latin) if not systems: return system, has_latin - if (len(systems) == 1 and systems[0] > QFontDatabase.Cyrillic): + if (len(systems) == 1 and systems[0] > QFontDatabase.WritingSystem.Cyrillic): return systems[0], has_latin if (len(systems) <= 2 and - systems[-1] > QFontDatabase.Armenian and - systems[-1] < QFontDatabase.Vietnamese): + systems[-1] > QFontDatabase.WritingSystem.Armenian and + systems[-1] < QFontDatabase.WritingSystem.Vietnamese): return systems[-1], has_latin if (len(systems) <= 5 and - systems[-1] >= QFontDatabase.SimplifiedChinese and - systems[-1] <= QFontDatabase.Korean): + systems[-1] >= QFontDatabase.WritingSystem.SimplifiedChinese and + systems[-1] <= QFontDatabase.WritingSystem.Korean): system = systems[-1] return system, has_latin @@ -96,7 +96,7 @@ class FontFamilyDelegate(QStyledItemDelegate): return QSize(300, 50) def do_size_hint(self, option, index): - text = index.data(Qt.DisplayRole) or '' + text = index.data(Qt.ItemDataRole.DisplayRole) or '' font = QFont(option.font) font.setPointSize(QFontInfo(font).pointSize() * 1.5) m = QFontMetrics(font) @@ -112,7 +112,7 @@ class FontFamilyDelegate(QStyledItemDelegate): painter.restore() def do_paint(self, painter, option, index): - text = unicode_type(index.data(Qt.DisplayRole) or '') + text = unicode_type(index.data(Qt.ItemDataRole.DisplayRole) or '') font = QFont(option.font) font.setPointSize(QFontInfo(font).pointSize() * 1.5) font2 = QFont(font) @@ -124,26 +124,26 @@ class FontFamilyDelegate(QStyledItemDelegate): r = option.rect - if option.state & QStyle.State_Selected: + if option.state & QStyle.StateFlag.State_Selected: painter.setPen(QPen(option.palette.highlightedText(), 0)) - if (option.direction == Qt.RightToLeft): + if (option.direction == Qt.LayoutDirection.RightToLeft): r.setRight(r.right() - 4) else: r.setLeft(r.left() + 4) painter.setFont(font) - painter.drawText(r, Qt.AlignVCenter|Qt.AlignLeading|Qt.TextSingleLine, text) + painter.drawText(r, Qt.AlignmentFlag.AlignVCenter|Qt.AlignmentFlag.AlignLeading|Qt.TextFlag.TextSingleLine, text) - if (system != QFontDatabase.Any): + if (system != QFontDatabase.WritingSystem.Any): w = painter.fontMetrics().width(text + " ") painter.setFont(font2) sample = QFontDatabase().writingSystemSample(system) - if (option.direction == Qt.RightToLeft): + if (option.direction == Qt.LayoutDirection.RightToLeft): r.setRight(r.right() - w) else: r.setLeft(r.left() + w) - painter.drawText(r, Qt.AlignVCenter|Qt.AlignLeading|Qt.TextSingleLine, sample) + painter.drawText(r, Qt.AlignmentFlag.AlignVCenter|Qt.AlignmentFlag.AlignLeading|Qt.TextFlag.TextSingleLine, sample) class Typefaces(QLabel): @@ -217,11 +217,11 @@ class FontFamilyDialog(QDialog): if icu_lower(val) == icu_lower(current_family): self.view.setCurrentIndex(self.m.index(i)) break - self.view.doubleClicked.connect(self.accept, type=Qt.QueuedConnection) + self.view.doubleClicked.connect(self.accept, type=Qt.ConnectionType.QueuedConnection) self.view.changed.connect(self.current_changed, - type=Qt.QueuedConnection) + type=Qt.ConnectionType.QueuedConnection) self.faces = Typefaces(self) - 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.add_fonts_button = afb = self.bb.addButton(_('Add &fonts'), @@ -248,7 +248,7 @@ class FontFamilyDialog(QDialog): l.addWidget(self.view, 2, 0, 1, 3) l.addWidget(self.faces, 1, 3, 2, 1) l.addWidget(self.bb, 3, 0, 1, 4) - l.setAlignment(self.faces, Qt.AlignTop) + l.setAlignment(self.faces, Qt.AlignmentFlag.AlignTop) self.resize(800, 600) @@ -256,7 +256,7 @@ class FontFamilyDialog(QDialog): self.view.setCurrentIndex(self.m.index(i)) def keyPressEvent(self, e): - if e.key() == Qt.Key_Return: + if e.key() == Qt.Key.Key_Return: return return QDialog.keyPressEvent(self, e) @@ -335,7 +335,7 @@ class FontFamilyChooser(QWidget): self.setLayout(l) self.button = QPushButton(self) self.button.setIcon(QIcon(I('font.png'))) - self.button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) + self.button.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) l.addWidget(self.button) self.default_text = _('Choose &font family') self.font_family = None diff --git a/src/calibre/gui2/gestures.py b/src/calibre/gui2/gestures.py index b25600344b..a4aa88eb24 100644 --- a/src/calibre/gui2/gestures.py +++ b/src/calibre/gui2/gestures.py @@ -135,15 +135,15 @@ class State(QObject): return -def send_click(view, pos, button=Qt.LeftButton, double_click=False): +def send_click(view, pos, button=Qt.MouseButton.LeftButton, double_click=False): mods = QApplication.keyboardModifiers() if double_click: - ev = QMouseEvent(QEvent.MouseButtonDblClick, pos, button, button, mods) + ev = QMouseEvent(QEvent.Type.MouseButtonDblClick, pos, button, button, mods) QApplication.postEvent(view.viewport(), ev) return - ev = QMouseEvent(QEvent.MouseButtonPress, pos, button, button, mods) + ev = QMouseEvent(QEvent.Type.MouseButtonPress, pos, button, button, mods) QApplication.postEvent(view.viewport(), ev) - ev = QMouseEvent(QEvent.MouseButtonRelease, pos, button, button, mods) + ev = QMouseEvent(QEvent.Type.MouseButtonRelease, pos, button, button, mods) QApplication.postEvent(view.viewport(), ev) @@ -152,14 +152,14 @@ class GestureManager(QObject): def __init__(self, view): QObject.__init__(self, view) if touch_supported: - view.viewport().setAttribute(Qt.WA_AcceptTouchEvents) + view.viewport().setAttribute(Qt.WidgetAttribute.WA_AcceptTouchEvents) self.state = State() - self.state.tapped.connect(self.handle_tap, type=Qt.QueuedConnection) # has to be queued otherwise QApplication.keyboardModifiers() does not work + self.state.tapped.connect(self.handle_tap, type=Qt.ConnectionType.QueuedConnection) # has to be queued otherwise QApplication.keyboardModifiers() does not work self.state.flicking.connect(self.handle_flicking) connect_lambda(self.state.tap_hold_started, self, lambda self, tp: self.handle_tap_hold('start', tp)) connect_lambda(self.state.tap_hold_updated, self, lambda self, tp: self.handle_tap_hold('update', tp)) connect_lambda(self.state.tap_hold_finished, self, lambda self, tp: self.handle_tap_hold('end', tp)) - self.evmap = {QEvent.TouchBegin: 'start', QEvent.TouchUpdate: 'update', QEvent.TouchEnd: 'end'} + self.evmap = {QEvent.Type.TouchBegin: 'start', QEvent.Type.TouchUpdate: 'update', QEvent.Type.TouchEnd: 'end'} self.last_tap_at = 0 if touch_supported: self.scroller = QScroller.scroller(view.viewport()) @@ -168,18 +168,18 @@ class GestureManager(QObject): if not touch_supported: return etype = ev.type() - if etype in (QEvent.MouseButtonPress, QEvent.MouseMove, QEvent.MouseButtonRelease, QEvent.MouseButtonDblClick): - if ev.source() in (Qt.MouseEventSynthesizedBySystem, Qt.MouseEventSynthesizedByQt): + if etype in (QEvent.Type.MouseButtonPress, QEvent.Type.MouseMove, QEvent.Type.MouseButtonRelease, QEvent.Type.MouseButtonDblClick): + if ev.source() in (Qt.MouseEventSource.MouseEventSynthesizedBySystem, Qt.MouseEventSource.MouseEventSynthesizedByQt): # swallow fake mouse events generated from touch events ev.ignore() return False self.scroller.stop() return - if etype == QEvent.Wheel and self.scroller.state() != QScroller.Inactive: + if etype == QEvent.Type.Wheel and self.scroller.state() != QScroller.State.Inactive: ev.ignore() return False boundary = self.evmap.get(etype, None) - if boundary is None or ev.device().type() != QTouchDevice.TouchScreen: + if boundary is None or ev.device().type() != QTouchDevice.DeviceType.TouchScreen: return self.state.update(ev, boundary=boundary) ev.accept() @@ -193,9 +193,9 @@ class GestureManager(QObject): def handle_flicking(self, touch_point, is_end): if is_end: - it = QScroller.InputRelease + it = QScroller.Input.InputRelease else: - it = QScroller.InputPress if touch_point.extra_data is None else QScroller.InputMove + it = QScroller.Input.InputPress if touch_point.extra_data is None else QScroller.Input.InputMove touch_point.extra_data = True self.scroller.handleInput(it, touch_point.current_position, int(touch_point.last_update_time * 1000)) @@ -211,4 +211,4 @@ class GestureManager(QObject): def handle_tap_hold(self, action, tp): self.scroller.stop() if action == 'end': - send_click(self.parent(), tp.start_position, button=Qt.RightButton) + send_click(self.parent(), tp.start_position, button=Qt.MouseButton.RightButton) diff --git a/src/calibre/gui2/icon_theme.py b/src/calibre/gui2/icon_theme.py index 96f55eca14..c5ff372a9e 100644 --- a/src/calibre/gui2/icon_theme.py +++ b/src/calibre/gui2/icon_theme.py @@ -183,7 +183,7 @@ def create_cover(report, icons=(), cols=5, size=120, padding=16): with lopen(ipath, 'rb') as f: img = image_from_data(f.read()) scaled, nwidth, nheight = fit_image(img.width(), img.height(), size, size) - img = img.scaled(nwidth, nheight, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) + img = img.scaled(nwidth, nheight, Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation) dx = (size - nwidth) // 2 canvas.compose(img, x + dx, y) return canvas.export() @@ -312,7 +312,7 @@ class Compress(QProgressDialog): self.setWindowTitle(self.labelText()) self.setWindowIcon(QIcon(I('lt.png'))) self.setMinimumDuration(0) - self.update_signal.connect(self.do_update, type=Qt.QueuedConnection) + self.update_signal.connect(self.do_update, type=Qt.ConnectionType.QueuedConnection) self.raw = self.prefix = None self.abort = Event() self.canceled.connect(self.abort.set) @@ -522,15 +522,15 @@ class Delegate(QStyledItemDelegate): def paint(self, painter, option, index): QStyledItemDelegate.paint(self, painter, option, empty_index) - theme = index.data(Qt.UserRole) + theme = index.data(Qt.ItemDataRole.UserRole) if not theme: return painter.save() - pixmap = index.data(Qt.DecorationRole) + pixmap = index.data(Qt.ItemDataRole.DecorationRole) if pixmap and not pixmap.isNull(): rect = option.rect.adjusted(0, self.SPACING, COVER_SIZE[0] - option.rect.width(), - self.SPACING) painter.drawPixmap(rect, pixmap) - if option.state & QStyle.State_Selected: + if option.state & QStyle.StateFlag.State_Selected: painter.setPen(QPen(QApplication.instance().palette().highlightedText().color())) bottom = option.rect.bottom() - 2 painter.drawLine(0, bottom, option.rect.right(), bottom) @@ -559,9 +559,9 @@ class DownloadProgress(ProgressDialog): def __init__(self, parent, size): ProgressDialog.__init__(self, _('Downloading icons...'), _( 'Downloading icons, please wait...'), max=size, parent=parent, icon='download_metadata.png') - self.ds.connect(self.bar.setValue, type=Qt.QueuedConnection) - self.acc.connect(self.accept, type=Qt.QueuedConnection) - self.rej.connect(self.reject, type=Qt.QueuedConnection) + self.ds.connect(self.bar.setValue, type=Qt.ConnectionType.QueuedConnection) + self.acc.connect(self.accept, type=Qt.ConnectionType.QueuedConnection) + self.rej.connect(self.reject, type=Qt.ConnectionType.QueuedConnection) def downloaded(self, byte_count): self.ds.emit(byte_count) @@ -586,8 +586,8 @@ class ChooseTheme(Dialog): Dialog.__init__(self, _('Choose an icon theme'), 'choose-icon-theme-dialog', parent) self.finished.connect(self.on_finish) self.dialog_closed = False - self.themes_downloaded.connect(self.show_themes, type=Qt.QueuedConnection) - self.cover_downloaded.connect(self.set_cover, type=Qt.QueuedConnection) + self.themes_downloaded.connect(self.show_themes, type=Qt.ConnectionType.QueuedConnection) + self.cover_downloaded.connect(self.set_cover, type=Qt.ConnectionType.QueuedConnection) self.keep_downloading = True self.commit_changes = None self.new_theme_title = None @@ -610,9 +610,9 @@ class ChooseTheme(Dialog): b.setIcon(QIcon(I('view-refresh.png'))) self.c = c = QWidget(self) self.c.v = v = QVBoxLayout(self.c) - v.addStretch(), v.addWidget(pi, 0, Qt.AlignCenter) + v.addStretch(), v.addWidget(pi, 0, Qt.AlignmentFlag.AlignCenter) self.wait_msg = m = QLabel(self) - v.addWidget(m, 0, Qt.AlignCenter), v.addStretch() + v.addWidget(m, 0, Qt.AlignmentFlag.AlignCenter), v.addStretch() f = m.font() f.setBold(True), f.setPointSize(28), m.setFont(f) self.start_spinner() @@ -678,9 +678,9 @@ class ChooseTheme(Dialog): self.theme_list.clear() for theme in self.themes: i = QListWidgetItem(theme.get('title', '') + ' %s %s' % (theme.get('number'), self.usage.get(theme.get('name'))), self.theme_list) - i.setData(Qt.UserRole, theme) + i.setData(Qt.ItemDataRole.UserRole, theme) if 'cover-pixmap' in theme: - i.setData(Qt.DecorationRole, theme['cover-pixmap']) + i.setData(Qt.ItemDataRole.DecorationRole, theme['cover-pixmap']) def get_themes(self): @@ -725,7 +725,7 @@ class ChooseTheme(Dialog): def item_from_name(self, name): for item in self: - if item.data(Qt.UserRole)['name'] == name: + if item.data(Qt.ItemDataRole.UserRole)['name'] == name: return item def set_cover(self, theme, cdata): @@ -739,7 +739,7 @@ class ChooseTheme(Dialog): p.setDevicePixelRatio(dpr) item = self.item_from_name(theme['name']) if item is not None: - item.setData(Qt.DecorationRole, p) + item.setData(Qt.ItemDataRole.DecorationRole, p) def restore_defaults(self): if self.current_theme is not None: @@ -754,7 +754,7 @@ class ChooseTheme(Dialog): if self.theme_list.currentRow() < 0: return error_dialog(self, _('No theme selected'), _( 'You must first select an icon theme'), show=True) - theme = self.theme_list.currentItem().data(Qt.UserRole) + theme = self.theme_list.currentItem().data(Qt.ItemDataRole.UserRole) url = BASE_URL + theme['icons-url'] size = theme['compressed-size'] theme = {k:theme.get(k, '') for k in 'name title version'.split()} diff --git a/src/calibre/gui2/image_popup.py b/src/calibre/gui2/image_popup.py index 4acc4f26ab..972c6be9cf 100644 --- a/src/calibre/gui2/image_popup.py +++ b/src/calibre/gui2/image_popup.py @@ -23,8 +23,8 @@ def render_svg(widget, path): sz = rend.defaultSize() h = (max_available_height() - 50) w = int(h * sz.height() / float(sz.width())) - pd = QImage(w * dpr, h * dpr, QImage.Format_RGB32) - pd.fill(Qt.white) + pd = QImage(w * dpr, h * dpr, QImage.Format.Format_RGB32) + pd.fill(Qt.GlobalColor.white) p = QPainter(pd) rend.render(p) p.end() @@ -37,8 +37,8 @@ class ImageView(QDialog): def __init__(self, parent, current_img, current_url, geom_name='viewer_image_popup_geometry'): QDialog.__init__(self) - self.setWindowFlag(Qt.WindowMinimizeButtonHint) - self.setWindowFlag(Qt.WindowMaximizeButtonHint) + self.setWindowFlag(Qt.WindowType.WindowMinimizeButtonHint) + self.setWindowFlag(Qt.WindowType.WindowMaximizeButtonHint) dw = QApplication.instance().desktop() self.avail_geom = dw.availableGeometry(parent if parent is not None else self) self.current_img = current_img @@ -47,16 +47,16 @@ class ImageView(QDialog): self.geom_name = geom_name self.label = l = QLabel(self) - l.setBackgroundRole(QPalette.Text if QApplication.instance().is_dark_theme else QPalette.Base) - l.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) + l.setBackgroundRole(QPalette.ColorRole.Text if QApplication.instance().is_dark_theme else QPalette.ColorRole.Base) + l.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Ignored) l.setScaledContents(True) self.scrollarea = sa = QScrollArea() - sa.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) - sa.setBackgroundRole(QPalette.Dark) + sa.setAlignment(Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter) + sa.setBackgroundRole(QPalette.ColorRole.Dark) sa.setWidget(l) - self.bb = bb = QDialogButtonBox(QDialogButtonBox.Close) + self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) self.zi_button = zi = bb.addButton(_('Zoom &in'), bb.ActionRole) @@ -214,7 +214,7 @@ class ImagePopup(object): return d = ImageView(self.parent, self.current_img, self.current_url) self.dialogs.append(d) - d.finished.connect(self.cleanup, type=Qt.QueuedConnection) + d.finished.connect(self.cleanup, type=Qt.ConnectionType.QueuedConnection) d() def cleanup(self): diff --git a/src/calibre/gui2/init.py b/src/calibre/gui2/init.py index ba3a4c816f..e4c52cf970 100644 --- a/src/calibre/gui2/init.py +++ b/src/calibre/gui2/init.py @@ -45,11 +45,11 @@ class LibraryViewMixin(object): # {{{ pass def init_library_view_mixin(self, db): - self.library_view.files_dropped.connect(self.iactions['Add Books'].files_dropped, type=Qt.QueuedConnection) - self.library_view.books_dropped.connect(self.iactions['Edit Metadata'].books_dropped, type=Qt.QueuedConnection) + self.library_view.files_dropped.connect(self.iactions['Add Books'].files_dropped, type=Qt.ConnectionType.QueuedConnection) + self.library_view.books_dropped.connect(self.iactions['Edit Metadata'].books_dropped, type=Qt.ConnectionType.QueuedConnection) self.library_view.add_column_signal.connect(partial(self.iactions['Preferences'].do_config, initial_plugin=('Interface', 'Custom Columns')), - type=Qt.QueuedConnection) + type=Qt.ConnectionType.QueuedConnection) for func, args in [ ('connect_to_search_box', (self.search, self.search_done)), @@ -116,7 +116,7 @@ class LibraryViewMixin(object): # {{{ class QuickviewSplitter(QSplitter): # {{{ - def __init__(self, parent=None, orientation=Qt.Vertical, qv_widget=None): + def __init__(self, parent=None, orientation=Qt.Orientation.Vertical, qv_widget=None): QSplitter.__init__(self, parent=parent, orientation=orientation) self.splitterMoved.connect(self.splitter_moved) self.setChildrenCollapsible(False) @@ -149,11 +149,11 @@ class QuickviewSplitter(QSplitter): # {{{ class LibraryWidget(Splitter): # {{{ def __init__(self, parent): - orientation = Qt.Vertical + orientation = Qt.Orientation.Vertical if config['gui_layout'] == 'narrow': - orientation = Qt.Horizontal if is_widescreen() else Qt.Vertical - idx = 0 if orientation == Qt.Vertical else 1 - size = 300 if orientation == Qt.Vertical else 550 + orientation = Qt.Orientation.Horizontal if is_widescreen() else Qt.Orientation.Vertical + idx = 0 if orientation == Qt.Orientation.Vertical else 1 + size = 300 if orientation == Qt.Orientation.Vertical else 550 Splitter.__init__(self, 'cover_browser_splitter', _('Cover browser'), I('cover_flow.png'), orientation=orientation, parent=parent, @@ -163,7 +163,7 @@ class LibraryWidget(Splitter): # {{{ quickview_widget = QWidget() parent.quickview_splitter = QuickviewSplitter( - parent=self, orientation=Qt.Vertical, qv_widget=quickview_widget) + parent=self, orientation=Qt.Orientation.Vertical, qv_widget=quickview_widget) parent.library_view = BooksView(parent) parent.library_view.setObjectName('library_view') stack = QStackedWidget(self) @@ -196,7 +196,7 @@ class Stack(QStackedWidget): # {{{ parent=parent, side_index=0, initial_side_size=200, shortcut='Shift+Alt+T') parent.tb_splitter.state_changed.connect( - self.tb_widget.set_pane_is_visible, Qt.QueuedConnection) + self.tb_widget.set_pane_is_visible, Qt.ConnectionType.QueuedConnection) parent.tb_splitter.addWidget(self.tb_widget) parent.tb_splitter.addWidget(parent.cb_splitter) parent.tb_splitter.setCollapsible(parent.tb_splitter.other_index, False) @@ -216,7 +216,7 @@ class UpdateLabel(QLabel): # {{{ def __init__(self, *args, **kwargs): QLabel.__init__(self, *args, **kwargs) - self.setCursor(Qt.PointingHandCursor) + self.setCursor(Qt.CursorShape.PointingHandCursor) def contextMenuEvent(self, e): pass @@ -228,7 +228,7 @@ class VersionLabel(QLabel): # {{{ def __init__(self, parent): QLabel.__init__(self, parent) self.mouse_over = False - self.setCursor(Qt.PointingHandCursor) + self.setCursor(Qt.CursorShape.PointingHandCursor) self.setToolTip(_('See what\'s new in this calibre release')) def mouseReleaseEvent(self, ev): @@ -253,9 +253,9 @@ class VersionLabel(QLabel): # {{{ p = QPainter(self) tool = QStyleOption() tool.rect = self.rect() - tool.state = QStyle.State_Raised | QStyle.State_Active | QStyle.State_MouseOver + tool.state = QStyle.StateFlag.State_Raised | QStyle.StateFlag.State_Active | QStyle.StateFlag.State_MouseOver s = self.style() - s.drawPrimitive(QStyle.PE_PanelButtonTool, tool, p, self) + s.drawPrimitive(QStyle.PrimitiveElement.PE_PanelButtonTool, tool, p, self) p.end() return QLabel.paintEvent(self, ev) # }}} @@ -400,7 +400,7 @@ class VLTabs(QTabBar): # {{{ self.gui = parent self.ignore_tab_changed = False self.currentChanged.connect(self.tab_changed) - self.tabMoved.connect(self.tab_moved, type=Qt.QueuedConnection) + self.tabMoved.connect(self.tab_moved, type=Qt.ConnectionType.QueuedConnection) self.tabCloseRequested.connect(self.tab_close) self.setVisible(gprefs['show_vl_tabs']) self.next_action = a = QAction(self) @@ -569,7 +569,7 @@ class LayoutMixin(object): # {{{ self.stack = Stack(self) self.bd_splitter = Splitter('book_details_splitter', _('Book details'), I('book.png'), - orientation=Qt.Vertical, parent=self, side_index=1, + orientation=Qt.Orientation.Vertical, parent=self, side_index=1, shortcut='Shift+Alt+D') self.bd_splitter.addWidget(self.stack) self.bd_splitter.addWidget(self.book_details) @@ -580,15 +580,15 @@ class LayoutMixin(object): # {{{ else: # wide {{{ self.bd_splitter = Splitter('book_details_splitter', _('Book details'), I('book.png'), initial_side_size=200, - orientation=Qt.Horizontal, parent=self, side_index=1, + orientation=Qt.Orientation.Horizontal, parent=self, side_index=1, shortcut='Shift+Alt+D') self.stack = Stack(self) self.bd_splitter.addWidget(self.stack) self.book_details = BookDetails(True, self) self.bd_splitter.addWidget(self.book_details) self.bd_splitter.setCollapsible(self.bd_splitter.other_index, False) - self.bd_splitter.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, - QSizePolicy.Expanding)) + self.bd_splitter.setSizePolicy(QSizePolicy(QSizePolicy.Policy.Expanding, + QSizePolicy.Policy.Expanding)) self.centralwidget.layout().addWidget(self.bd_splitter) button_order = ('sb', 'tb', 'cb', 'gv', 'qv', 'bd') # }}} @@ -633,9 +633,9 @@ class LayoutMixin(object): # {{{ self.status_bar.addPermanentWidget(b) else: self.layout_button = b = QToolButton(self) - b.setAutoRaise(True), b.setCursor(Qt.PointingHandCursor) + b.setAutoRaise(True), b.setCursor(Qt.CursorShape.PointingHandCursor) b.setPopupMode(b.InstantPopup) - b.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) + b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) b.setText(_('Layout')), b.setIcon(QIcon(I('config.png'))) b.setMenu(LayoutMenu(self)) b.setToolTip(_( @@ -650,18 +650,18 @@ class LayoutMixin(object): # {{{ self.book_details.show_book_info.connect(self.iactions['Show Book Details'].show_book_info) self.book_details.files_dropped.connect(self.iactions['Add Books'].files_dropped_on_book) self.book_details.cover_changed.connect(self.bd_cover_changed, - type=Qt.QueuedConnection) + type=Qt.ConnectionType.QueuedConnection) self.book_details.open_cover_with.connect(self.bd_open_cover_with, - type=Qt.QueuedConnection) + type=Qt.ConnectionType.QueuedConnection) self.book_details.open_fmt_with.connect(self.bd_open_fmt_with, - type=Qt.QueuedConnection) + type=Qt.ConnectionType.QueuedConnection) self.book_details.edit_book.connect(self.bd_edit_book, - type=Qt.QueuedConnection) + type=Qt.ConnectionType.QueuedConnection) self.book_details.cover_removed.connect(self.bd_cover_removed, - type=Qt.QueuedConnection) + type=Qt.ConnectionType.QueuedConnection) self.book_details.remote_file_dropped.connect( self.iactions['Add Books'].remote_file_dropped_on_book, - type=Qt.QueuedConnection) + type=Qt.ConnectionType.QueuedConnection) self.book_details.open_containing_folder.connect(self.iactions['View'].view_folder_for_id) self.book_details.view_specific_format.connect(self.iactions['View'].view_format_by_id) self.book_details.search_requested.connect(self.search.set_search_string) @@ -676,7 +676,7 @@ class LayoutMixin(object): # {{{ self.book_details.set_cover_from_format.connect( self.iactions['Edit Metadata'].set_cover_from_format) self.book_details.copy_link.connect(self.bd_copy_link, - type=Qt.QueuedConnection) + type=Qt.ConnectionType.QueuedConnection) self.book_details.view_device_book.connect( self.iactions['View'].view_device_book) self.book_details.manage_category.connect(self.manage_category_triggerred) @@ -689,7 +689,7 @@ class LayoutMixin(object): # {{{ QTimer.singleShot(0, self.library_view.set_current_row) m.current_changed(self.library_view.currentIndex(), self.library_view.currentIndex()) - self.library_view.setFocus(Qt.OtherFocusReason) + self.library_view.setFocus(Qt.FocusReason.OtherFocusReason) def edit_identifiers_triggerred(self): book_id = self.library_view.current_book @@ -725,7 +725,7 @@ class LayoutMixin(object): # {{{ def toggle_search_bar(self, show): self.search_bar.setVisible(show) if show: - self.search.setFocus(Qt.OtherFocusReason) + self.search.setFocus(Qt.FocusReason.OtherFocusReason) def bd_cover_changed(self, id_, cdata): self.library_view.model().db.set_cover(id_, cdata) diff --git a/src/calibre/gui2/job_indicator.py b/src/calibre/gui2/job_indicator.py index 59f35c469e..4f7d475fdf 100644 --- a/src/calibre/gui2/job_indicator.py +++ b/src/calibre/gui2/job_indicator.py @@ -24,7 +24,7 @@ class Pointer(QWidget): self.animation = QPropertyAnimation(self, b"geometry", self) self.animation.setDuration(750) self.animation.setLoopCount(2) - self.animation.setEasingCurve(QEasingCurve.Linear) + self.animation.setEasingCurve(QEasingCurve.Type.Linear) self.animation.finished.connect(self.hide) taily, heady = 0, 55 @@ -37,10 +37,10 @@ class Pointer(QWidget): self.arrow_path.lineTo(60, taily) self.arrow_path.closeSubpath() - c = self.palette().color(QPalette.Active, QPalette.WindowText) + c = self.palette().color(QPalette.ColorGroup.Active, QPalette.ColorRole.WindowText) self.color = QColor(c) self.color.setAlpha(100) - self.brush = QBrush(self.color, Qt.SolidPattern) + self.brush = QBrush(self.color, Qt.BrushStyle.SolidPattern) # from PyQt5.Qt import QTimer # QTimer.singleShot(1000, self.start) @@ -88,6 +88,6 @@ class Pointer(QWidget): p = QPainter(self) p.setRenderHints(p.Antialiasing) p.setBrush(self.brush) - p.setPen(Qt.NoPen) + p.setPen(Qt.PenStyle.NoPen) p.drawPath(self.arrow_path) p.end() diff --git a/src/calibre/gui2/jobs.py b/src/calibre/gui2/jobs.py index dbd7785b88..fb53377341 100644 --- a/src/calibre/gui2/jobs.py +++ b/src/calibre/gui2/jobs.py @@ -81,7 +81,7 @@ class JobManager(QAbstractTableModel, AdaptSQP): # {{{ self.changed_queue = Queue() self.timer = QTimer(self) - self.timer.timeout.connect(self.update, type=Qt.QueuedConnection) + self.timer.timeout.connect(self.update, type=Qt.ConnectionType.QueuedConnection) self.timer.start(1000) def columnCount(self, parent=QModelIndex()): @@ -91,9 +91,9 @@ class JobManager(QAbstractTableModel, AdaptSQP): # {{{ return len(self.jobs) def headerData(self, section, orientation, role): - if role != Qt.DisplayRole: + if role != Qt.ItemDataRole.DisplayRole: return None - if orientation == Qt.Horizontal: + if orientation == Qt.Orientation.Horizontal: return ({ 0: _('Job'), 1: _('Status'), @@ -129,12 +129,12 @@ class JobManager(QAbstractTableModel, AdaptSQP): # {{{ def data(self, index, role): try: - if role not in (Qt.DisplayRole, Qt.DecorationRole): + if role not in (Qt.ItemDataRole.DisplayRole, Qt.ItemDataRole.DecorationRole): return None row, col = index.row(), index.column() job = self.jobs[row] - if role == Qt.DisplayRole: + if role == Qt.ItemDataRole.DisplayRole: if col == 0: desc = job.description if not desc: @@ -152,7 +152,7 @@ class JobManager(QAbstractTableModel, AdaptSQP): # {{{ return human_readable_interval(rtime) if col == 4 and job.start_time is not None: return (strftime('%H:%M -- %d %b', time.localtime(job.start_time))) - if role == Qt.DecorationRole and col == 0: + if role == Qt.ItemDataRole.DecorationRole and col == 0: state = job.run_state if state == job.WAITING: return self.wait_icon @@ -427,12 +427,12 @@ class ProgressBarDelegate(QAbstractItemDelegate): # {{{ opts.maximum = 100 opts.textVisible = True try: - percent = int(index.model().data(index, Qt.DisplayRole)) + percent = int(index.model().data(index, Qt.ItemDataRole.DisplayRole)) except (TypeError, ValueError): percent = 0 opts.progress = percent opts.text = (_('Unavailable') if percent == 0 else '%d%%'%percent) - QApplication.style().drawControl(QStyle.CE_ProgressBar, opts, painter) + QApplication.style().drawControl(QStyle.ControlElement.CE_ProgressBar, opts, painter) # }}} @@ -502,7 +502,7 @@ class JobsButton(QWidget): # {{{ QWidget.__init__(self, parent) self.num_jobs = 0 self.mouse_over = False - self.pi = ProgressIndicator(self, self.style().pixelMetric(QStyle.PM_ToolBarIconSize)) + self.pi = ProgressIndicator(self, self.style().pixelMetric(QStyle.PixelMetric.PM_ToolBarIconSize)) self._jobs = QLabel('') self._jobs.mouseReleaseEvent = self.mouseReleaseEvent self.update_label() @@ -512,10 +512,10 @@ class JobsButton(QWidget): # {{{ l.setSpacing(3) l.addWidget(self.pi) l.addWidget(self._jobs) - m = self.style().pixelMetric(QStyle.PM_DefaultFrameWidth) + m = self.style().pixelMetric(QStyle.PixelMetric.PM_DefaultFrameWidth) self.layout().setContentsMargins(m, m, m, m) - self._jobs.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) - self.setCursor(Qt.PointingHandCursor) + self._jobs.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Minimum) + self.setCursor(Qt.CursorShape.PointingHandCursor) b = _('Click to see list of jobs') self.setToolTip(b + ' [%s]'%self.shortcut) self.action_toggle = QAction(b, parent) @@ -603,9 +603,9 @@ class JobsButton(QWidget): # {{{ p = QPainter(self) tool = QStyleOption() tool.rect = self.rect() - tool.state = QStyle.State_Raised | QStyle.State_Active | QStyle.State_MouseOver + tool.state = QStyle.StateFlag.State_Raised | QStyle.StateFlag.State_Active | QStyle.StateFlag.State_MouseOver s = self.style() - s.drawPrimitive(QStyle.PE_PanelButtonTool, tool, p, self) + s.drawPrimitive(QStyle.PrimitiveElement.PE_PanelButtonTool, tool, p, self) p.end() QWidget.paintEvent(self, ev) @@ -623,7 +623,7 @@ class JobsDialog(QDialog, Ui_JobsDialog): self.proxy_model.setSourceModel(self.model) self.proxy_model.search_done.connect(self.search.search_done) self.jobs_view.setModel(self.proxy_model) - self.setWindowModality(Qt.NonModal) + self.setWindowModality(Qt.WindowModality.NonModal) self.setWindowTitle(__appname__ + _(' - Jobs')) self.details_button.clicked.connect(self.show_details) self.kill_button.clicked.connect(self.kill_job) diff --git a/src/calibre/gui2/keyboard.py b/src/calibre/gui2/keyboard.py index aad131b97a..85c7ac6b29 100644 --- a/src/calibre/gui2/keyboard.py +++ b/src/calibre/gui2/keyboard.py @@ -37,15 +37,15 @@ class NameConflict(ValueError): def keysequence_from_event(ev): # {{{ k, mods = ev.key(), int(ev.modifiers()) if k in ( - 0, Qt.Key_unknown, Qt.Key_Shift, Qt.Key_Control, Qt.Key_Alt, - Qt.Key_Meta, Qt.Key_AltGr, Qt.Key_CapsLock, Qt.Key_NumLock, - Qt.Key_ScrollLock): + 0, Qt.Key.Key_unknown, Qt.Key.Key_Shift, Qt.Key.Key_Control, Qt.Key.Key_Alt, + Qt.Key.Key_Meta, Qt.Key.Key_AltGr, Qt.Key.Key_CapsLock, Qt.Key.Key_NumLock, + Qt.Key.Key_ScrollLock): return - letter = QKeySequence(k).toString(QKeySequence.PortableText) - if mods & Qt.SHIFT and letter.lower() == letter.upper(): + letter = QKeySequence(k).toString(QKeySequence.SequenceFormat.PortableText) + if mods & Qt.Modifier.SHIFT and letter.lower() == letter.upper(): # Something like Shift+* or Shift+> we have to remove the shift, # since it is included in keycode. - mods = mods & ~Qt.SHIFT + mods = mods & ~Qt.Modifier.SHIFT return QKeySequence(k | mods) # }}} @@ -69,8 +69,8 @@ def finalize(shortcuts, custom_keys_map={}): # {{{ shortcut['set_to_default'] = False keys = [] for x in candidates: - ks = QKeySequence(x, QKeySequence.PortableText) - x = unicode_type(ks.toString(QKeySequence.PortableText)) + ks = QKeySequence(x, QKeySequence.SequenceFormat.PortableText) + x = unicode_type(ks.toString(QKeySequence.SequenceFormat.PortableText)) if x in seen: if DEBUG: prints('Key %r for shortcut %s is already used by' @@ -250,9 +250,9 @@ class ConfigModel(SearchQueryParser, QAbstractItemModel): return self.index(i, 0) return ROOT - def data(self, index, role=Qt.DisplayRole): + def data(self, index, role=Qt.ItemDataRole.DisplayRole): ip = index.internalPointer() - if ip is not None and role == Qt.UserRole: + if ip is not None and role == Qt.ItemDataRole.UserRole: return ip return None @@ -260,7 +260,7 @@ class ConfigModel(SearchQueryParser, QAbstractItemModel): ans = QAbstractItemModel.flags(self, index) ip = index.internalPointer() if getattr(ip, 'is_shortcut', False): - ans |= Qt.ItemIsEditable + ans |= Qt.ItemFlag.ItemIsEditable return ans def restore_defaults(self): @@ -399,7 +399,7 @@ class Editor(QFrame): # {{{ def __init__(self, parent=None): QFrame.__init__(self, parent) - self.setFocusPolicy(Qt.StrongFocus) + self.setFocusPolicy(Qt.FocusPolicy.StrongFocus) self.setAutoFillBackground(True) self.capture = 0 @@ -448,7 +448,7 @@ class Editor(QFrame): # {{{ self.all_shortcuts = all_shortcuts self.shortcut = shortcut - self.default_keys = [QKeySequence(k, QKeySequence.PortableText) for k + self.default_keys = [QKeySequence(k, QKeySequence.SequenceFormat.PortableText) for k in shortcut['default_keys']] self.current_keys = list(shortcut['keys']) default = ', '.join([unicode_type(k.toString(k.NativeText)) for k in @@ -480,7 +480,7 @@ class Editor(QFrame): # {{{ self.capture = which button = getattr(self, 'button%d'%which) button.setText(_('Press a key...')) - button.setFocus(Qt.OtherFocusReason) + button.setFocus(Qt.FocusReason.OtherFocusReason) button.setStyleSheet('QPushButton { font-weight: bold}') def clear_clicked(self, which=0): @@ -508,12 +508,12 @@ class Editor(QFrame): # {{{ button = getattr(self, 'button%d'%which) button.setStyleSheet('QPushButton { font-weight: normal}') - button.setText(sequence.toString(QKeySequence.NativeText)) + button.setText(sequence.toString(QKeySequence.SequenceFormat.NativeText)) self.capture = 0 dup_desc = self.dup_check(sequence) if dup_desc is not None: error_dialog(self, _('Already assigned'), - unicode_type(sequence.toString(QKeySequence.NativeText)) + ' ' + _( + unicode_type(sequence.toString(QKeySequence.SequenceFormat.NativeText)) + ' ' + _( 'already assigned to') + ' ' + dup_desc, show=True) self.clear_clicked(which=which) @@ -535,7 +535,7 @@ class Editor(QFrame): # {{{ t = unicode_type(button.text()) if t == _('None'): continue - ks = QKeySequence(t, QKeySequence.NativeText) + ks = QKeySequence(t, QKeySequence.SequenceFormat.NativeText) if not ks.isEmpty(): ans.append(ks) return tuple(ans) @@ -553,7 +553,7 @@ class Delegate(QStyledItemDelegate): # {{{ self.closeEditor.connect(self.editing_done) def to_doc(self, index): - data = index.data(Qt.UserRole) + data = index.data(Qt.ItemDataRole.UserRole) if data is None: html = _('This shortcut no longer exists') elif data.is_shortcut: @@ -583,8 +583,8 @@ class Delegate(QStyledItemDelegate): # {{{ painter.save() painter.setClipRect(QRectF(option.rect)) if hasattr(QStyle, 'CE_ItemViewItem'): - QApplication.style().drawControl(QStyle.CE_ItemViewItem, option, painter) - elif option.state & QStyle.State_Selected: + QApplication.style().drawControl(QStyle.ControlElement.CE_ItemViewItem, option, painter) + elif option.state & QStyle.StateFlag.State_Selected: painter.fillRect(option.rect, option.palette.highlight()) painter.translate(option.rect.topLeft()) self.to_doc(index).drawContents(painter) @@ -612,11 +612,11 @@ class Delegate(QStyledItemDelegate): # {{{ def setModelData(self, editor, model, index): self.closeEditor.emit(editor, self.NoHint) custom_keys = editor.custom_keys - sc = index.data(Qt.UserRole).data + sc = index.data(Qt.ItemDataRole.UserRole).data if custom_keys is None: candidates = [] for ckey in sc['default_keys']: - ckey = QKeySequence(ckey, QKeySequence.PortableText) + ckey = QKeySequence(ckey, QKeySequence.SequenceFormat.PortableText) matched = False for s in editor.all_shortcuts: if s is editor.shortcut: @@ -666,7 +666,7 @@ class ShortcutConfig(QWidget): # {{{ self.delegate = Delegate() self.view.setItemDelegate(self.delegate) self.delegate.sizeHintChanged.connect(self.editor_opened, - type=Qt.QueuedConnection) + type=Qt.ConnectionType.QueuedConnection) self.delegate.changed_signal.connect(self.changed_signal) self.search = SearchBox2(self) self.search.initialize('shortcuts_search_history', @@ -723,7 +723,7 @@ class ShortcutConfig(QWidget): # {{{ self.view.selectionModel().select(idx, self.view.selectionModel().ClearAndSelect) self.view.setCurrentIndex(idx) - self.view.setFocus(Qt.OtherFocusReason) + self.view.setFocus(Qt.FocusReason.OtherFocusReason) def find_next(self, *args): idx = self.view.currentIndex() @@ -749,6 +749,6 @@ class ShortcutConfig(QWidget): # {{{ self.view.selectionModel().select(idx, self.view.selectionModel().ClearAndSelect) self.view.setCurrentIndex(idx) - self.view.setFocus(Qt.OtherFocusReason) + self.view.setFocus(Qt.FocusReason.OtherFocusReason) # }}} diff --git a/src/calibre/gui2/layout.py b/src/calibre/gui2/layout.py index abfdbb89d6..4563d8171f 100644 --- a/src/calibre/gui2/layout.py +++ b/src/calibre/gui2/layout.py @@ -191,23 +191,23 @@ class SearchBar(QFrame): # {{{ def __init__(self, parent): QFrame.__init__(self, parent) - self.setFrameStyle(QFrame.NoFrame) + self.setFrameStyle(QFrame.Shape.NoFrame) self.setObjectName('search_bar') self._layout = l = QHBoxLayout(self) l.setContentsMargins(0, 4, 0, 4) x = parent.virtual_library = QToolButton(self) - x.setCursor(Qt.PointingHandCursor) + x.setCursor(Qt.CursorShape.PointingHandCursor) x.setPopupMode(x.InstantPopup) x.setText(_('Virtual library')) x.setAutoRaise(True) x.setIcon(QIcon(I('vl.png'))) x.setObjectName("virtual_library") - x.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) + x.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) l.addWidget(x) x = QToolButton(self) - x.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) + x.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) x.setAutoRaise(True) x.setIcon(QIcon(I('minus.png'))) x.setObjectName('clear_vl') @@ -216,17 +216,17 @@ class SearchBar(QFrame): # {{{ x.setToolTip(_('Close the Virtual library')) parent.clear_vl = x self.vl_sep = QFrame(self) - self.vl_sep.setFrameStyle(QFrame.VLine | QFrame.Sunken) + self.vl_sep.setFrameStyle(QFrame.Shape.VLine | QFrame.Shadow.Sunken) l.addWidget(self.vl_sep) parent.sort_sep = QFrame(self) - parent.sort_sep.setFrameStyle(QFrame.VLine | QFrame.Sunken) + parent.sort_sep.setFrameStyle(QFrame.Shape.VLine | QFrame.Shadow.Sunken) parent.sort_sep.setVisible(False) parent.sort_button = self.sort_button = sb = QToolButton(self) - sb.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) + sb.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) sb.setToolTip(_('Change how the displayed books are sorted')) - sb.setCursor(Qt.PointingHandCursor) - sb.setPopupMode(QToolButton.InstantPopup) + sb.setCursor(Qt.CursorShape.PointingHandCursor) + sb.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup) sb.setAutoRaise(True) sb.setText(_('Sort')) sb.setIcon(QIcon(I('sort.png'))) @@ -237,14 +237,14 @@ class SearchBar(QFrame): # {{{ l.addWidget(parent.sort_sep) x = parent.search = SearchBox2(self, as_url=search_as_url) - x.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum) + x.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum) x.setObjectName("search") x.setToolTip(_("Search the list of books by title, author, publisher, "
"tags, comments, etc.
Words separated by spaces are ANDed"))
x.setMinimumContentsLength(10)
l.addWidget(x)
- parent.advanced_search_toggle_action = ac = parent.search.add_action('gear.png', QLineEdit.LeadingPosition)
+ parent.advanced_search_toggle_action = ac = parent.search.add_action('gear.png', QLineEdit.ActionPosition.LeadingPosition)
parent.addAction(ac)
ac.setToolTip(_('Advanced search'))
parent.keyboard.register_shortcut('advanced search toggle',
@@ -252,15 +252,15 @@ class SearchBar(QFrame): # {{{
action=ac)
self.search_button = QToolButton()
- self.search_button.setToolButtonStyle(Qt.ToolButtonTextOnly)
+ self.search_button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextOnly)
self.search_button.setIcon(QIcon(I('search.png')))
- self.search_button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
+ self.search_button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
self.search_button.setText(_('Search'))
self.search_button.setAutoRaise(True)
- self.search_button.setCursor(Qt.PointingHandCursor)
+ self.search_button.setCursor(Qt.CursorShape.PointingHandCursor)
l.addWidget(self.search_button)
- self.search_button.setSizePolicy(QSizePolicy.Minimum,
- QSizePolicy.Minimum)
+ self.search_button.setSizePolicy(QSizePolicy.Policy.Minimum,
+ QSizePolicy.Policy.Minimum)
self.search_button.clicked.connect(parent.do_search_button)
self.search_button.setToolTip(
_('Do quick search (you can also press the Enter key)'))
@@ -268,8 +268,8 @@ class SearchBar(QFrame): # {{{
x = parent.highlight_only_button = QToolButton(self)
x.setAutoRaise(True)
x.setText(_('Highlight'))
- x.setCursor(Qt.PointingHandCursor)
- x.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
+ x.setCursor(Qt.CursorShape.PointingHandCursor)
+ x.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
x.setIcon(QIcon(I('arrow-down.png')))
l.addWidget(x)
@@ -282,7 +282,7 @@ class SearchBar(QFrame): # {{{
x = parent.copy_search_button = QToolButton(self)
x.setAutoRaise(True)
- x.setCursor(Qt.PointingHandCursor)
+ x.setCursor(Qt.CursorShape.PointingHandCursor)
x.setIcon(QIcon(I("search_copy_saved.png")))
x.setObjectName("copy_search_button")
l.addWidget(x)
@@ -291,7 +291,7 @@ class SearchBar(QFrame): # {{{
x = parent.save_search_button = RightClickButton(self)
x.setAutoRaise(True)
- x.setCursor(Qt.PointingHandCursor)
+ x.setCursor(Qt.CursorShape.PointingHandCursor)
x.setIcon(QIcon(I("search_add_saved.png")))
x.setObjectName("save_search_button")
l.addWidget(x)
@@ -302,8 +302,8 @@ class SearchBar(QFrame): # {{{
'Use an existing Saved search or create a new one'
))
x.setText(_('Saved search'))
- x.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
- x.setCursor(Qt.PointingHandCursor)
+ x.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
+ x.setCursor(Qt.CursorShape.PointingHandCursor)
x.setPopupMode(x.InstantPopup)
x.setAutoRaise(True)
x.setIcon(QIcon(I("bookmarks.png")))
@@ -337,7 +337,7 @@ class MainWindowMixin(object): # {{{
self.setWindowIcon(QIcon(I('lt.png')))
self.setWindowTitle(__appname__)
- self.setContextMenuPolicy(Qt.NoContextMenu)
+ self.setContextMenuPolicy(Qt.ContextMenuPolicy.NoContextMenu)
self.centralwidget = QWidget(self)
self.setCentralWidget(self.centralwidget)
self._central_widget_layout = l = QVBoxLayout(self.centralwidget)
@@ -352,10 +352,10 @@ class MainWindowMixin(object): # {{{
self.bars_manager = BarsManager(self.donate_action,
self.location_manager, self)
for bar in self.bars_manager.main_bars:
- self.addToolBar(Qt.TopToolBarArea, bar)
+ self.addToolBar(Qt.ToolBarArea.TopToolBarArea, bar)
bar.setStyleSheet('QToolBar { border: 0px }')
for bar in self.bars_manager.child_bars:
- self.addToolBar(Qt.BottomToolBarArea, bar)
+ self.addToolBar(Qt.ToolBarArea.BottomToolBarArea, bar)
bar.setStyleSheet('QToolBar { border: 0px }')
self.bars_manager.update_bars()
# This is disabled because it introduces various toolbar related bugs
@@ -372,7 +372,7 @@ class MainWindowMixin(object): # {{{
# Add in the widget for the shutdown messages. It is invisible until a
# message is shown
smw = self.shutdown_message_widget = QLabel(self)
- smw.setAlignment(Qt.AlignCenter)
+ smw.setAlignment(Qt.AlignmentFlag.AlignCenter)
smw.setVisible(False)
smw.setAutoFillBackground(True)
smw.setStyleSheet('QLabel { background-color: rgba(200, 200, 200, 200); color: black }')
diff --git a/src/calibre/gui2/layout_menu.py b/src/calibre/gui2/layout_menu.py
index 03f43e5ac8..faaa97c20a 100644
--- a/src/calibre/gui2/layout_menu.py
+++ b/src/calibre/gui2/layout_menu.py
@@ -16,10 +16,10 @@ class LayoutItem(QWidget):
def __init__(self, button, parent=None):
QWidget.__init__(self, parent)
self.mouse_over = False
- self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
+ self.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
self.button = button
self.text = button.label
- self.setCursor(Qt.PointingHandCursor)
+ self.setCursor(Qt.CursorShape.PointingHandCursor)
self.fm = QFontMetrics(self.font())
self._bi = self._di = None
@@ -32,7 +32,7 @@ class LayoutItem(QWidget):
@property
def dull_icon(self):
if self._di is None:
- self._di = self.button.icon().pixmap(ICON_SZ, ICON_SZ, mode=QIcon.Disabled)
+ self._di = self.button.icon().pixmap(ICON_SZ, ICON_SZ, mode=QIcon.Mode.Disabled)
return self._di
def event(self, ev):
@@ -60,13 +60,13 @@ class LayoutItem(QWidget):
if self.mouse_over:
tool = QStyleOption()
tool.rect = self.rect()
- tool.state = QStyle.State_Raised | QStyle.State_Active | QStyle.State_MouseOver
+ tool.state = QStyle.StateFlag.State_Raised | QStyle.StateFlag.State_Active | QStyle.StateFlag.State_MouseOver
s = self.style()
- s.drawPrimitive(QStyle.PE_PanelButtonTool, tool, painter, self)
+ s.drawPrimitive(QStyle.PrimitiveElement.PE_PanelButtonTool, tool, painter, self)
painter.drawText(
0, 0,
self.width(),
- ls, Qt.AlignCenter | Qt.TextSingleLine, self.text)
+ ls, Qt.AlignmentFlag.AlignCenter | Qt.TextFlag.TextSingleLine, self.text)
text = _('Hide') if shown else _('Show')
f = self.font()
f.setBold(True)
@@ -74,7 +74,7 @@ class LayoutItem(QWidget):
painter.drawText(
0, self.height() - ls,
self.width(),
- ls, Qt.AlignCenter | Qt.TextSingleLine, text)
+ ls, Qt.AlignmentFlag.AlignCenter | Qt.TextFlag.TextSingleLine, text)
x = (self.width() - ICON_SZ) // 2
y = ls + (self.height() - ICON_SZ - 2 * ls) // 2
pmap = self.bright_icon if shown else self.dull_icon
@@ -115,7 +115,7 @@ class LayoutMenu(QMenu):
return item
def mousePressEvent(self, ev):
- if ev.button() != Qt.LeftButton:
+ if ev.button() != Qt.MouseButton.LeftButton:
ev.ignore()
return
if (ev.pos().isNull() and not ev.screenPos().isNull()) or not self.rect().contains(ev.pos()):
@@ -127,7 +127,7 @@ class LayoutMenu(QMenu):
ev.ignore()
def mouseReleaseEvent(self, ev):
- if ev.button() != Qt.LeftButton:
+ if ev.button() != Qt.MouseButton.LeftButton:
ev.ignore()
return
item = self.item_for_ev(ev)
diff --git a/src/calibre/gui2/library/alternate_views.py b/src/calibre/gui2/library/alternate_views.py
index 9fbc7dd107..39b33deae1 100644
--- a/src/calibre/gui2/library/alternate_views.py
+++ b/src/calibre/gui2/library/alternate_views.py
@@ -49,9 +49,9 @@ class EncodeError(ValueError):
def handle_enter_press(self, ev, special_action=None, has_edit_cell=True):
- if ev.key() in (Qt.Key_Enter, Qt.Key_Return):
+ if ev.key() in (Qt.Key.Key_Enter, Qt.Key.Key_Return):
mods = ev.modifiers()
- if mods & Qt.CTRL or mods & Qt.ALT or mods & Qt.SHIFT or mods & Qt.META:
+ if mods & Qt.Modifier.CTRL or mods & Qt.Modifier.ALT or mods & Qt.Modifier.SHIFT or mods & Qt.Modifier.META:
return
if self.state() != self.EditingState and self.hasFocus() and self.currentIndex().isValid():
from calibre.gui2.ui import get_gui
@@ -102,13 +102,13 @@ def dragMoveEvent(self, event):
def event_has_mods(self, event=None):
mods = event.modifiers() if event is not None else \
QApplication.keyboardModifiers()
- return mods & Qt.ControlModifier or mods & Qt.ShiftModifier
+ return mods & Qt.KeyboardModifier.ControlModifier or mods & Qt.KeyboardModifier.ShiftModifier
def mousePressEvent(self, event):
ep = event.pos()
if self.indexAt(ep) in self.selectionModel().selectedIndexes() and \
- event.button() == Qt.LeftButton and not self.event_has_mods():
+ event.button() == Qt.MouseButton.LeftButton and not self.event_has_mods():
self.drag_start_pos = ep
if hasattr(self, 'handle_mouse_press_event'):
return self.handle_mouse_press_event(event)
@@ -116,12 +116,12 @@ def mousePressEvent(self, event):
def drag_icon(self, cover, multiple):
- cover = cover.scaledToHeight(120, Qt.SmoothTransformation)
+ cover = cover.scaledToHeight(120, Qt.TransformationMode.SmoothTransformation)
if multiple:
base_width = cover.width()
base_height = cover.height()
base = QImage(base_width+21, base_height+21,
- QImage.Format_ARGB32_Premultiplied)
+ QImage.Format.Format_ARGB32_Premultiplied)
base.fill(QColor(255, 255, 255, 0).rgba())
p = QPainter(base)
rect = QRect(20, 0, base_width, base_height)
@@ -198,7 +198,7 @@ def mouseMoveEvent(self, event):
self.drag_start_pos = None
return
- if not (event.buttons() & Qt.LeftButton) or \
+ if not (event.buttons() & Qt.MouseButton.LeftButton) or \
(event.pos() - self.drag_start_pos).manhattanLength() \
< QApplication.startDragDistance():
return
@@ -207,7 +207,7 @@ def mouseMoveEvent(self, event):
if not index.isValid():
return
drag = self.drag_data()
- drag.exec_(Qt.CopyAction)
+ drag.exec_(Qt.DropAction.CopyAction)
self.drag_start_pos = None
@@ -216,8 +216,8 @@ def dnd_merge_ok(md):
def dragEnterEvent(self, event):
- if int(event.possibleActions() & Qt.CopyAction) + \
- int(event.possibleActions() & Qt.MoveAction) == 0:
+ if int(event.possibleActions() & Qt.DropAction.CopyAction) + \
+ int(event.possibleActions() & Qt.DropAction.MoveAction) == 0:
return
paths = self.paths_from_event(event)
md = event.mimeData()
@@ -235,11 +235,11 @@ def dropEvent(self, event):
book_id = self.model().id(row)
if book_id and book_id not in ids:
self.books_dropped.emit({book_id: ids})
- event.setDropAction(Qt.CopyAction)
+ event.setDropAction(Qt.DropAction.CopyAction)
event.accept()
return
paths = self.paths_from_event(event)
- event.setDropAction(Qt.CopyAction)
+ event.setDropAction(Qt.DropAction.CopyAction)
event.accept()
self.files_dropped.emit(paths)
@@ -329,7 +329,7 @@ class AlternateViews(object):
self.main_connected = True
self.main_view.selectionModel().currentChanged.connect(self.main_current_changed)
self.main_view.selectionModel().selectionChanged.connect(self.main_selection_changed)
- view.setFocus(Qt.OtherFocusReason)
+ view.setFocus(Qt.FocusReason.OtherFocusReason)
def set_database(self, db, stage=0):
for view in itervalues(self.views):
@@ -399,13 +399,13 @@ class CoverDelegate(QStyledItemDelegate):
super(CoverDelegate, self).__init__(parent)
self._animated_size = 1.0
self.animation = QPropertyAnimation(self, b'animated_size', self)
- self.animation.setEasingCurve(QEasingCurve.OutInCirc)
+ self.animation.setEasingCurve(QEasingCurve.Type.OutInCirc)
self.animation.setDuration(500)
self.set_dimensions()
self.cover_cache = CoverCache()
self.render_queue = LifoQueue()
self.animating = None
- self.highlight_color = QColor(Qt.white)
+ self.highlight_color = QColor(Qt.GlobalColor.white)
self.rating_font = QFont(rating_font())
def set_dimensions(self):
@@ -516,8 +516,8 @@ class CoverDelegate(QStyledItemDelegate):
painter.save()
try:
painter.setPen(self.highlight_color)
- painter.setRenderHint(QPainter.Antialiasing, True)
- painter.drawRoundedRect(option.rect, 10, 10, Qt.RelativeSize)
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
+ painter.drawRoundedRect(option.rect, 10, 10, Qt.SizeMode.RelativeSize)
finally:
painter.restore()
marked = db.data.get_marked(book_id)
@@ -556,8 +556,8 @@ class CoverDelegate(QStyledItemDelegate):
if cdata is None or cdata is False:
title = db.field_for('title', book_id, default_value='')
authors = ' & '.join(db.field_for('authors', book_id, default_value=()))
- painter.setRenderHint(QPainter.TextAntialiasing, True)
- painter.drawText(rect, Qt.AlignCenter|Qt.TextWordWrap, '%s\n\n%s' % (title, authors))
+ painter.setRenderHint(QPainter.RenderHint.TextAntialiasing, True)
+ painter.drawText(rect, Qt.AlignmentFlag.AlignCenter|Qt.TextFlag.TextWordWrap, '%s\n\n%s' % (title, authors))
if cdata is False:
self.render_queue.put(book_id)
if self.title_height != 0:
@@ -593,14 +593,14 @@ class CoverDelegate(QStyledItemDelegate):
painter.restore()
def paint_title(self, painter, rect, db, book_id):
- painter.setRenderHint(QPainter.TextAntialiasing, True)
+ painter.setRenderHint(QPainter.RenderHint.TextAntialiasing, True)
title, is_stars = self.render_field(db, book_id)
if is_stars:
painter.setFont(self.rating_font)
metrics = painter.fontMetrics()
painter.setPen(self.highlight_color)
- painter.drawText(rect, Qt.AlignCenter|Qt.TextSingleLine,
- metrics.elidedText(title, Qt.ElideRight, rect.width()))
+ painter.drawText(rect, Qt.AlignmentFlag.AlignCenter|Qt.TextFlag.TextSingleLine,
+ metrics.elidedText(title, Qt.TextElideMode.ElideRight, rect.width()))
def paint_emblems(self, painter, rect, emblems):
gutter = self.emblem_size + self.MARGIN
@@ -647,7 +647,7 @@ class CoverDelegate(QStyledItemDelegate):
@pyqtSlot(QHelpEvent, QAbstractItemView, QStyleOptionViewItem, QModelIndex, result=bool)
def helpEvent(self, event, view, option, index):
- if event is not None and view is not None and event.type() == QEvent.ToolTip:
+ if event is not None and view is not None and event.type() == QEvent.Type.ToolTip:
try:
db = index.model().db
except AttributeError:
@@ -717,9 +717,9 @@ class GridView(QListView):
self.thumbnail_cache = ThumbnailCache(max_size=gprefs['cover_grid_disk_cache_size'],
thumbnail_size=(int(dpr * self.delegate.cover_size.width()), int(dpr * self.delegate.cover_size.height())))
self.render_thread = None
- self.update_item.connect(self.re_render, type=Qt.QueuedConnection)
+ self.update_item.connect(self.re_render, type=Qt.ConnectionType.QueuedConnection)
self.doubleClicked.connect(self.double_clicked)
- self.setCursor(Qt.PointingHandCursor)
+ self.setCursor(Qt.CursorShape.PointingHandCursor)
self.gui = parent
self.context_menu = None
self.update_timer = QTimer(self)
@@ -924,7 +924,7 @@ class GridView(QListView):
if scaled:
if self.ignore_render_requests.is_set():
return
- p = p.scaled(nwidth, nheight, Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
+ p = p.scaled(nwidth, nheight, Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation)
p.setDevicePixelRatio(dpr)
cdata = p
# update cache
@@ -1029,7 +1029,7 @@ class GridView(QListView):
pass
def handle_mouse_press_event(self, ev):
- if QApplication.keyboardModifiers() & Qt.ShiftModifier:
+ if QApplication.keyboardModifiers() & Qt.KeyboardModifier.ShiftModifier:
# Shift-Click in QListView is broken. It selects extra items in
# various circumstances, for example, click on some item in the
# middle of a row then click on an item in the next row, all items
@@ -1079,13 +1079,13 @@ class GridView(QListView):
if handle_enter_press(self, ev, self.start_view_animation, False):
return
k = ev.key()
- if ev.modifiers() & Qt.ShiftModifier and k in (Qt.Key_Left, Qt.Key_Right, Qt.Key_Up, Qt.Key_Down):
+ if ev.modifiers() & Qt.KeyboardModifier.ShiftModifier and k in (Qt.Key.Key_Left, Qt.Key.Key_Right, Qt.Key.Key_Up, Qt.Key.Key_Down):
ci = self.currentIndex()
if not ci.isValid():
return
c = ci.row()
ncols = self.number_of_columns() or 1
- delta = {Qt.Key_Left: -1, Qt.Key_Right: 1, Qt.Key_Up: -ncols, Qt.Key_Down: ncols}[k]
+ delta = {Qt.Key.Key_Left: -1, Qt.Key.Key_Right: 1, Qt.Key.Key_Up: -ncols, Qt.Key.Key_Down: ncols}[k]
n = max(0, min(c + delta, self.model().rowCount(None) - 1))
if n == c:
return
@@ -1117,7 +1117,7 @@ class GridView(QListView):
def restore_current_book_state(self, state):
book_id = state
- self.setFocus(Qt.OtherFocusReason)
+ self.setFocus(Qt.FocusReason.OtherFocusReason)
try:
row = self.model().db.data.id_to_index(book_id)
except (IndexError, ValueError, KeyError, TypeError, AttributeError):
@@ -1146,12 +1146,12 @@ class GridView(QListView):
return index
def selectionCommand(self, index, event):
- if event and event.type() == event.KeyPress and event.key() in (Qt.Key_Home, Qt.Key_End) and event.modifiers() & Qt.CTRL:
- return QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Rows
+ if event and event.type() == event.KeyPress and event.key() in (Qt.Key.Key_Home, Qt.Key.Key_End) and event.modifiers() & Qt.Modifier.CTRL:
+ return QItemSelectionModel.SelectionFlag.ClearAndSelect | QItemSelectionModel.SelectionFlag.Rows
return super(GridView, self).selectionCommand(index, event)
def wheelEvent(self, ev):
- if ev.phase() not in (Qt.ScrollUpdate, 0, Qt.ScrollMomentum):
+ if ev.phase() not in (Qt.ScrollPhase.ScrollUpdate, 0, Qt.ScrollPhase.ScrollMomentum):
return
number_of_pixels = ev.pixelDelta()
number_of_degrees = ev.angleDelta() / 8.0
diff --git a/src/calibre/gui2/library/annotations.py b/src/calibre/gui2/library/annotations.py
index 9b52ccb0d4..6bfa04255b 100644
--- a/src/calibre/gui2/library/annotations.py
+++ b/src/calibre/gui2/library/annotations.py
@@ -24,7 +24,7 @@ from calibre.gui2.widgets2 import Dialog
# rendering {{{
def render_highlight_as_text(hl, lines):
lines.append(hl['highlighted_text'])
- date = QDateTime.fromString(hl['timestamp'], Qt.ISODate).toLocalTime().toString(Qt.SystemLocaleShortDate)
+ date = QDateTime.fromString(hl['timestamp'], Qt.DateFormat.ISODate).toLocalTime().toString(Qt.DateFormat.SystemLocaleShortDate)
lines.append(date)
notes = hl.get('notes')
if notes:
@@ -37,7 +37,7 @@ def render_highlight_as_text(hl, lines):
def render_bookmark_as_text(b, lines):
lines.append(b['title'])
- date = QDateTime.fromString(b['timestamp'], Qt.ISODate).toLocalTime().toString(Qt.SystemLocaleShortDate)
+ date = QDateTime.fromString(b['timestamp'], Qt.DateFormat.ISODate).toLocalTime().toString(Qt.DateFormat.SystemLocaleShortDate)
lines.append(date)
lines.append('')
lines.append('───')
@@ -186,7 +186,7 @@ def current_db():
class BusyCursor(object):
def __enter__(self):
- QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
+ QApplication.setOverrideCursor(QCursor(Qt.CursorShape.WaitCursor))
def __exit__(self, *args):
QApplication.restoreOverrideCursor()
@@ -205,7 +205,7 @@ class ResultsList(QTreeWidget):
QTreeWidget.__init__(self, parent)
self.setHeaderHidden(True)
self.setSelectionMode(self.ExtendedSelection)
- self.setContextMenuPolicy(Qt.CustomContextMenu)
+ self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.customContextMenuRequested.connect(self.show_context_menu)
self.delegate = AnnotsResultsDelegate(self)
self.setItemDelegate(self.delegate)
@@ -219,7 +219,7 @@ class ResultsList(QTreeWidget):
def show_context_menu(self, pos):
item = self.itemAt(pos)
if item is not None:
- result = item.data(0, Qt.UserRole)
+ result = item.data(0, Qt.ItemDataRole.UserRole)
else:
result = None
items = self.selectedItems()
@@ -239,17 +239,17 @@ class ResultsList(QTreeWidget):
m.exec_(self.mapToGlobal(pos))
def edit_notes(self, item):
- r = item.data(0, Qt.UserRole)
+ r = item.data(0, Qt.ItemDataRole.UserRole)
if isinstance(r, dict):
self.edit_annotation.emit(r['id'], r['annotation'])
def show_in_calibre(self, item):
- r = item.data(0, Qt.UserRole)
+ r = item.data(0, Qt.ItemDataRole.UserRole)
if isinstance(r, dict):
self.show_book.emit(r['book_id'], r['format'])
def item_activated(self, item):
- r = item.data(0, Qt.UserRole)
+ r = item.data(0, Qt.ItemDataRole.UserRole)
if isinstance(r, dict):
self.open_annotation.emit(r['book_id'], r['format'], r['annotation'])
@@ -267,23 +267,23 @@ class ResultsList(QTreeWidget):
book_id_map[book_id]['matches'].append(result)
for book_id, entry in book_id_map.items():
section = QTreeWidgetItem([entry['title']], 1)
- section.setFlags(Qt.ItemIsEnabled)
+ section.setFlags(Qt.ItemFlag.ItemIsEnabled)
section.setFont(0, self.section_font)
self.addTopLevelItem(section)
section.setExpanded(True)
for result in entry['matches']:
item = QTreeWidgetItem(section, [' '], 2)
self.item_map.append(item)
- item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemNeverHasChildren)
- item.setData(0, Qt.UserRole, result)
- item.setData(0, Qt.UserRole + 1, self.number_of_results)
+ item.setFlags(Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemNeverHasChildren)
+ item.setData(0, Qt.ItemDataRole.UserRole, result)
+ item.setData(0, Qt.ItemDataRole.UserRole + 1, self.number_of_results)
self.number_of_results += 1
if self.item_map:
self.setCurrentItem(self.item_map[0])
def current_item_changed(self, current, previous):
if current is not None:
- r = current.data(0, Qt.UserRole)
+ r = current.data(0, Qt.ItemDataRole.UserRole)
if isinstance(r, dict):
self.current_result_changed.emit(r)
else:
@@ -293,7 +293,7 @@ class ResultsList(QTreeWidget):
item = self.currentItem()
if item is None:
return
- i = int(item.data(0, Qt.UserRole + 1))
+ i = int(item.data(0, Qt.ItemDataRole.UserRole + 1))
i += -1 if backwards else 1
i %= self.number_of_results
self.setCurrentItem(self.item_map[i])
@@ -301,19 +301,19 @@ class ResultsList(QTreeWidget):
@property
def selected_annot_ids(self):
for item in self.selectedItems():
- yield item.data(0, Qt.UserRole)['id']
+ yield item.data(0, Qt.ItemDataRole.UserRole)['id']
@property
def selected_annotations(self):
for item in self.selectedItems():
- x = item.data(0, Qt.UserRole)
+ x = item.data(0, Qt.ItemDataRole.UserRole)
ans = x['annotation'].copy()
for key in ('book_id', 'format'):
ans[key] = x[key]
yield ans
def keyPressEvent(self, ev):
- if ev.matches(QKeySequence.Delete):
+ if ev.matches(QKeySequence.StandardKey.Delete):
self.delete_requested.emit()
ev.accept()
return
@@ -445,21 +445,21 @@ class BrowsePanel(QWidget):
l.addLayout(h)
self.search_box = sb = SearchBox(self)
sb.initialize('library-annotations-browser-search-box')
- sb.cleared.connect(self.cleared, type=Qt.QueuedConnection)
+ sb.cleared.connect(self.cleared, type=Qt.ConnectionType.QueuedConnection)
sb.lineEdit().returnPressed.connect(self.show_next)
sb.lineEdit().setPlaceholderText(_('Enter words to search for'))
h.addWidget(sb)
self.next_button = nb = QToolButton(self)
h.addWidget(nb)
- nb.setFocusPolicy(Qt.NoFocus)
+ nb.setFocusPolicy(Qt.FocusPolicy.NoFocus)
nb.setIcon(QIcon(I('arrow-down.png')))
nb.clicked.connect(self.show_next)
nb.setToolTip(_('Find next match'))
self.prev_button = nb = QToolButton(self)
h.addWidget(nb)
- nb.setFocusPolicy(Qt.NoFocus)
+ nb.setFocusPolicy(Qt.FocusPolicy.NoFocus)
nb.setIcon(QIcon(I('arrow-up.png')))
nb.clicked.connect(self.show_previous)
nb.setToolTip(_('Find previous match'))
@@ -480,7 +480,7 @@ class BrowsePanel(QWidget):
def re_initialize(self, restrict_to_book_ids=None):
db = current_db()
- self.search_box.setFocus(Qt.OtherFocusReason)
+ self.search_box.setFocus(Qt.FocusReason.OtherFocusReason)
self.restrictions.re_initialize(db, restrict_to_book_ids or set())
self.current_query = None
self.results_list.clear()
@@ -569,9 +569,9 @@ class Details(QTextBrowser):
QTextBrowser.__init__(self, parent)
self.setFrameShape(self.NoFrame)
self.setOpenLinks(False)
- self.setAttribute(Qt.WA_OpaquePaintEvent, False)
+ self.setAttribute(Qt.WidgetAttribute.WA_OpaquePaintEvent, False)
palette = self.palette()
- palette.setBrush(QPalette.Base, Qt.transparent)
+ palette.setBrush(QPalette.ColorRole.Base, Qt.GlobalColor.transparent)
self.setPalette(palette)
self.setAcceptDrops(False)
@@ -665,7 +665,7 @@ class DetailsPanel(QWidget):
_('Add notes to this highlight'), _('Add notes')))
annot_text += '\n'.join(paras)
- date = QDateTime.fromString(annot['timestamp'], Qt.ISODate).toLocalTime().toString(Qt.SystemLocaleShortDate)
+ date = QDateTime.fromString(annot['timestamp'], Qt.DateFormat.ISODate).toLocalTime().toString(Qt.DateFormat.SystemLocaleShortDate)
text = '''
@@ -722,7 +722,7 @@ class AnnotationsBrowser(Dialog):
def __init__(self, parent=None):
Dialog.__init__(self, _('Annotations browser'), 'library-annotations-browser', parent=parent)
- self.setAttribute(Qt.WA_DeleteOnClose, False)
+ self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, False)
self.setWindowIcon(QIcon(I('highlight.png')))
def do_open_annotation(self, book_id, fmt, annot):
@@ -735,7 +735,7 @@ class AnnotationsBrowser(Dialog):
self.open_annotation.emit(book_id, fmt, 'epubcfi(/{}{})'.format(x, annot['start_cfi']))
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 Dialog.keyPressEvent(self, ev)
def setup_ui(self):
@@ -744,7 +744,7 @@ class AnnotationsBrowser(Dialog):
us.setToolTip('
' + _(
'With this option searching for words will also match on any related English words. For'
' example: correction matches correcting and corrected as well'))
- us.stateChanged.connect(lambda state: gprefs.set('browse_annots_use_stemmer', state != Qt.Unchecked))
+ us.stateChanged.connect(lambda state: gprefs.set('browse_annots_use_stemmer', state != Qt.CheckState.Unchecked))
l = QVBoxLayout(self)
diff --git a/src/calibre/gui2/library/delegates.py b/src/calibre/gui2/library/delegates.py
index 2ac8494405..88959d97b9 100644
--- a/src/calibre/gui2/library/delegates.py
+++ b/src/calibre/gui2/library/delegates.py
@@ -52,18 +52,18 @@ class UpdateEditorGeometry(object):
else:
# The line edit box seems to extend by the space consumed by an 'M'.
# So add that to the text
- text = self.displayText(index.data(Qt.DisplayRole), QLocale()) + 'M'
- srect = style.itemTextRect(fm, editor.geometry(), Qt.AlignLeft, False, text)
+ text = self.displayText(index.data(Qt.ItemDataRole.DisplayRole), QLocale()) + 'M'
+ srect = style.itemTextRect(fm, editor.geometry(), Qt.AlignmentFlag.AlignLeft, False, text)
new_width = srect.width()
# Now get the size of the combo/spinner arrows and add them to the needed width
if isinstance(editor, (QComboBox, QDateTimeEdit)):
- r = style.subControlRect(QStyle.CC_ComboBox, QStyleOptionComboBox(),
- QStyle.SC_ComboBoxArrow, editor)
+ r = style.subControlRect(QStyle.ComplexControl.CC_ComboBox, QStyleOptionComboBox(),
+ QStyle.SubControl.SC_ComboBoxArrow, editor)
new_width += r.width()
elif isinstance(editor, (QSpinBox, QDoubleSpinBox)):
- r = style.subControlRect(QStyle.CC_SpinBox, QStyleOptionSpinBox(),
- QStyle.SC_SpinBoxUp, editor)
+ r = style.subControlRect(QStyle.ComplexControl.CC_SpinBox, QStyleOptionSpinBox(),
+ QStyle.SubControl.SC_SpinBoxUp, editor)
new_width += r.width()
# Compute the maximum we can show if we consume the entire viewport
@@ -94,7 +94,7 @@ class UpdateEditorGeometry(object):
space_left = initial_geometry.x()
space_right = max_width - space_left
- if editor.layoutDirection() == Qt.RightToLeft:
+ if editor.layoutDirection() == Qt.LayoutDirection.RightToLeft:
# If language is RtL, align to the cell's right edge if possible
cw = initial_geometry.width()
consume_on_left = min(space_left, new_width - cw)
@@ -132,7 +132,7 @@ def make_clearing_spinbox(spinbox):
def contextMenuEvent(self, ev):
m = QMenu(self)
- m.addAction(_('Set to undefined') + '\t' + QKeySequence(Qt.Key_Space).toString(QKeySequence.NativeText),
+ m.addAction(_('Set to undefined') + '\t' + QKeySequence(Qt.Key.Key_Space).toString(QKeySequence.SequenceFormat.NativeText),
self.clear_to_undefined)
m.addSeparator()
populate_standard_spinbox_context_menu(self, m)
@@ -142,7 +142,7 @@ def make_clearing_spinbox(spinbox):
self.setValue(self.minimum())
def keyPressEvent(self, ev):
- if ev.key() == Qt.Key_Space:
+ if ev.key() == Qt.Key.Key_Space:
self.clear_to_undefined()
else:
return spinbox.keyPressEvent(self, ev)
@@ -158,15 +158,15 @@ ClearingDoubleSpinBox = make_clearing_spinbox(QDoubleSpinBox)
def check_key_modifier(which_modifier):
- v = int(QApplication.keyboardModifiers() & (Qt.ControlModifier + Qt.ShiftModifier))
+ v = int(QApplication.keyboardModifiers() & (Qt.KeyboardModifier.ControlModifier + Qt.KeyboardModifier.ShiftModifier))
return v == which_modifier
def get_val_for_textlike_columns(index_):
- if check_key_modifier(Qt.ControlModifier):
+ if check_key_modifier(Qt.KeyboardModifier.ControlModifier):
ct = ''
else:
- ct = index_.data(Qt.DisplayRole) or ''
+ ct = index_.data(Qt.ItemDataRole.DisplayRole) or ''
return unicode_type(ct)
# }}}
@@ -179,7 +179,7 @@ class RatingDelegate(QStyledItemDelegate, UpdateEditorGeometry): # {{{
self.is_half_star = kwargs.get('is_half_star', False)
self.table_widget = args[0]
self.rf = QFont(rating_font())
- self.em = Qt.ElideMiddle
+ self.em = Qt.TextElideMode.ElideMiddle
delta = 0
if iswindows and sys.getwindowsversion().major >= 6:
delta = 2
@@ -195,15 +195,15 @@ class RatingDelegate(QStyledItemDelegate, UpdateEditorGeometry): # {{{
return RatingEditor(parent, is_half_star=self.is_half_star)
def setEditorData(self, editor, index):
- if check_key_modifier(Qt.ControlModifier):
+ if check_key_modifier(Qt.KeyboardModifier.ControlModifier):
val = 0
else:
- val = index.data(Qt.EditRole)
+ val = index.data(Qt.ItemDataRole.EditRole)
editor.rating_value = val
def setModelData(self, editor, model, index):
val = editor.rating_value
- model.setData(index, val, Qt.EditRole)
+ model.setData(index, val, Qt.ItemDataRole.EditRole)
def sizeHint(self, option, index):
option.font = self.rf
@@ -239,12 +239,12 @@ class DateDelegate(QStyledItemDelegate, UpdateEditorGeometry): # {{{
return DateTimeEdit(parent, self.format)
def setEditorData(self, editor, index):
- if check_key_modifier(Qt.ControlModifier):
+ if check_key_modifier(Qt.KeyboardModifier.ControlModifier):
val = UNDEFINED_QDATETIME
- elif check_key_modifier(Qt.ShiftModifier + Qt.ControlModifier):
+ elif check_key_modifier(Qt.KeyboardModifier.ShiftModifier + Qt.KeyboardModifier.ControlModifier):
val = now()
else:
- val = index.data(Qt.EditRole)
+ val = index.data(Qt.ItemDataRole.EditRole)
editor.setDateTime(val)
# }}}
@@ -269,10 +269,10 @@ class PubDateDelegate(QStyledItemDelegate, UpdateEditorGeometry): # {{{
return DateTimeEdit(parent, self.format)
def setEditorData(self, editor, index):
- val = index.data(Qt.EditRole)
- if check_key_modifier(Qt.ControlModifier):
+ val = index.data(Qt.ItemDataRole.EditRole)
+ if check_key_modifier(Qt.KeyboardModifier.ControlModifier):
val = UNDEFINED_QDATETIME
- elif check_key_modifier(Qt.ShiftModifier + Qt.ControlModifier):
+ elif check_key_modifier(Qt.KeyboardModifier.ShiftModifier + Qt.KeyboardModifier.ControlModifier):
val = now()
elif is_date_undefined(val):
val = QDate.currentDate()
@@ -315,7 +315,7 @@ class TextDelegate(QStyledItemDelegate, UpdateEditorGeometry): # {{{
def setModelData(self, editor, model, index):
if isinstance(editor, EditWithComplete):
val = editor.lineEdit().text()
- model.setData(index, (val), Qt.EditRole)
+ model.setData(index, (val), Qt.ItemDataRole.EditRole)
else:
QStyledItemDelegate.setModelData(self, editor, model, index)
@@ -326,7 +326,7 @@ class SeriesDelegate(TextDelegate): # {{{
def initStyleOption(self, option, index):
TextDelegate.initStyleOption(self, option, index)
- option.textElideMode = Qt.ElideMiddle
+ option.textElideMode = Qt.TextElideMode.ElideMiddle
# }}}
@@ -347,11 +347,11 @@ class CompleteDelegate(QStyledItemDelegate, UpdateEditorGeometry): # {{{
m = index.model()
col = m.column_map[index.column()]
# If shifted, bring up the tag editor instead of the line editor.
- if check_key_modifier(Qt.ShiftModifier) and col != 'authors':
+ if check_key_modifier(Qt.KeyboardModifier.ShiftModifier) and col != 'authors':
key = col if m.is_custom_column(col) else None
d = TagEditor(parent, self.db, m.id(index.row()), key=key)
if d.exec_() == TagEditor.Accepted:
- m.setData(index, self.sep.join(d.tags), Qt.EditRole)
+ m.setData(index, self.sep.join(d.tags), Qt.ItemDataRole.EditRole)
return None
editor = EditWithComplete(parent)
editor.set_separator(self.sep)
@@ -375,7 +375,7 @@ class CompleteDelegate(QStyledItemDelegate, UpdateEditorGeometry): # {{{
def setModelData(self, editor, model, index):
if isinstance(editor, EditWithComplete):
val = editor.lineEdit().text()
- model.setData(index, (val), Qt.EditRole)
+ model.setData(index, (val), Qt.ItemDataRole.EditRole)
else:
QStyledItemDelegate.setModelData(self, editor, model, index)
# }}}
@@ -398,7 +398,7 @@ class LanguagesDelegate(QStyledItemDelegate, UpdateEditorGeometry): # {{{
def setModelData(self, editor, model, index):
val = ','.join(editor.lang_codes)
editor.update_recently_used()
- model.setData(index, (val), Qt.EditRole)
+ model.setData(index, (val), Qt.ItemDataRole.EditRole)
# }}}
@@ -432,12 +432,12 @@ class CcDateDelegate(QStyledItemDelegate, UpdateEditorGeometry): # {{{
return DateTimeEdit(parent, self.format)
def setEditorData(self, editor, index):
- if check_key_modifier(Qt.ControlModifier):
+ if check_key_modifier(Qt.KeyboardModifier.ControlModifier):
val = UNDEFINED_QDATETIME
- elif check_key_modifier(Qt.ShiftModifier + Qt.ControlModifier):
+ elif check_key_modifier(Qt.KeyboardModifier.ShiftModifier + Qt.KeyboardModifier.ControlModifier):
val = now()
else:
- val = index.data(Qt.EditRole)
+ val = index.data(Qt.ItemDataRole.EditRole)
if is_date_undefined(val):
val = now()
editor.setDateTime(val)
@@ -446,7 +446,7 @@ class CcDateDelegate(QStyledItemDelegate, UpdateEditorGeometry): # {{{
val = editor.dateTime()
if is_date_undefined(val):
val = None
- model.setData(index, (val), Qt.EditRole)
+ model.setData(index, (val), Qt.ItemDataRole.EditRole)
# }}}
@@ -472,7 +472,7 @@ class CcTextDelegate(QStyledItemDelegate, UpdateEditorGeometry): # {{{
editor.update_items_cache(complete_items)
else:
editor = QLineEdit(parent)
- text = index.data(Qt.DisplayRole)
+ text = index.data(Qt.ItemDataRole.DisplayRole)
if text:
editor.setText(text)
editor.selectAll()
@@ -486,7 +486,7 @@ class CcTextDelegate(QStyledItemDelegate, UpdateEditorGeometry): # {{{
val = editor.text() or ''
if not isinstance(editor, EditWithComplete):
val = val.strip()
- model.setData(index, val, Qt.EditRole)
+ model.setData(index, val, Qt.ItemDataRole.EditRole)
# }}}
@@ -494,7 +494,7 @@ class CcSeriesDelegate(CcTextDelegate): # {{{
def initStyleOption(self, option, index):
CcTextDelegate.initStyleOption(self, option, index)
- option.textElideMode = Qt.ElideMiddle
+ option.textElideMode = Qt.TextElideMode.ElideMiddle
# }}}
@@ -511,17 +511,17 @@ class CcLongTextDelegate(QStyledItemDelegate): # {{{
def createEditor(self, parent, option, index):
m = index.model()
col = m.column_map[index.column()]
- if check_key_modifier(Qt.ControlModifier):
+ if check_key_modifier(Qt.KeyboardModifier.ControlModifier):
text = ''
else:
text = m.db.data[index.row()][m.custom_columns[col]['rec_index']]
d = PlainTextDialog(parent, text, column_name=m.custom_columns[col]['name'])
if d.exec_() == d.Accepted:
- m.setData(index, d.text, Qt.EditRole)
+ m.setData(index, d.text, Qt.ItemDataRole.EditRole)
return None
def setModelData(self, editor, model, index):
- model.setData(index, (editor.textbox.html), Qt.EditRole)
+ model.setData(index, (editor.textbox.html), Qt.ItemDataRole.EditRole)
# }}}
@@ -554,13 +554,13 @@ class CcNumberDelegate(QStyledItemDelegate, UpdateEditorGeometry): # {{{
val = editor.value()
if val == editor.minimum():
val = None
- model.setData(index, (val), Qt.EditRole)
+ model.setData(index, (val), Qt.ItemDataRole.EditRole)
editor.adjustSize()
def setEditorData(self, editor, index):
m = index.model()
val = m.db.data[index.row()][m.custom_columns[m.column_map[index.column()]]['rec_index']]
- if check_key_modifier(Qt.ControlModifier):
+ if check_key_modifier(Qt.KeyboardModifier.ControlModifier):
val = -1000000
elif val is None:
val = 0
@@ -569,7 +569,7 @@ class CcNumberDelegate(QStyledItemDelegate, UpdateEditorGeometry): # {{{
def get_required_width(self, editor, style, fm):
val = editor.maximum()
text = editor.textFromValue(val)
- srect = style.itemTextRect(fm, editor.geometry(), Qt.AlignLeft, False,
+ srect = style.itemTextRect(fm, editor.geometry(), Qt.AlignmentFlag.AlignLeft, False,
text + 'M')
return srect.width()
@@ -604,17 +604,17 @@ class CcEnumDelegate(QStyledItemDelegate, UpdateEditorGeometry): # {{{
val = unicode_type(editor.currentText())
if not val:
val = None
- model.setData(index, (val), Qt.EditRole)
+ model.setData(index, (val), Qt.ItemDataRole.EditRole)
def get_required_width(self, editor, style, fm):
- srect = style.itemTextRect(fm, editor.geometry(), Qt.AlignLeft, False,
+ srect = style.itemTextRect(fm, editor.geometry(), Qt.AlignmentFlag.AlignLeft, False,
self.longest_text + 'M')
return srect.width()
def setEditorData(self, editor, index):
m = index.model()
val = m.db.data[index.row()][m.custom_columns[m.column_map[index.column()]]['rec_index']]
- if val is None or check_key_modifier(Qt.ControlModifier):
+ if val is None or check_key_modifier(Qt.KeyboardModifier.ControlModifier):
val = ''
idx = editor.findText(val)
if idx < 0:
@@ -639,17 +639,17 @@ class CcCommentsDelegate(QStyledItemDelegate): # {{{
style = QApplication.style() if option.widget is None \
else option.widget.style()
self.document.setHtml(option.text)
- style.drawPrimitive(QStyle.PE_PanelItemViewItem, option, painter, widget=option.widget)
- rect = style.subElementRect(QStyle.SE_ItemViewItemDecoration, option, self.parent())
+ style.drawPrimitive(QStyle.PrimitiveElement.PE_PanelItemViewItem, option, painter, widget=option.widget)
+ rect = style.subElementRect(QStyle.SubElement.SE_ItemViewItemDecoration, option, self.parent())
ic = option.icon
if rect.isValid() and not ic.isNull():
sz = ic.actualSize(option.decorationSize)
painter.drawPixmap(rect.topLeft(), ic.pixmap(sz))
ctx = QAbstractTextDocumentLayout.PaintContext()
ctx.palette = option.palette
- if option.state & QStyle.State_Selected:
+ if option.state & QStyle.StateFlag.State_Selected:
ctx.palette.setColor(ctx.palette.Text, ctx.palette.color(ctx.palette.HighlightedText))
- textRect = style.subElementRect(QStyle.SE_ItemViewItemText, option, self.parent())
+ textRect = style.subElementRect(QStyle.SubElement.SE_ItemViewItemText, option, self.parent())
painter.save()
painter.translate(textRect.topLeft())
painter.setClipRect(textRect.translated(-textRect.topLeft()))
@@ -659,18 +659,18 @@ class CcCommentsDelegate(QStyledItemDelegate): # {{{
def createEditor(self, parent, option, index):
m = index.model()
col = m.column_map[index.column()]
- if check_key_modifier(Qt.ControlModifier):
+ if check_key_modifier(Qt.KeyboardModifier.ControlModifier):
text = ''
else:
text = m.db.data[index.row()][m.custom_columns[col]['rec_index']]
editor = CommentsDialog(parent, text, column_name=m.custom_columns[col]['name'])
d = editor.exec_()
if d:
- m.setData(index, (editor.textbox.html), Qt.EditRole)
+ m.setData(index, (editor.textbox.html), Qt.ItemDataRole.EditRole)
return None
def setModelData(self, editor, model, index):
- model.setData(index, (editor.textbox.html), Qt.EditRole)
+ model.setData(index, (editor.textbox.html), Qt.ItemDataRole.EditRole)
# }}}
@@ -710,21 +710,21 @@ class CcBoolDelegate(QStyledItemDelegate, UpdateEditorGeometry): # {{{
return editor
def get_required_width(self, editor, style, fm):
- srect = style.itemTextRect(fm, editor.geometry(), Qt.AlignLeft, False,
+ srect = style.itemTextRect(fm, editor.geometry(), Qt.AlignmentFlag.AlignLeft, False,
self.longest_text + 'M')
return srect.width() + editor.iconSize().width()
def setModelData(self, editor, model, index):
val = {0:True, 1:False, 2:None}[editor.currentIndex()]
- model.setData(index, (val), Qt.EditRole)
+ model.setData(index, (val), Qt.ItemDataRole.EditRole)
def setEditorData(self, editor, index):
m = index.model()
val = m.db.data[index.row()][m.custom_columns[m.column_map[index.column()]]['rec_index']]
if not m.db.new_api.pref('bools_are_tristate'):
- val = 1 if not val or check_key_modifier(Qt.ControlModifier) else 0
+ val = 1 if not val or check_key_modifier(Qt.KeyboardModifier.ControlModifier) else 0
else:
- val = 2 if val is None or check_key_modifier(Qt.ControlModifier) \
+ val = 2 if val is None or check_key_modifier(Qt.KeyboardModifier.ControlModifier) \
else 1 if not val else 0
editor.setCurrentIndex(val)
@@ -742,7 +742,7 @@ class CcTemplateDelegate(QStyledItemDelegate): # {{{
def createEditor(self, parent, option, index):
m = index.model()
mi = m.db.get_metadata(index.row(), index_is_id=False)
- if check_key_modifier(Qt.ControlModifier):
+ if check_key_modifier(Qt.KeyboardModifier.ControlModifier):
text = ''
else:
text = m.custom_columns[m.column_map[index.column()]]['display']['composite_template']
@@ -752,7 +752,7 @@ class CcTemplateDelegate(QStyledItemDelegate): # {{{
editor.textbox.setTabStopWidth(20)
d = editor.exec_()
if d:
- m.setData(index, (editor.rule[1]), Qt.EditRole)
+ m.setData(index, (editor.rule[1]), Qt.ItemDataRole.EditRole)
return None
# }}}
diff --git a/src/calibre/gui2/library/models.py b/src/calibre/gui2/library/models.py
index 6c0aa8f59a..6aa176292a 100644
--- a/src/calibre/gui2/library/models.py
+++ b/src/calibre/gui2/library/models.py
@@ -43,8 +43,8 @@ def human_readable(size, precision=1):
TIME_FMT = '%d %b %Y'
-ALIGNMENT_MAP = {'left': Qt.AlignLeft, 'right': Qt.AlignRight, 'center':
- Qt.AlignHCenter}
+ALIGNMENT_MAP = {'left': Qt.AlignmentFlag.AlignLeft, 'right': Qt.AlignmentFlag.AlignRight, 'center':
+ Qt.AlignmentFlag.AlignHCenter}
_default_image = None
@@ -138,7 +138,7 @@ class ColumnIcon(object): # {{{
if (os.path.exists(d)):
bm = QPixmap(d)
scaled, nw, nh = fit_image(bm.width(), bm.height(), bm.width(), dim)
- bm = bm.scaled(nw, nh, aspectRatioMode=Qt.IgnoreAspectRatio, transformMode=Qt.SmoothTransformation)
+ bm = bm.scaled(nw, nh, aspectRatioMode=Qt.AspectRatioMode.IgnoreAspectRatio, transformMode=Qt.TransformationMode.SmoothTransformation)
bm.setDevicePixelRatio(self.dpr)
icon_bitmaps.append(bm)
total_width += bm.width()
@@ -146,7 +146,7 @@ class ColumnIcon(object): # {{{
i = len(icon_bitmaps)
result = QPixmap(total_width + ((i-1)*2), dim)
result.setDevicePixelRatio(self.dpr)
- result.fill(Qt.transparent)
+ result.fill(Qt.GlobalColor.transparent)
painter = QPainter(result)
x = 0
for bm in icon_bitmaps:
@@ -501,11 +501,11 @@ class BooksModel(QAbstractTableModel): # {{{
self.searched.emit(True)
self.search_done.emit()
- def sort(self, col, order=Qt.AscendingOrder, reset=True):
+ def sort(self, col, order=Qt.SortOrder.AscendingOrder, reset=True):
if not self.db:
return
if not isinstance(order, bool):
- order = order == Qt.AscendingOrder
+ order = order == Qt.SortOrder.AscendingOrder
label = self.column_map[col]
self._sort(label, order, reset)
@@ -904,7 +904,7 @@ class BooksModel(QAbstractTableModel): # {{{
# we will get asked to display columns we don't know about. Must test for this.
if col >= len(self.column_to_dc_map):
return None
- if role == Qt.DisplayRole:
+ if role == Qt.ItemDataRole.DisplayRole:
rules = self.db.new_api.pref('column_icon_rules')
if rules:
key = self.column_map[col]
@@ -926,14 +926,14 @@ class BooksModel(QAbstractTableModel): # {{{
return None
self.icon_cache[id_][cache_index] = None
return self.column_to_dc_map[col](index.row())
- elif role == Qt.ToolTipRole:
+ elif role == Qt.ItemDataRole.ToolTipRole:
return self.column_to_tc_map[col](index.row())
- elif role == Qt.EditRole:
+ elif role == Qt.ItemDataRole.EditRole:
return self.column_to_dc_map[col](index.row())
- elif role == Qt.BackgroundRole:
+ elif role == Qt.ItemDataRole.BackgroundRole:
if self.id(index) in self.ids_to_highlight_set:
return QColor('#027524') if QApplication.instance().is_dark_theme else QColor('#b4ecb4')
- elif role == Qt.ForegroundRole:
+ elif role == Qt.ItemDataRole.ForegroundRole:
key = self.column_map[col]
id_ = self.id(index)
self.column_color.mi = None
@@ -950,7 +950,7 @@ class BooksModel(QAbstractTableModel): # {{{
cc = self.custom_columns[self.column_map[col]]['display']
colors = cc.get('enum_colors', [])
values = cc.get('enum_values', [])
- txt = unicode_type(index.data(Qt.DisplayRole) or '')
+ txt = unicode_type(index.data(Qt.ItemDataRole.DisplayRole) or '')
if len(colors) > 0 and txt in values:
try:
color = QColor(colors[values.index(txt)])
@@ -971,7 +971,7 @@ class BooksModel(QAbstractTableModel): # {{{
self.column_color.mi = None
return None
- elif role == Qt.DecorationRole:
+ elif role == Qt.ItemDataRole.DecorationRole:
default_icon = None
if self.column_to_dc_decorator_map[col] is not None:
default_icon = self.column_to_dc_decorator_map[index.column()](index.row())
@@ -1001,24 +1001,24 @@ class BooksModel(QAbstractTableModel): # {{{
return self.bool_blank_icon
self.icon_cache[id_][cache_index] = None
return default_icon
- elif role == Qt.TextAlignmentRole:
+ elif role == Qt.ItemDataRole.TextAlignmentRole:
cname = self.column_map[index.column()]
- ans = Qt.AlignVCenter | ALIGNMENT_MAP[self.alignment_map.get(cname,
+ ans = Qt.AlignmentFlag.AlignVCenter | ALIGNMENT_MAP[self.alignment_map.get(cname,
'left')]
return (ans)
- elif role == Qt.FontRole and self.styled_columns:
+ elif role == Qt.ItemDataRole.FontRole and self.styled_columns:
cname = self.column_map[index.column()]
return self.styled_columns.get(cname)
- # elif role == Qt.ToolTipRole and index.isValid():
+ # elif role == Qt.ItemDataRole.ToolTipRole and index.isValid():
# if self.column_map[index.column()] in self.editable_cols:
# return (_("Double click to edit me
"))
return None
def headerData(self, section, orientation, role):
- if orientation == Qt.Horizontal:
+ if orientation == Qt.Orientation.Horizontal:
if section >= len(self.column_map): # same problem as in data, the column_map can be wrong
return None
- if role == Qt.ToolTipRole:
+ if role == Qt.ItemDataRole.ToolTipRole:
ht = self.column_map[section]
fm = self.db.field_metadata[self.column_map[section]]
if ht == 'timestamp': # change help text because users know this field as 'date'
@@ -1033,16 +1033,16 @@ class BooksModel(QAbstractTableModel): # {{{
if cust_desc:
cust_desc = '\n' + _('Description:') + ' ' + cust_desc
return (_('The lookup/search name is "{0}"{1}{2}').format(ht, cust_desc, is_cat))
- if role == Qt.DisplayRole:
+ if role == Qt.ItemDataRole.DisplayRole:
return (self.headers[self.column_map[section]])
return None
- if DEBUG and role == Qt.ToolTipRole and orientation == Qt.Vertical:
+ if DEBUG and role == Qt.ItemDataRole.ToolTipRole and orientation == Qt.Orientation.Vertical:
col = self.db.field_metadata['uuid']['rec_index']
return (_('This book\'s UUID is "{0}"').format(self.db.data[section][col]))
- if role == Qt.DisplayRole: # orientation is vertical
+ if role == Qt.ItemDataRole.DisplayRole: # orientation is vertical
return (section+1)
- if role == Qt.DecorationRole:
+ if role == Qt.ItemDataRole.DecorationRole:
try:
return self.marked_icon if self.db.data.get_marked(self.db.data.index_to_id(section)) else self.row_decoration
except (ValueError, IndexError):
@@ -1054,10 +1054,10 @@ class BooksModel(QAbstractTableModel): # {{{
if index.isValid():
colhead = self.column_map[index.column()]
if colhead in self.editable_cols:
- flags |= Qt.ItemIsEditable
+ flags |= Qt.ItemFlag.ItemIsEditable
elif self.is_custom_column(colhead):
if self.custom_columns[colhead]['is_editable']:
- flags |= Qt.ItemIsEditable
+ flags |= Qt.ItemFlag.ItemIsEditable
return flags
def set_custom_column_data(self, row, colhead, value):
@@ -1126,7 +1126,7 @@ class BooksModel(QAbstractTableModel): # {{{
from calibre.gui2.ui import get_gui
if get_gui().shutting_down:
return False
- if role == Qt.EditRole:
+ if role == Qt.ItemDataRole.EditRole:
from calibre.gui2.ui import get_gui
try:
return self._set_data(index, value)
@@ -1427,7 +1427,7 @@ class DeviceBooksModel(BooksModel): # {{{
def flags(self, index):
if self.is_row_marked_for_deletion(index.row()):
- return Qt.NoItemFlags
+ return Qt.ItemFlag.NoItemFlags
flags = QAbstractTableModel.flags(self, index)
if index.isValid():
cname = self.column_map[index.column()]
@@ -1436,7 +1436,7 @@ class DeviceBooksModel(BooksModel): # {{{
(callable(getattr(self.db, 'supports_collections', None)) and
self.db.supports_collections() and
device_prefs['manage_device_metadata']=='manual')):
- flags |= Qt.ItemIsEditable
+ flags |= Qt.ItemFlag.ItemIsEditable
return flags
def search(self, text, reset=True):
@@ -1470,7 +1470,7 @@ class DeviceBooksModel(BooksModel): # {{{
self.search(self.last_search, reset)
def sort(self, col, order, reset=True):
- descending = order != Qt.AscendingOrder
+ descending = order != Qt.SortOrder.AscendingOrder
cname = self.column_map[col]
def author_key(x):
@@ -1646,7 +1646,7 @@ class DeviceBooksModel(BooksModel): # {{{
def data(self, index, role):
row, col = index.row(), index.column()
cname = self.column_map[col]
- if role == Qt.DisplayRole or role == Qt.EditRole:
+ if role == Qt.ItemDataRole.DisplayRole or role == Qt.ItemDataRole.EditRole:
if cname == 'title':
text = self.db[self.map[row]].title
if not text:
@@ -1677,7 +1677,7 @@ class DeviceBooksModel(BooksModel): # {{{
return (', '.join(tags))
elif DEBUG and cname == 'inlibrary':
return (self.db[self.map[row]].in_library)
- elif role == Qt.ToolTipRole and index.isValid():
+ elif role == Qt.ItemDataRole.ToolTipRole and index.isValid():
if col == 0 and hasattr(self.db[self.map[row]], 'in_library_waiting'):
return (_('Waiting for metadata to be updated'))
if self.is_row_marked_for_deletion(row):
@@ -1687,28 +1687,28 @@ class DeviceBooksModel(BooksModel): # {{{
callable(getattr(self.db, 'supports_collections', None)) and self.db.supports_collections())
):
return (_("Double click to edit me
"))
- elif role == Qt.DecorationRole and cname == 'inlibrary':
+ elif role == Qt.ItemDataRole.DecorationRole and cname == 'inlibrary':
if hasattr(self.db[self.map[row]], 'in_library_waiting'):
return (self.sync_icon)
elif self.db[self.map[row]].in_library:
return (self.bool_yes_icon)
elif self.db[self.map[row]].in_library is not None:
return (self.bool_no_icon)
- elif role == Qt.TextAlignmentRole:
+ elif role == Qt.ItemDataRole.TextAlignmentRole:
cname = self.column_map[index.column()]
- ans = Qt.AlignVCenter | ALIGNMENT_MAP[self.alignment_map.get(cname,
+ ans = Qt.AlignmentFlag.AlignVCenter | ALIGNMENT_MAP[self.alignment_map.get(cname,
'left')]
return (ans)
return None
def headerData(self, section, orientation, role):
- if role == Qt.ToolTipRole and orientation == Qt.Horizontal:
+ if role == Qt.ItemDataRole.ToolTipRole and orientation == Qt.Orientation.Horizontal:
return (_('The lookup/search name is "{0}"').format(self.column_map[section]))
- if DEBUG and role == Qt.ToolTipRole and orientation == Qt.Vertical:
+ if DEBUG and role == Qt.ItemDataRole.ToolTipRole and orientation == Qt.Orientation.Vertical:
return (_('This book\'s UUID is "{0}"').format(self.db[self.map[section]].uuid))
- if role != Qt.DisplayRole:
+ if role != Qt.ItemDataRole.DisplayRole:
return None
- if orientation == Qt.Horizontal:
+ if orientation == Qt.Orientation.Horizontal:
cname = self.column_map[section]
text = self.headers[cname]
return (text)
@@ -1720,7 +1720,7 @@ class DeviceBooksModel(BooksModel): # {{{
if get_gui().shutting_down:
return False
done = False
- if role == Qt.EditRole:
+ if role == Qt.ItemDataRole.EditRole:
row, col = index.row(), index.column()
cname = self.column_map[col]
if cname in ('size', 'timestamp', 'inlibrary'):
diff --git a/src/calibre/gui2/library/views.py b/src/calibre/gui2/library/views.py
index 6c6f8b7cb4..823bffac1b 100644
--- a/src/calibre/gui2/library/views.py
+++ b/src/calibre/gui2/library/views.py
@@ -48,11 +48,11 @@ class HeaderView(QHeaderView): # {{{
def __init__(self, *args):
QHeaderView.__init__(self, *args)
- if self.orientation() == Qt.Horizontal:
+ if self.orientation() == Qt.Orientation.Horizontal:
self.setSectionsMovable(True)
self.setSectionsClickable(True)
- self.setContextMenuPolicy(Qt.CustomContextMenu)
- self.setTextElideMode(Qt.ElideRight)
+ self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
+ self.setTextElideMode(Qt.TextElideMode.ElideRight)
self.hover = -1
self.current_font = QFont(self.font())
self.current_font.setBold(True)
@@ -74,18 +74,18 @@ class HeaderView(QHeaderView): # {{{
opt.orientation = self.orientation()
opt.fontMetrics = self.fm
model = self.parent().model()
- opt.text = unicode_type(model.headerData(logical_index, opt.orientation, Qt.DisplayRole) or '')
- if opt.orientation == Qt.Vertical:
+ opt.text = unicode_type(model.headerData(logical_index, opt.orientation, Qt.ItemDataRole.DisplayRole) or '')
+ if opt.orientation == Qt.Orientation.Vertical:
try:
- val = model.headerData(logical_index, opt.orientation, Qt.DecorationRole)
+ val = model.headerData(logical_index, opt.orientation, Qt.ItemDataRole.DecorationRole)
if val is not None:
opt.icon = val
- opt.iconAlignment = Qt.AlignVCenter
+ opt.iconAlignment = Qt.AlignmentFlag.AlignVCenter
except (IndexError, ValueError, TypeError):
pass
if self.isSortIndicatorShown():
- opt.sortIndicator = QStyleOptionHeader.SortDown
- return self.style().sizeFromContents(QStyle.CT_HeaderSection, opt, QSize(), self)
+ opt.sortIndicator = QStyleOptionHeader.SortIndicator.SortDown
+ return self.style().sizeFromContents(QStyle.ContentsType.CT_HeaderSection, opt, QSize(), self)
def paintSection(self, painter, rect, logical_index):
opt = QStyleOptionHeader()
@@ -93,41 +93,41 @@ class HeaderView(QHeaderView): # {{{
opt.rect = rect
opt.section = logical_index
opt.orientation = self.orientation()
- opt.textAlignment = Qt.AlignHCenter | Qt.AlignVCenter
+ opt.textAlignment = Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter
opt.fontMetrics = self.fm
model = self.parent().model()
style = self.style()
margin = 2 * style.pixelMetric(style.PM_HeaderMargin, None, self)
if self.isSortIndicatorShown() and self.sortIndicatorSection() == logical_index:
- opt.sortIndicator = QStyleOptionHeader.SortDown if self.sortIndicatorOrder() == Qt.AscendingOrder else QStyleOptionHeader.SortUp
+ opt.sortIndicator = QStyleOptionHeader.SortIndicator.SortDown if self.sortIndicatorOrder() == Qt.SortOrder.AscendingOrder else QStyleOptionHeader.SortIndicator.SortUp
margin += style.pixelMetric(style.PM_HeaderMarkSize, None, self)
- opt.text = unicode_type(model.headerData(logical_index, opt.orientation, Qt.DisplayRole) or '')
- if self.textElideMode() != Qt.ElideNone:
- opt.text = opt.fontMetrics.elidedText(opt.text, Qt.ElideRight, rect.width() - margin)
+ opt.text = unicode_type(model.headerData(logical_index, opt.orientation, Qt.ItemDataRole.DisplayRole) or '')
+ if self.textElideMode() != Qt.TextElideMode.ElideNone:
+ opt.text = opt.fontMetrics.elidedText(opt.text, Qt.TextElideMode.ElideRight, rect.width() - margin)
if self.isEnabled():
- opt.state |= QStyle.State_Enabled
+ opt.state |= QStyle.StateFlag.State_Enabled
if self.window().isActiveWindow():
- opt.state |= QStyle.State_Active
+ opt.state |= QStyle.StateFlag.State_Active
if self.hover == logical_index:
- opt.state |= QStyle.State_MouseOver
+ opt.state |= QStyle.StateFlag.State_MouseOver
sm = self.selectionModel()
- if opt.orientation == Qt.Vertical:
+ if opt.orientation == Qt.Orientation.Vertical:
try:
- val = model.headerData(logical_index, opt.orientation, Qt.DecorationRole)
+ val = model.headerData(logical_index, opt.orientation, Qt.ItemDataRole.DecorationRole)
if val is not None:
opt.icon = val
- opt.iconAlignment = Qt.AlignVCenter
+ opt.iconAlignment = Qt.AlignmentFlag.AlignVCenter
except (IndexError, ValueError, TypeError):
pass
if sm.isRowSelected(logical_index, QModelIndex()):
- opt.state |= QStyle.State_Sunken
+ opt.state |= QStyle.StateFlag.State_Sunken
painter.save()
if (
- (opt.orientation == Qt.Horizontal and sm.currentIndex().column() == logical_index) or (
- opt.orientation == Qt.Vertical and sm.currentIndex().row() == logical_index)):
+ (opt.orientation == Qt.Orientation.Horizontal and sm.currentIndex().column() == logical_index) or (
+ opt.orientation == Qt.Orientation.Vertical and sm.currentIndex().row() == logical_index)):
painter.setFont(self.current_font)
- self.style().drawControl(QStyle.CE_Header, opt, painter, self)
+ self.style().drawControl(QStyle.ControlElement.CE_Header, opt, painter, self)
painter.restore()
# }}}
@@ -285,9 +285,9 @@ class BooksView(QTableView): # {{{
self.setModel(self._model)
self.pin_view.setModel(self._model)
self._model.count_changed_signal.connect(self.do_row_sizing,
- type=Qt.QueuedConnection)
+ type=Qt.ConnectionType.QueuedConnection)
for wv in self, self.pin_view:
- wv.setSelectionBehavior(QAbstractItemView.SelectRows)
+ wv.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
wv.setSortingEnabled(True)
self.selectionModel().currentRowChanged.connect(self._model.current_changed)
self.selectionModel().selectionChanged.connect(self.selection_changed.emit)
@@ -297,8 +297,8 @@ class BooksView(QTableView): # {{{
# {{{ Column Header setup
self.can_add_columns = True
self.was_restored = False
- self.column_header = HeaderView(Qt.Horizontal, self)
- self.pin_view.column_header = HeaderView(Qt.Horizontal, self.pin_view)
+ self.column_header = HeaderView(Qt.Orientation.Horizontal, self)
+ self.pin_view.column_header = HeaderView(Qt.Orientation.Horizontal, self.pin_view)
self.setHorizontalHeader(self.column_header)
self.pin_view.setHorizontalHeader(self.pin_view.column_header)
self.column_header.sectionMoved.connect(self.save_state)
@@ -307,12 +307,12 @@ class BooksView(QTableView): # {{{
self.pin_view.column_header.sortIndicatorChanged.disconnect()
self.pin_view.column_header.sortIndicatorChanged.connect(self.pin_view_user_sort_requested)
self.column_header.customContextMenuRequested.connect(partial(self.show_column_header_context_menu, view=self))
- self.column_header.sectionResized.connect(self.column_resized, Qt.QueuedConnection)
+ self.column_header.sectionResized.connect(self.column_resized, Qt.ConnectionType.QueuedConnection)
if self.is_library_view:
- self.pin_view.column_header.sectionResized.connect(self.pin_view_column_resized, Qt.QueuedConnection)
+ self.pin_view.column_header.sectionResized.connect(self.pin_view_column_resized, Qt.ConnectionType.QueuedConnection)
self.pin_view.column_header.sectionMoved.connect(self.pin_view.save_state)
self.pin_view.column_header.customContextMenuRequested.connect(partial(self.show_column_header_context_menu, view=self.pin_view))
- self.row_header = HeaderView(Qt.Vertical, self)
+ self.row_header = HeaderView(Qt.Orientation.Vertical, self)
self.row_header.setSectionResizeMode(self.row_header.Fixed)
self.setVerticalHeader(self.row_header)
# }}}
@@ -320,11 +320,11 @@ class BooksView(QTableView): # {{{
self._model.database_changed.connect(self.database_changed)
hv = self.verticalHeader()
hv.setSectionsClickable(True)
- hv.setCursor(Qt.PointingHandCursor)
+ hv.setCursor(Qt.CursorShape.PointingHandCursor)
self.selected_ids = []
self._model.about_to_be_sorted.connect(self.about_to_be_sorted)
self._model.sorting_done.connect(self.sorting_done,
- type=Qt.QueuedConnection)
+ type=Qt.ConnectionType.QueuedConnection)
self.set_row_header_visibility()
self.allow_mirroring = True
if self.is_library_view:
@@ -340,7 +340,7 @@ class BooksView(QTableView): # {{{
# Pin view {{{
def set_pin_view_visibility(self, visible=False):
self.pin_view.setVisible(visible)
- self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff if visible else Qt.ScrollBarAsNeeded)
+ self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff if visible else Qt.ScrollBarPolicy.ScrollBarAsNeeded)
self.mirror_selection_between_views(self)
def mirror_selection_between_views(self, src):
@@ -349,14 +349,14 @@ class BooksView(QTableView): # {{{
if dest is self.pin_view and not dest.isVisible():
return
self.allow_mirroring = False
- dest.selectionModel().select(src.selectionModel().selection(), QItemSelectionModel.ClearAndSelect)
+ dest.selectionModel().select(src.selectionModel().selection(), QItemSelectionModel.SelectionFlag.ClearAndSelect)
ci = dest.currentIndex()
nci = src.selectionModel().currentIndex()
# Save/restore horz scroll. ci column may be scrolled out of view.
hpos = dest.horizontalScrollBar().value()
if ci.isValid():
nci = dest.model().index(nci.row(), ci.column())
- dest.selectionModel().setCurrentIndex(nci, QItemSelectionModel.NoUpdate)
+ dest.selectionModel().setCurrentIndex(nci, QItemSelectionModel.SelectionFlag.NoUpdate)
dest.horizontalScrollBar().setValue(hpos)
self.allow_mirroring = True
@@ -472,7 +472,7 @@ class BooksView(QTableView): # {{{
ans.addSeparator()
if hidden_cols:
m = ans.addMenu(_('Show column'))
- hcols = [(hcol, unicode_type(self.model().headerData(hidx, Qt.Horizontal, Qt.DisplayRole) or '')) for hcol, hidx in iteritems(hidden_cols)]
+ hcols = [(hcol, unicode_type(self.model().headerData(hidx, Qt.Orientation.Horizontal, Qt.ItemDataRole.DisplayRole) or '')) for hcol, hidx in iteritems(hidden_cols)]
hcols.sort(key=lambda x: primary_sort_key(x[1]))
for hcol, hname in hcols:
m.addAction(hname, partial(handler, action='show', column=hcol))
@@ -498,7 +498,7 @@ class BooksView(QTableView): # {{{
col = None
if idx > -1 and idx < len(self.column_map):
col = self.column_map[idx]
- name = unicode_type(self.model().headerData(idx, Qt.Horizontal, Qt.DisplayRole) or '')
+ name = unicode_type(self.model().headerData(idx, Qt.Orientation.Horizontal, Qt.ItemDataRole.DisplayRole) or '')
view.column_header_context_menu = self.create_context_menu(col, name, view)
has_context_menu = hasattr(view, 'column_header_context_menu')
if self.is_library_view and has_context_menu:
@@ -522,11 +522,11 @@ class BooksView(QTableView): # {{{
for v in views:
ch = v.column_header
ch.blockSignals(True)
- ch.setSortIndicator(logical_idx, Qt.AscendingOrder if ascending else Qt.DescendingOrder)
+ ch.setSortIndicator(logical_idx, Qt.SortOrder.AscendingOrder if ascending else Qt.SortOrder.DescendingOrder)
ch.blockSignals(False)
def sort_by_column_and_order(self, col, ascending):
- order = Qt.AscendingOrder if ascending else Qt.DescendingOrder
+ order = Qt.SortOrder.AscendingOrder if ascending else Qt.SortOrder.DescendingOrder
self.column_header.blockSignals(True)
self.column_header.setSortIndicator(col, order)
self.column_header.blockSignals(False)
@@ -534,15 +534,15 @@ class BooksView(QTableView): # {{{
if self.is_library_view:
self.set_sort_indicator(col, ascending)
- def user_sort_requested(self, col, order=Qt.AscendingOrder):
+ def user_sort_requested(self, col, order=Qt.SortOrder.AscendingOrder):
if 0 <= col < len(self.column_map):
field = self.column_map[col]
- self.intelligent_sort(field, order == Qt.AscendingOrder)
+ self.intelligent_sort(field, order == Qt.SortOrder.AscendingOrder)
- def pin_view_user_sort_requested(self, col, order=Qt.AscendingOrder):
+ def pin_view_user_sort_requested(self, col, order=Qt.SortOrder.AscendingOrder):
if col < len(self.column_map) and col >= 0:
field = self.column_map[col]
- self.intelligent_sort(field, order == Qt.AscendingOrder)
+ self.intelligent_sort(field, order == Qt.SortOrder.AscendingOrder)
def intelligent_sort(self, field, ascending):
m = self.model()
@@ -898,14 +898,14 @@ class BooksView(QTableView): # {{{
pass
sections = tuple(x for x in map(f, changed) if x is not None)
if sections:
- self.row_header.headerDataChanged(Qt.Vertical, min(sections), max(sections))
+ self.row_header.headerDataChanged(Qt.Orientation.Vertical, min(sections), max(sections))
# This is needed otherwise Qt does not always update the
# viewport correctly. See https://bugs.launchpad.net/bugs/1404697
self.row_header.viewport().update()
else:
# Marked items have either appeared or all been removed
self.model().set_row_decoration(current_marked)
- self.row_header.headerDataChanged(Qt.Vertical, 0, self.row_header.count()-1)
+ self.row_header.headerDataChanged(Qt.Orientation.Vertical, 0, self.row_header.count()-1)
self.row_header.geometriesChanged.emit()
self.set_row_header_visibility()
@@ -974,13 +974,13 @@ class BooksView(QTableView): # {{{
self.set_ondevice_column_visibility()
# incase there were marked books
self.model().set_row_decoration(set())
- self.row_header.headerDataChanged(Qt.Vertical, 0, self.row_header.count()-1)
+ self.row_header.headerDataChanged(Qt.Orientation.Vertical, 0, self.row_header.count()-1)
self.row_header.geometriesChanged.emit()
# }}}
# Context Menu {{{
def set_context_menu(self, menu, edit_collections_action):
- self.setContextMenuPolicy(Qt.DefaultContextMenu)
+ self.setContextMenuPolicy(Qt.ContextMenuPolicy.DefaultContextMenu)
self.context_menu = menu
self.alternate_views.set_context_menu(menu)
self.edit_collections_action = edit_collections_action
@@ -996,7 +996,7 @@ class BooksView(QTableView): # {{{
# }}}
def handle_mouse_press_event(self, ev):
- if QApplication.keyboardModifiers() & Qt.ShiftModifier:
+ if QApplication.keyboardModifiers() & Qt.KeyboardModifier.ShiftModifier:
# Shift-Click in QTableView is badly behaved.
index = self.indexAt(ev.pos())
if not index.isValid():
@@ -1175,15 +1175,15 @@ class BooksView(QTableView): # {{{
rows = moved
if moved > rows:
index = self.model().index(orig.row() - rows, index.column())
- elif action == QTableView.MoveHome and modifiers & Qt.ControlModifier:
+ elif action == QTableView.MoveHome and modifiers & Qt.KeyboardModifier.ControlModifier:
return self.model().index(0, orig.column())
- elif action == QTableView.MoveEnd and modifiers & Qt.ControlModifier:
+ elif action == QTableView.MoveEnd and modifiers & Qt.KeyboardModifier.ControlModifier:
return self.model().index(self.model().rowCount(QModelIndex()) - 1, orig.column())
return index
def selectionCommand(self, index, event):
- if event and event.type() == event.KeyPress and event.key() in (Qt.Key_Home, Qt.Key_End) and event.modifiers() & Qt.CTRL:
- return QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Rows
+ if event and event.type() == event.KeyPress and event.key() in (Qt.Key.Key_Home, Qt.Key.Key_End) and event.modifiers() & Qt.Modifier.CTRL:
+ return QItemSelectionModel.SelectionFlag.ClearAndSelect | QItemSelectionModel.SelectionFlag.Rows
return super(BooksView, self).selectionCommand(index, event)
def keyPressEvent(self, ev):
@@ -1329,7 +1329,7 @@ class BooksView(QTableView): # {{{
elif self._model.highlight_only:
self.clearSelection()
if self.isVisible() and getattr(txt, 'as_you_type', False) is not True:
- self.setFocus(Qt.OtherFocusReason)
+ self.setFocus(Qt.FocusReason.OtherFocusReason)
def connect_to_search_box(self, sb, search_done):
sb.search.connect(self.search_proxy)
@@ -1358,7 +1358,7 @@ class DeviceBooksView(BooksView): # {{{
BooksView.__init__(self, parent, DeviceBooksModel,
use_edit_metadata_dialog=False)
self._model.resize_rows.connect(self.do_row_sizing,
- type=Qt.QueuedConnection)
+ type=Qt.ConnectionType.QueuedConnection)
self.can_add_columns = False
self.resize_on_select = False
self.rating_delegate = None
diff --git a/src/calibre/gui2/linux_file_dialogs.py b/src/calibre/gui2/linux_file_dialogs.py
index 4a80eb7ba1..b013d90fbf 100644
--- a/src/calibre/gui2/linux_file_dialogs.py
+++ b/src/calibre/gui2/linux_file_dialogs.py
@@ -312,7 +312,7 @@ def linux_native_dialog(name):
t = Thread(name='FileDialogHelper', target=r)
t.daemon = True
t.start()
- loop.exec_(QEventLoop.ExcludeUserInputEvents)
+ loop.exec_(QEventLoop.ProcessEventsFlag.ExcludeUserInputEvents)
if ret[1] is not None:
reraise(*ret[1])
return ret[0]
diff --git a/src/calibre/gui2/listener.py b/src/calibre/gui2/listener.py
index c163c9a690..21af389ba1 100644
--- a/src/calibre/gui2/listener.py
+++ b/src/calibre/gui2/listener.py
@@ -29,7 +29,7 @@ class Listener(QLocalServer):
QLocalServer.__init__(self, parent)
self.address = address or gui_socket_address()
self.uses_filesystem = self.address[0] not in '\0\\'
- self.setSocketOptions(QLocalServer.UserAccessOption)
+ self.setSocketOptions(QLocalServer.SocketOption.UserAccessOption)
self.newConnection.connect(self.on_new_connection)
self.connection_id = count()
self.pending_messages = {}
@@ -43,12 +43,12 @@ class Listener(QLocalServer):
raise OSError(f'Could not start Listener for IPC at address @{self.address[1:]} with error: {self.errorString()}')
else:
if not self.listen(self.address):
- if self.serverError() == QAbstractSocket.AddressInUseError and self.uses_filesystem:
+ if self.serverError() == QAbstractSocket.SocketError.AddressInUseError and self.uses_filesystem:
self.removeServer(self.address)
if self.listen(self.address):
return
code = self.serverError()
- if code == QAbstractSocket.AddressInUseError:
+ if code == QAbstractSocket.SocketError.AddressInUseError:
raise OSError(errno.EADDRINUSE, os.strerror(errno.EADDRINUSE), self.address)
raise OSError(f'Could not start Listener for IPC at address {self.address} with error: {self.errorString()}')
diff --git a/src/calibre/gui2/lrf_renderer/document.py b/src/calibre/gui2/lrf_renderer/document.py
index c55e0bec96..2853e1a45e 100644
--- a/src/calibre/gui2/lrf_renderer/document.py
+++ b/src/calibre/gui2/lrf_renderer/document.py
@@ -25,7 +25,7 @@ class Pen(QPen):
def __init__(self, color, width):
QPen.__init__(self, QBrush(Color(color)), width,
- (Qt.SolidLine if width > 0 else Qt.NoPen))
+ (Qt.PenStyle.SolidLine if width > 0 else Qt.PenStyle.NoPen))
class ContentObject(object):
@@ -38,7 +38,7 @@ class ContentObject(object):
class RuledLine(QGraphicsLineItem, ContentObject):
- map = {'solid': Qt.SolidLine, 'dashed': Qt.DashLine, 'dotted': Qt.DotLine, 'double': Qt.DashDotLine}
+ map = {'solid': Qt.PenStyle.SolidLine, 'dashed': Qt.PenStyle.DashLine, 'dotted': Qt.PenStyle.DotLine, 'double': Qt.PenStyle.DashDotLine}
def __init__(self, rl):
QGraphicsLineItem.__init__(self, 0, 0, rl.linelength, 0)
@@ -82,7 +82,7 @@ class _Canvas(QGraphicsRectItem):
self.current_y, self.max_y, self.max_x = 0, height, width
self.is_full = False
pen = QPen()
- pen.setStyle(Qt.NoPen)
+ pen.setStyle(Qt.PenStyle.NoPen)
self.setPen(pen)
if not hasattr(self, 'children'):
self.children = self.childItems
@@ -156,8 +156,8 @@ class _Canvas(QGraphicsRectItem):
max_width = min(br.width(), self.max_x-x)
if br.height() > max_height or br.width() > max_width:
p = ib.pixmap()
- ib.setPixmap(p.scaled(max_width, max_height, Qt.IgnoreAspectRatio,
- Qt.SmoothTransformation))
+ ib.setPixmap(p.scaled(max_width, max_height, Qt.AspectRatioMode.IgnoreAspectRatio,
+ Qt.TransformationMode.SmoothTransformation))
br = ib.boundingRect()
ib.setParentItem(self)
ib.setPos(x, y)
@@ -220,7 +220,7 @@ class Header(Canvas):
Canvas.__init__(self, font_loader, header, logger, opts, ruby_tags, link_activated,
page_style.textwidth, page_style.headheight)
if opts.visual_debug:
- self.setPen(QPen(Qt.blue, 1, Qt.DashLine))
+ self.setPen(QPen(Qt.GlobalColor.blue, 1, Qt.PenStyle.DashLine))
class Footer(Canvas):
@@ -229,7 +229,7 @@ class Footer(Canvas):
Canvas.__init__(self, font_loader, footer, logger, opts, ruby_tags, link_activated,
page_style.textwidth, page_style.footheight)
if opts.visual_debug:
- self.setPen(QPen(Qt.blue, 1, Qt.DashLine))
+ self.setPen(QPen(Qt.GlobalColor.blue, 1, Qt.PenStyle.DashLine))
class Screen(_Canvas):
@@ -249,7 +249,7 @@ class Screen(_Canvas):
_Canvas.__init__(self, font_loader, logger, opts, width=width, height=self.footer_y+page_style.footheight)
if opts.visual_debug:
- self.setPen(QPen(Qt.red, 1, Qt.SolidLine))
+ self.setPen(QPen(Qt.GlobalColor.red, 1, Qt.PenStyle.SolidLine))
header = footer = None
if page_style.headheight > 0:
try:
@@ -289,7 +289,7 @@ class Page(_Canvas):
def __init__(self, font_loader, logger, opts, width, height):
_Canvas.__init__(self, font_loader, logger, opts, width, height)
if opts.visual_debug:
- self.setPen(QPen(Qt.cyan, 1, Qt.DashLine))
+ self.setPen(QPen(Qt.GlobalColor.cyan, 1, Qt.PenStyle.DashLine))
def id(self):
for child in self.children():
diff --git a/src/calibre/gui2/lrf_renderer/main.py b/src/calibre/gui2/lrf_renderer/main.py
index 848daf1793..f092b80786 100644
--- a/src/calibre/gui2/lrf_renderer/main.py
+++ b/src/calibre/gui2/lrf_renderer/main.py
@@ -73,7 +73,7 @@ class Main(MainWindow, Ui_MainWindow):
MainWindow.__init__(self, opts, parent)
Ui_MainWindow.__init__(self)
self.setupUi(self)
- self.setAttribute(Qt.WA_DeleteOnClose)
+ self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
self.setWindowTitle(__appname__ + _(' - LRF Viewer'))
self.logger = logger
@@ -82,7 +82,7 @@ class Main(MainWindow, Ui_MainWindow):
self.spin_box_action = self.spin_box = QSpinBox()
self.tool_bar.addWidget(self.spin_box)
self.tool_bar.addSeparator()
- self.slider_action = self.slider = QSlider(Qt.Horizontal)
+ self.slider_action = self.slider = QSlider(Qt.Orientation.Horizontal)
self.tool_bar.addWidget(self.slider)
self.tool_bar.addSeparator()
self.search = SearchBox2(self)
@@ -90,9 +90,9 @@ class Main(MainWindow, Ui_MainWindow):
self.search_action = self.tool_bar.addWidget(self.search)
self.search.search.connect(self.find)
- self.action_next_page.setShortcuts([QKeySequence.MoveToNextPage, QKeySequence(Qt.Key_Space)])
- self.action_previous_page.setShortcuts([QKeySequence.MoveToPreviousPage, QKeySequence(Qt.Key_Backspace)])
- self.action_next_match.setShortcuts(QKeySequence.FindNext)
+ self.action_next_page.setShortcuts([QKeySequence.StandardKey.MoveToNextPage, QKeySequence(Qt.Key.Key_Space)])
+ self.action_previous_page.setShortcuts([QKeySequence.StandardKey.MoveToPreviousPage, QKeySequence(Qt.Key.Key_Backspace)])
+ self.action_next_match.setShortcuts(QKeySequence.StandardKey.FindNext)
self.addAction(self.action_next_match)
self.action_next_page.triggered[(bool)].connect(self.next)
self.action_previous_page.triggered[(bool)].connect(self.previous)
@@ -104,9 +104,9 @@ class Main(MainWindow, Ui_MainWindow):
self.spin_box.valueChanged[(int)].connect(self.go_to_page)
self.slider.valueChanged[(int)].connect(self.go_to_page)
- self.graphics_view.setRenderHint(QPainter.Antialiasing, True)
- self.graphics_view.setRenderHint(QPainter.TextAntialiasing, True)
- self.graphics_view.setRenderHint(QPainter.SmoothPixmapTransform, True)
+ self.graphics_view.setRenderHint(QPainter.RenderHint.Antialiasing, True)
+ self.graphics_view.setRenderHint(QPainter.RenderHint.TextAntialiasing, True)
+ self.graphics_view.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform, True)
self.closed = False
@@ -114,7 +114,7 @@ class Main(MainWindow, Ui_MainWindow):
opts = self.opts
d = Config(self, opts)
d.exec_()
- if d.result() == QDialog.Accepted:
+ if d.result() == QDialog.DialogCode.Accepted:
gprefs['lrf_viewer_white_background'] = opts.white_background = bool(d.white_background.isChecked())
gprefs['lrf_viewer_hyphenate'] = opts.hyphenate = bool(d.hyphenate.isChecked())
@@ -128,7 +128,7 @@ class Main(MainWindow, Ui_MainWindow):
self.file_name = os.path.basename(stream.name) if hasattr(stream, 'name') else ''
self.progress_label.setText('Parsing '+ self.file_name)
self.renderer = RenderWorker(self, stream, self.logger, self.opts)
- self.renderer.finished.connect(self.parsed, type=Qt.QueuedConnection)
+ self.renderer.finished.connect(self.parsed, type=Qt.ConnectionType.QueuedConnection)
self.search.clear()
self.last_search = None
else:
@@ -195,7 +195,7 @@ class Main(MainWindow, Ui_MainWindow):
self.spin_box.setSuffix(' of %d'%(self.document.num_of_pages,))
self.spin_box.updateGeometry()
self.stack.setCurrentIndex(0)
- self.graphics_view.setFocus(Qt.OtherFocusReason)
+ self.graphics_view.setFocus(Qt.FocusReason.OtherFocusReason)
elif self.renderer.exception is not None:
exception = self.renderer.exception
print('Error rendering document', file=sys.stderr)
diff --git a/src/calibre/gui2/lrf_renderer/text.py b/src/calibre/gui2/lrf_renderer/text.py
index e19555294f..cb1da7bad9 100644
--- a/src/calibre/gui2/lrf_renderer/text.py
+++ b/src/calibre/gui2/lrf_renderer/text.py
@@ -23,19 +23,19 @@ class PixmapItem(QGraphicsPixmapItem):
def __init__(self, data, encoding, x0, y0, x1, y1, xsize, ysize):
p = QPixmap()
- p.loadFromData(data, encoding, Qt.AutoColor)
+ p.loadFromData(data, encoding, Qt.ImageConversionFlag.AutoColor)
w, h = p.width(), p.height()
p = p.copy(x0, y0, min(w, x1-x0), min(h, y1-y0))
if p.width() != xsize or p.height() != ysize:
- p = p.scaled(xsize, ysize, Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
+ p = p.scaled(xsize, ysize, Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation)
QGraphicsPixmapItem.__init__(self, p)
self.height, self.width = ysize, xsize
- self.setTransformationMode(Qt.SmoothTransformation)
- self.setShapeMode(QGraphicsPixmapItem.BoundingRectShape)
+ self.setTransformationMode(Qt.TransformationMode.SmoothTransformation)
+ self.setShapeMode(QGraphicsPixmapItem.ShapeMode.BoundingRectShape)
def resize(self, width, height):
p = self.pixmap()
- self.setPixmap(p.scaled(width, height, Qt.IgnoreAspectRatio, Qt.SmoothTransformation))
+ self.setPixmap(p.scaled(width, height, Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation))
self.width, self.height = width, height
@@ -80,7 +80,7 @@ class FontLoader(object):
if font in self.cache:
rfont = self.cache[font]
else:
- italic = font[2] == QFont.StyleItalic
+ italic = font[2] == QFont.Style.StyleItalic
rfont = QFont(font[0], font[3], font[1], italic)
rfont.setPixelSize(font[3])
rfont.setBold(wt>=69)
@@ -131,7 +131,7 @@ class TextStyle(Style):
def __init__(self, style, font_loader, ruby_tags):
self.font_loader = font_loader
- self.fontstyle = QFont.StyleNormal
+ self.fontstyle = QFont.Style.StyleNormal
for attr in ruby_tags:
setattr(self, attr, ruby_tags[attr])
Style.__init__(self, style, font_loader.dpi)
@@ -260,7 +260,7 @@ class TextBlock(object):
self.create_link(i.attrs['refobj'])
elif i.name == 'Italic':
open_containers.append((('current_style', self.current_style.copy()),))
- self.current_style.update(fontstyle=QFont.StyleItalic)
+ self.current_style.update(fontstyle=QFont.Style.StyleItalic)
elif i.name == 'Plot':
plot = Plot(i, self.font_loader.dpi)
if self.current_line is None:
@@ -340,8 +340,8 @@ class Link(QGraphicsRectItem):
self.refobj = refobj
self.slot = slot
self.brush = self.__class__.inactive_brush
- self.setPen(QPen(Qt.NoPen))
- self.setCursor(Qt.PointingHandCursor)
+ self.setPen(QPen(Qt.PenStyle.NoPen))
+ self.setCursor(Qt.CursorShape.PointingHandCursor)
self.setAcceptHoverEvents(True)
def hoverEnterEvent(self, event):
@@ -492,11 +492,11 @@ class Line(QGraphicsItem):
x, y = 0, 0+self.height-self.descent
if self.vdebug:
painter.save()
- painter.setPen(QPen(Qt.yellow, 1, Qt.DotLine))
+ painter.setPen(QPen(Qt.GlobalColor.yellow, 1, Qt.PenStyle.DotLine))
painter.drawRect(self.boundingRect())
painter.restore()
painter.save()
- painter.setPen(QPen(Qt.NoPen))
+ painter.setPen(QPen(Qt.PenStyle.NoPen))
for c in self.children():
painter.setBrush(c.brush)
painter.drawRect(c.boundingRect())
@@ -509,8 +509,8 @@ class Line(QGraphicsItem):
painter.setFont(tok.font)
if tok.highlight:
painter.save()
- painter.setPen(QPen(Qt.NoPen))
- painter.setBrush(QBrush(Qt.yellow))
+ painter.setPen(QPen(Qt.PenStyle.NoPen))
+ painter.setBrush(QBrush(Qt.GlobalColor.yellow))
painter.drawRect(x, 0, tok.width, tok.height)
painter.restore()
painter.setPen(QPen(tok.text_color))
diff --git a/src/calibre/gui2/main_window.py b/src/calibre/gui2/main_window.py
index a720a5fbde..f1f29de45d 100644
--- a/src/calibre/gui2/main_window.py
+++ b/src/calibre/gui2/main_window.py
@@ -107,8 +107,8 @@ class MainWindow(QMainWindow):
def get_menubar_actions(cls):
preferences_action = QAction(QIcon(I('config.png')), _('&Preferences'), None)
quit_action = QAction(QIcon(I('window-close.png')), _('&Quit'), None)
- preferences_action.setMenuRole(QAction.PreferencesRole)
- quit_action.setMenuRole(QAction.QuitRole)
+ preferences_action.setMenuRole(QAction.MenuRole.PreferencesRole)
+ quit_action.setMenuRole(QAction.MenuRole.QuitRole)
return preferences_action, quit_action
@property
diff --git a/src/calibre/gui2/metadata/basic_widgets.py b/src/calibre/gui2/metadata/basic_widgets.py
index 5ad6d19a22..1fc2c6f264 100644
--- a/src/calibre/gui2/metadata/basic_widgets.py
+++ b/src/calibre/gui2/metadata/basic_widgets.py
@@ -56,7 +56,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_()
@@ -156,10 +156,10 @@ def make_undoable(spinbox):
self.undo, self.redo = self.undo_stack.undo, self.undo_stack.redo
def keyPressEvent(self, ev):
- if ev == QKeySequence.Undo:
+ if ev == QKeySequence.StandardKey.Undo:
self.undo()
return ev.accept()
- if ev == QKeySequence.Redo:
+ if ev == QKeySequence.StandardKey.Redo:
self.redo()
return ev.accept()
return spinbox.keyPressEvent(self, ev)
@@ -167,12 +167,12 @@ def make_undoable(spinbox):
def contextMenuEvent(self, ev):
m = QMenu(self)
if hasattr(self, 'setDateTime'):
- m.addAction(_('Set date to undefined') + '\t' + QKeySequence(Qt.Key_Minus).toString(QKeySequence.NativeText),
+ m.addAction(_('Set date to undefined') + '\t' + QKeySequence(Qt.Key.Key_Minus).toString(QKeySequence.SequenceFormat.NativeText),
lambda : self.setDateTime(self.minimumDateTime()))
- m.addAction(_('Set date to today') + '\t' + QKeySequence(Qt.Key_Equal).toString(QKeySequence.NativeText),
+ m.addAction(_('Set date to today') + '\t' + QKeySequence(Qt.Key.Key_Equal).toString(QKeySequence.SequenceFormat.NativeText),
lambda : self.setDateTime(QDateTime.currentDateTime()))
- m.addAction(_('&Undo') + access_key(QKeySequence.Undo), self.undo).setEnabled(self.undo_stack.canUndo())
- m.addAction(_('&Redo') + access_key(QKeySequence.Redo), self.redo).setEnabled(self.undo_stack.canRedo())
+ m.addAction(_('&Undo') + access_key(QKeySequence.StandardKey.Undo), self.undo).setEnabled(self.undo_stack.canUndo())
+ m.addAction(_('&Redo') + access_key(QKeySequence.StandardKey.Redo), self.redo).setEnabled(self.undo_stack.canRedo())
m.addSeparator()
populate_standard_spinbox_context_menu(self, m)
m.popup(ev.globalPos())
@@ -270,7 +270,7 @@ class TitleSortEdit(TitleEdit, ToMetadataMixin):
'No action is required if this is what you want.'))
self.tooltips = (ok_tooltip, bad_tooltip)
- self.title_edit.textChanged.connect(self.update_state_and_val, type=Qt.QueuedConnection)
+ self.title_edit.textChanged.connect(self.update_state_and_val, type=Qt.ConnectionType.QueuedConnection)
self.textChanged.connect(self.update_state)
self.autogen_button = autogen_button
@@ -369,9 +369,9 @@ class AuthorsEdit(EditWithComplete, ToMetadataMixin):
_('You have changed the authors for this book. You must save '
'these changes before you can use Manage authors. Do you '
'want to save these changes?'))
- if d == QMessageBox.Cancel:
+ if d == QMessageBox.StandardButton.Cancel:
return
- if d == QMessageBox.Yes:
+ if d == QMessageBox.StandardButton.Yes:
self.commit(self.db, self.id_)
self.db.commit()
self.original_val = self.current_val
@@ -465,7 +465,7 @@ class AuthorSortEdit(EnLineEdit, ToMetadataMixin):
'No action is required if this is what you want.'))
self.tooltips = (ok_tooltip, bad_tooltip)
- self.authors_edit.editTextChanged.connect(self.update_state_and_val, type=Qt.QueuedConnection)
+ self.authors_edit.editTextChanged.connect(self.update_state_and_val, type=Qt.ConnectionType.QueuedConnection)
self.textChanged.connect(self.update_state)
self.textChanged.connect(self.data_changed)
@@ -722,7 +722,7 @@ class BuddyLabel(QLabel): # {{{
def __init__(self, buddy):
QLabel.__init__(self, buddy.LABEL)
self.setBuddy(buddy)
- self.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
+ self.setAlignment(Qt.AlignmentFlag.AlignRight|Qt.AlignmentFlag.AlignVCenter)
# }}}
# Formats {{{
@@ -736,7 +736,7 @@ class Format(QListWidgetItem):
self.size = float(size)/(1024*1024)
text = '%s (%.2f MB)'%(self.ext.upper(), self.size)
QListWidgetItem.__init__(self, file_icon_provider().icon_from_ext(ext),
- text, parent, QListWidgetItem.UserType)
+ text, parent, QListWidgetItem.ItemType.UserType)
if timestamp is not None:
ts = timestamp.astimezone(local_tz)
t = strftime('%a, %d %b %Y [%H:%M:%S]', ts.timetuple())
@@ -792,7 +792,7 @@ class FormatList(_FormatList):
def __init__(self, parent):
_FormatList.__init__(self, parent)
- self.setContextMenuPolicy(Qt.DefaultContextMenu)
+ self.setContextMenuPolicy(Qt.ContextMenuPolicy.DefaultContextMenu)
def contextMenuEvent(self, event):
item = self.itemFromIndex(self.currentIndex())
@@ -804,12 +804,12 @@ class FormatList(_FormatList):
if item:
action = ViewAction(item, cm)
- action.view_fmt.connect(self.view_fmt, type=Qt.QueuedConnection)
+ action.view_fmt.connect(self.view_fmt, type=Qt.ConnectionType.QueuedConnection)
cm.addAction(action)
if item.ext.upper() in EDIT_SUPPORTED:
action = EditAction(item, cm)
- action.edit_fmt.connect(self.edit_fmt, type=Qt.QueuedConnection)
+ action.edit_fmt.connect(self.edit_fmt, type=Qt.ConnectionType.QueuedConnection)
cm.addAction(action)
if item and originals:
@@ -1104,8 +1104,8 @@ class Cover(ImageView): # {{{
self.setText(text)
if icon is not None:
self.setIcon(QIcon(I(icon)))
- self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Preferred)
- self.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
+ self.setSizePolicy(QSizePolicy.Policy.MinimumExpanding, QSizePolicy.Policy.Preferred)
+ self.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
if action is not None:
self.clicked.connect(action)
@@ -1115,7 +1115,7 @@ class Cover(ImageView): # {{{
'Automatically detect and remove extra space at the cover\'s edges.\n'
'Pressing it repeatedly can sometimes remove stubborn borders.'))
b.m = m = QMenu(b)
- b.setPopupMode(QToolButton.InstantPopup)
+ b.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)
m.addAction(QIcon(I('trim.png')), _('Automatically trim borders'), self.trim_cover)
m.addSeparator()
m.addAction(_('Trim borders manually'), self.manual_trim_cover)
@@ -1135,8 +1135,8 @@ class Cover(ImageView): # {{{
self.generate_cover_button]
self.frame_size = (300, 400)
- self.setSizePolicy(QSizePolicy(QSizePolicy.Preferred,
- QSizePolicy.Preferred))
+ self.setSizePolicy(QSizePolicy(QSizePolicy.Policy.Preferred,
+ QSizePolicy.Policy.Preferred))
def undo_trim(self):
if self.cdata_before_trim:
@@ -1408,9 +1408,9 @@ class TagsEdit(EditWithComplete, ToMetadataMixin): # {{{
_('You have changed the tags. In order to use the tags'
' 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(db, id_)
db.commit()
self.original_val = self.current_val
@@ -1428,7 +1428,7 @@ class TagsEdit(EditWithComplete, ToMetadataMixin): # {{{
return True
def keyPressEvent(self, ev):
- if ev.key() == Qt.Key_F2:
+ if ev.key() == Qt.Key.Key_F2:
self.tag_editor_requested.emit()
ev.accept()
return
@@ -1717,7 +1717,7 @@ class ISBNDialog(QDialog): # {{{
w.selectAll()
w.textChanged.connect(self.checkText)
l.addWidget(w, 1, 1, 1, 1)
- w = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
+ w = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel)
l.addWidget(w, 2, 0, 1, 2)
w.accepted.connect(self.accept)
w.rejected.connect(self.reject)
@@ -1855,9 +1855,9 @@ class DateEdit(make_undoable(DateTimeEdit), ToMetadataMixin):
return o != c
def keyPressEvent(self, ev):
- if ev.key() == Qt.Key_Up and is_date_undefined(self.current_val):
+ if ev.key() == Qt.Key.Key_Up and is_date_undefined(self.current_val):
self.setDateTime(QDateTime.currentDateTime())
- elif ev.key() == Qt.Key_Tab and is_date_undefined(self.current_val):
+ elif ev.key() == Qt.Key.Key_Tab and is_date_undefined(self.current_val):
ev.ignore()
else:
return super(DateEdit, self).keyPressEvent(ev)
diff --git a/src/calibre/gui2/metadata/bulk_download.py b/src/calibre/gui2/metadata/bulk_download.py
index 6f06d92bf2..bc6f1c1f9f 100644
--- a/src/calibre/gui2/metadata/bulk_download.py
+++ b/src/calibre/gui2/metadata/bulk_download.py
@@ -83,7 +83,7 @@ class ConfirmDialog(QDialog):
l.setColumnStretch(1, 100)
self.identify = self.covers = True
- self.bb = QDialogButtonBox(QDialogButtonBox.Cancel)
+ self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel)
self.bb.rejected.connect(self.reject)
b = self.bb.addButton(_('Download only &metadata'),
self.bb.AcceptRole)
@@ -105,7 +105,7 @@ class ConfirmDialog(QDialog):
b.setIcon(QIcon(I('ok.png')))
self.resize(self.sizeHint())
- b.setFocus(Qt.OtherFocusReason)
+ b.setFocus(Qt.FocusReason.OtherFocusReason)
def only_metadata(self):
self.covers = False
diff --git a/src/calibre/gui2/metadata/config.py b/src/calibre/gui2/metadata/config.py
index 32e16ac2ea..f79a80ca6e 100644
--- a/src/calibre/gui2/metadata/config.py
+++ b/src/calibre/gui2/metadata/config.py
@@ -38,8 +38,8 @@ class FieldsModel(FM): # {{{
def state(self, field, defaults=False):
src = self.prefs.defaults if defaults else self.prefs
- return (Qt.Unchecked if field in src['ignore_fields']
- else Qt.Checked)
+ return (Qt.CheckState.Unchecked if field in src['ignore_fields']
+ else Qt.CheckState.Checked)
def restore_defaults(self):
self.beginResetModel()
@@ -50,7 +50,7 @@ class FieldsModel(FM): # {{{
ignored_fields = {x for x in self.prefs['ignore_fields'] if x not in
self.overrides}
changed = {k for k, v in iteritems(self.overrides) if v ==
- Qt.Unchecked}
+ Qt.CheckState.Unchecked}
self.prefs['ignore_fields'] = list(ignored_fields.union(changed))
# }}}
diff --git a/src/calibre/gui2/metadata/diff.py b/src/calibre/gui2/metadata/diff.py
index 41c1168c0d..5cebaa903e 100644
--- a/src/calibre/gui2/metadata/diff.py
+++ b/src/calibre/gui2/metadata/diff.py
@@ -303,7 +303,7 @@ class CoverView(QWidget):
self.metadata = metadata
self.pixmap = None
self.blank = QPixmap(I('blank.png'))
- self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.GrowFlag|QSizePolicy.ExpandFlag)
+ self.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.PolicyFlag.GrowFlag|QSizePolicy.PolicyFlag.ExpandFlag)
self.sizePolicy().setHeightForWidth(True)
@property
@@ -363,7 +363,7 @@ class CoverView(QWidget):
scaled, width, height = fit_image(pmap.width(), pmap.height(), target.width(), target.height())
target.setRect(target.x(), target.y(), width, height)
p = QPainter(self)
- p.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
+ p.setRenderHints(QPainter.RenderHint.Antialiasing | QPainter.RenderHint.SmoothPixmapTransform)
p.drawPixmap(target, pmap)
if self.pixmap is not None and not self.pixmap.isNull():
@@ -372,7 +372,7 @@ class CoverView(QWidget):
f.setBold(True)
p.setFont(f)
sz = u'\u00a0%d x %d\u00a0'%(self.pixmap.width(), self.pixmap.height())
- flags = int(Qt.AlignBottom|Qt.AlignRight|Qt.TextSingleLine)
+ flags = int(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)))
@@ -445,7 +445,7 @@ class CompareSingle(QWidget):
if field == 'identifiers':
button.m = m = QMenu(button)
button.setMenu(m)
- button.setPopupMode(QToolButton.DelayedPopup)
+ button.setPopupMode(QToolButton.ToolButtonPopupMode.DelayedPopup)
m.addAction(button.toolTip()).triggered.connect(button.click)
m.actions()[0].setIcon(button.icon())
m.addAction(_('Merge identifiers')).triggered.connect(self.merge_identifiers)
@@ -453,7 +453,7 @@ class CompareSingle(QWidget):
elif field == 'tags':
button.m = m = QMenu(button)
button.setMenu(m)
- button.setPopupMode(QToolButton.DelayedPopup)
+ button.setPopupMode(QToolButton.ToolButtonPopupMode.DelayedPopup)
m.addAction(button.toolTip()).triggered.connect(button.click)
m.actions()[0].setIcon(button.icon())
m.addAction(_('Merge tags')).triggered.connect(self.merge_tags)
@@ -556,7 +556,7 @@ class CompareMany(QDialog):
sa.setWidget(self.compare_widget)
sa.setWidgetResizable(True)
- self.bb = bb = QDialogButtonBox(QDialogButtonBox.Cancel)
+ self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel)
bb.button(bb.Cancel).setAutoDefault(False)
bb.rejected.connect(self.reject)
if self.total > 1:
@@ -576,7 +576,7 @@ class CompareMany(QDialog):
if reject_button_tooltip:
b.setToolTip(reject_button_tooltip)
self.next_action = ac = QAction(self)
- ac.setShortcut(QKeySequence(Qt.ALT | Qt.Key_Right))
+ ac.setShortcut(QKeySequence(Qt.Modifier.ALT | Qt.Key.Key_Right))
self.addAction(ac)
if action_button is not None:
self.acb = b = bb.addButton(action_button[0], bb.ActionRole)
@@ -585,7 +585,7 @@ class CompareMany(QDialog):
b.clicked.connect(self.action_button_clicked)
self.nb = b = bb.addButton(_('&Next') if self.total > 1 else _('&OK'), bb.ActionRole)
if self.total > 1:
- b.setToolTip(_('Move to next [%s]') % self.next_action.shortcut().toString(QKeySequence.NativeText))
+ b.setToolTip(_('Move to next [%s]') % self.next_action.shortcut().toString(QKeySequence.SequenceFormat.NativeText))
self.next_action.triggered.connect(b.click)
b.setIcon(QIcon(I('forward.png' if self.total > 1 else 'ok.png')))
connect_lambda(b.clicked, self, lambda self: self.next_item(True))
@@ -609,7 +609,7 @@ class CompareMany(QDialog):
geom = gprefs.get('diff_dialog_geom', None)
if geom is not None:
QApplication.instance().safe_restore_geometry(self, geom)
- b.setFocus(Qt.OtherFocusReason)
+ b.setFocus(Qt.FocusReason.OtherFocusReason)
self.next_called = False
@property
@@ -679,7 +679,7 @@ class CompareMany(QDialog):
self.accept()
def keyPressEvent(self, ev):
- if ev.key() in (Qt.Key_Enter, Qt.Key_Return):
+ if ev.key() in (Qt.Key.Key_Enter, Qt.Key.Key_Return):
ev.accept()
return
return QDialog.keyPressEvent(self, ev)
diff --git a/src/calibre/gui2/metadata/pdf_covers.py b/src/calibre/gui2/metadata/pdf_covers.py
index ca1c964640..e45536e903 100644
--- a/src/calibre/gui2/metadata/pdf_covers.py
+++ b/src/calibre/gui2/metadata/pdf_covers.py
@@ -33,8 +33,8 @@ class CoverDelegate(QStyledItemDelegate):
QStyledItemDelegate.paint(self, painter, option, index)
style = QApplication.style()
# Ensure the cover is rendered over any selection rect
- style.drawItemPixmap(painter, option.rect, Qt.AlignTop|Qt.AlignHCenter,
- QPixmap(index.data(Qt.DecorationRole)))
+ style.drawItemPixmap(painter, option.rect, Qt.AlignmentFlag.AlignTop|Qt.AlignmentFlag.AlignHCenter,
+ QPixmap(index.data(Qt.ItemDataRole.DecorationRole)))
PAGES_PER_RENDER = 10
@@ -63,15 +63,15 @@ class PDFCovers(QDialog):
c.setViewMode(c.IconMode)
c.setUniformItemSizes(True)
c.setResizeMode(c.Adjust)
- c.itemDoubleClicked.connect(self.accept, type=Qt.QueuedConnection)
+ c.itemDoubleClicked.connect(self.accept, type=Qt.ConnectionType.QueuedConnection)
- 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.more_pages = b = bb.addButton(_('&More pages'), QDialogButtonBox.ActionRole)
+ self.more_pages = b = bb.addButton(_('&More pages'), QDialogButtonBox.ButtonRole.ActionRole)
b.clicked.connect(self.start_rendering)
l.addWidget(bb)
- self.rendering_done.connect(self.show_pages, type=Qt.QueuedConnection)
+ self.rendering_done.connect(self.show_pages, type=Qt.ConnectionType.QueuedConnection)
self.first = 1
self.setWindowTitle(_('Choose cover from PDF'))
self.setWindowIcon(file_icon_provider().icon_from_ext('pdf'))
@@ -88,9 +88,9 @@ class PDFCovers(QDialog):
@property
def cover_path(self):
for item in self.covers.selectedItems():
- return unicode_type(item.data(Qt.UserRole) or '')
+ return unicode_type(item.data(Qt.ItemDataRole.UserRole) or '')
if self.covers.count() > 0:
- return unicode_type(self.covers.item(0).data(Qt.UserRole) or '')
+ return unicode_type(self.covers.item(0).data(Qt.ItemDataRole.UserRole) or '')
def cleanup(self):
try:
@@ -136,11 +136,11 @@ class PDFCovers(QDialog):
dpr = self.devicePixelRatio()
for i, f in enumerate(sorted(files)):
- p = QPixmap(f).scaled(self.covers.iconSize()*dpr, aspectRatioMode=Qt.IgnoreAspectRatio, transformMode=Qt.SmoothTransformation)
+ p = QPixmap(f).scaled(self.covers.iconSize()*dpr, aspectRatioMode=Qt.AspectRatioMode.IgnoreAspectRatio, transformMode=Qt.TransformationMode.SmoothTransformation)
p.setDevicePixelRatio(dpr)
i = QListWidgetItem(_('page %d') % (self.first + i))
- i.setData(Qt.DecorationRole, p)
- i.setData(Qt.UserRole, f)
+ i.setData(Qt.ItemDataRole.DecorationRole, p)
+ i.setData(Qt.ItemDataRole.UserRole, f)
self.covers.addItem(i)
self.first += len(files)
if len(files) == PAGES_PER_RENDER:
diff --git a/src/calibre/gui2/metadata/single.py b/src/calibre/gui2/metadata/single.py
index 3f34dce288..b29ca145b5 100644
--- a/src/calibre/gui2/metadata/single.py
+++ b/src/calibre/gui2/metadata/single.py
@@ -71,7 +71,7 @@ class MetadataSingleDialogBase(QDialog):
def setupUi(self, *args): # {{{
self.download_shortcut = QShortcut(self)
self.download_shortcut.setKey(QKeySequence('Ctrl+D',
- QKeySequence.PortableText))
+ QKeySequence.SequenceFormat.PortableText))
p = self.parent()
if hasattr(p, 'keyboard'):
kname = u'Interface Action: Edit Metadata (Edit Metadata) : menu action : download'
@@ -79,7 +79,7 @@ class MetadataSingleDialogBase(QDialog):
if sc:
self.download_shortcut.setKey(sc[0])
self.swap_title_author_shortcut = s = QShortcut(self)
- s.setKey(QKeySequence('Alt+Down', QKeySequence.PortableText))
+ s.setKey(QKeySequence('Alt+Down', QKeySequence.SequenceFormat.PortableText))
self.button_box = bb = QDialogButtonBox(self)
self.button_box.accepted.connect(self.accept)
@@ -187,7 +187,7 @@ class MetadataSingleDialogBase(QDialog):
self.swap_title_author_button = QToolButton(self)
self.swap_title_author_button.setIcon(QIcon(I('swap.png')))
self.swap_title_author_button.setToolTip(_(
- 'Swap the author and title') + ' [%s]' % self.swap_title_author_shortcut.key().toString(QKeySequence.NativeText))
+ 'Swap the author and title') + ' [%s]' % self.swap_title_author_shortcut.key().toString(QKeySequence.SequenceFormat.NativeText))
self.swap_title_author_button.clicked.connect(self.swap_title_author)
self.swap_title_author_shortcut.activated.connect(self.swap_title_author_button.click)
@@ -272,12 +272,12 @@ class MetadataSingleDialogBase(QDialog):
# center the text in a QToolButton with an icon, so we cant just set an
# icon
b.setIcon(QIcon(I('download-metadata.png')))
- b.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
+ b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
b.setMinimumHeight(b.sizeHint().height())
b.setIcon(QIcon())
b.setText(_('&Download metadata')), b.setPopupMode(b.DelayedPopup)
- b.setToolTip(_('Download metadata for this book [%s]') % self.download_shortcut.key().toString(QKeySequence.NativeText))
- b.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed))
+ b.setToolTip(_('Download metadata for this book [%s]') % self.download_shortcut.key().toString(QKeySequence.SequenceFormat.NativeText))
+ b.setSizePolicy(QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed))
self.fetch_metadata_button.clicked.connect(self.fetch_metadata)
self.fetch_metadata_menu = m = QMenu(self.fetch_metadata_button)
m.addAction(QIcon(I('edit-undo.png')), _('Undo last metadata download'), self.undo_fetch_metadata)
@@ -399,7 +399,7 @@ class MetadataSingleDialogBase(QDialog):
self.set_current_callback(id_)
self.was_data_edited = False
# Commented out as it doesn't play nice with Next, Prev buttons
- # self.fetch_metadata_button.setFocus(Qt.OtherFocusReason)
+ # self.fetch_metadata_button.setFocus(Qt.FocusReason.OtherFocusReason)
# Miscellaneous interaction methods {{{
def update_window_title(self, *args):
@@ -530,7 +530,7 @@ class MetadataSingleDialogBase(QDialog):
val = merge_two_comments(cval, val)
self.comments.set_value(val)
if fw is not None:
- fw.setFocus(Qt.OtherFocusReason)
+ fw.setFocus(Qt.FocusReason.OtherFocusReason)
def fetch_metadata(self, *args):
from calibre.ebooks.metadata.sources.update import update_sources
@@ -718,7 +718,7 @@ class MetadataSingleDialogBase(QDialog):
self.prev_button.setToolTip(tip)
self.prev_button.setEnabled(prev is not None)
self.button_box.button(self.button_box.Ok).setDefault(True)
- self.button_box.button(self.button_box.Ok).setFocus(Qt.OtherFocusReason)
+ self.button_box.button(self.button_box.Ok).setFocus(Qt.FocusReason.OtherFocusReason)
self(self.db.id(self.row_list[self.current_row]))
for w, state in iteritems(self.comments_edit_state_at_apply):
if state == 'code':
@@ -778,8 +778,8 @@ class MetadataSingleDialog(MetadataSingleDialogBase): # {{{
self.tabs.append(w)
self.central_widget.addTab(ScrollArea(w, self), _('&Custom metadata'))
l.addLayout(tl)
- l.addItem(QSpacerItem(10, 15, QSizePolicy.Expanding,
- QSizePolicy.Fixed))
+ l.addItem(QSpacerItem(10, 15, QSizePolicy.Policy.Expanding,
+ QSizePolicy.Policy.Fixed))
sto = QWidget.setTabOrder
sto(self.button_box, self.fetch_metadata_button)
@@ -815,7 +815,7 @@ class MetadataSingleDialog(MetadataSingleDialogBase): # {{{
tl.addWidget(self.formats_manager, 0, 6, 3, 1)
- self.splitter = Splitter(Qt.Horizontal, self)
+ self.splitter = Splitter(Qt.Orientation.Horizontal, self)
self.splitter.addWidget(self.cover)
self.splitter.frame_resized.connect(self.cover.frame_resized)
l.addWidget(self.splitter)
@@ -852,8 +852,8 @@ class MetadataSingleDialog(MetadataSingleDialogBase): # {{{
sto(widget, button)
l.addWidget(gb, 0, 0, 1, 3)
- self.tabs[0].spc_one = QSpacerItem(10, 10, QSizePolicy.Expanding,
- QSizePolicy.Expanding)
+ self.tabs[0].spc_one = QSpacerItem(10, 10, QSizePolicy.Policy.Expanding,
+ QSizePolicy.Policy.Expanding)
l.addItem(self.tabs[0].spc_one, 1, 0, 1, 3)
sto(self.cover.buttons[-1], self.rating)
create_row2(1, self.rating, self.clear_ratings_button)
@@ -873,8 +873,8 @@ class MetadataSingleDialog(MetadataSingleDialogBase): # {{{
create_row2(6, self.publisher, self.publisher.clear_button)
sto(self.publisher.clear_button, self.languages)
create_row2(7, self.languages)
- self.tabs[0].spc_two = QSpacerItem(10, 10, QSizePolicy.Expanding,
- QSizePolicy.Expanding)
+ self.tabs[0].spc_two = QSpacerItem(10, 10, QSizePolicy.Policy.Expanding,
+ QSizePolicy.Policy.Expanding)
l.addItem(self.tabs[0].spc_two, 9, 0, 1, 3)
l.addWidget(self.fetch_metadata_button, 10, 0, 1, 2)
l.addWidget(self.config_metadata_button, 10, 2, 1, 1)
@@ -1002,7 +1002,7 @@ class MetadataSingleDialogAlt1(MetadataSingleDialogBase): # {{{
sto(self.swap_title_author_button, self.manage_authors_button)
sto(self.manage_authors_button, self.tags_editor_button)
sto(self.tags_editor_button, self.paste_isbn_button)
- tl.addItem(QSpacerItem(1, 1, QSizePolicy.Fixed, QSizePolicy.Expanding),
+ tl.addItem(QSpacerItem(1, 1, QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Expanding),
13, 1, 1 ,1)
w = getattr(self, 'custom_metadata_widgets_parent', None)
@@ -1012,7 +1012,7 @@ class MetadataSingleDialogAlt1(MetadataSingleDialogBase): # {{{
gb.setLayout(gbl)
sr = QScrollArea(tab0)
sr.setWidgetResizable(True)
- sr.setFrameStyle(QFrame.NoFrame)
+ sr.setFrameStyle(QFrame.Shape.NoFrame)
sr.setWidget(w)
gbl.addWidget(sr)
self.tabs[0].l.addWidget(gb, 0, 1, 1, 1)
@@ -1021,8 +1021,8 @@ class MetadataSingleDialogAlt1(MetadataSingleDialogBase): # {{{
w = QGroupBox(_('&Comments'), tab0)
sp = QSizePolicy()
sp.setVerticalStretch(10)
- sp.setHorizontalPolicy(QSizePolicy.Expanding)
- sp.setVerticalPolicy(QSizePolicy.Expanding)
+ sp.setHorizontalPolicy(QSizePolicy.Policy.Expanding)
+ sp.setVerticalPolicy(QSizePolicy.Policy.Expanding)
w.setSizePolicy(sp)
l = QHBoxLayout()
w.setLayout(l)
@@ -1049,13 +1049,13 @@ class MetadataSingleDialogAlt1(MetadataSingleDialogBase): # {{{
sto(self.cover.buttons[-2], self.cover.buttons[-1])
l.addLayout(hl, 1, 0, 1, 3)
wgl.addWidget(gb)
- wgl.addItem(QSpacerItem(10, 10, QSizePolicy.Expanding,
- QSizePolicy.Expanding))
- wgl.addItem(QSpacerItem(10, 10, QSizePolicy.Expanding,
- QSizePolicy.Expanding))
+ wgl.addItem(QSpacerItem(10, 10, QSizePolicy.Policy.Expanding,
+ QSizePolicy.Policy.Expanding))
+ wgl.addItem(QSpacerItem(10, 10, QSizePolicy.Policy.Expanding,
+ QSizePolicy.Policy.Expanding))
wgl.addWidget(self.formats_manager)
- self.splitter = QSplitter(Qt.Horizontal, tab1)
+ self.splitter = QSplitter(Qt.Orientation.Horizontal, tab1)
tab1.l.addWidget(self.splitter)
self.splitter.addWidget(self.cover)
self.splitter.addWidget(wsp)
@@ -1141,7 +1141,7 @@ class MetadataSingleDialogAlt2(MetadataSingleDialogBase): # {{{
sto(self.swap_title_author_button, self.manage_authors_button)
sto(self.manage_authors_button, self.tags_editor_button)
sto(self.tags_editor_button, self.paste_isbn_button)
- tl.addItem(QSpacerItem(1, 1, QSizePolicy.Fixed, QSizePolicy.Expanding),
+ tl.addItem(QSpacerItem(1, 1, QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Expanding),
13, 1, 1 ,1)
# Custom metadata in col 1
@@ -1151,16 +1151,16 @@ class MetadataSingleDialogAlt2(MetadataSingleDialogBase): # {{{
gbl = QVBoxLayout()
gb.setLayout(gbl)
sr = QScrollArea(gb)
- sr.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
+ sr.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
sr.setWidgetResizable(True)
- sr.setFrameStyle(QFrame.NoFrame)
+ sr.setFrameStyle(QFrame.Shape.NoFrame)
sr.setWidget(w)
gbl.addWidget(sr)
l.addWidget(gb, 0, 1, 1, 1)
sp = QSizePolicy()
sp.setVerticalStretch(10)
- sp.setHorizontalPolicy(QSizePolicy.Minimum)
- sp.setVerticalPolicy(QSizePolicy.Expanding)
+ sp.setHorizontalPolicy(QSizePolicy.Policy.Minimum)
+ sp.setVerticalPolicy(QSizePolicy.Policy.Expanding)
gb.setSizePolicy(sp)
self.set_custom_metadata_tab_order()
@@ -1168,8 +1168,8 @@ class MetadataSingleDialogAlt2(MetadataSingleDialogBase): # {{{
w = QGroupBox(_('Comments'), tab0)
sp = QSizePolicy()
sp.setVerticalStretch(10)
- sp.setHorizontalPolicy(QSizePolicy.Expanding)
- sp.setVerticalPolicy(QSizePolicy.Expanding)
+ sp.setHorizontalPolicy(QSizePolicy.Policy.Expanding)
+ sp.setVerticalPolicy(QSizePolicy.Policy.Expanding)
w.setSizePolicy(sp)
lb = QHBoxLayout()
w.setLayout(lb)
@@ -1180,7 +1180,7 @@ class MetadataSingleDialogAlt2(MetadataSingleDialogBase): # {{{
gb = QGroupBox(_('Cover'), tab0)
lb = QGridLayout()
gb.setLayout(lb)
- lb.addWidget(self.cover, 0, 0, 1, 3, alignment=Qt.AlignCenter)
+ lb.addWidget(self.cover, 0, 0, 1, 3, alignment=Qt.AlignmentFlag.AlignCenter)
sto(self.manage_authors_button, self.cover.buttons[0])
for i, b in enumerate(self.cover.buttons[:3]):
lb.addWidget(b, 1, i, 1, 1)
diff --git a/src/calibre/gui2/metadata/single_download.py b/src/calibre/gui2/metadata/single_download.py
index e540cd489b..6121a2ad3f 100644
--- a/src/calibre/gui2/metadata/single_download.py
+++ b/src/calibre/gui2/metadata/single_download.py
@@ -52,9 +52,9 @@ class RichTextDelegate(QStyledItemDelegate): # {{{
def to_doc(self, index, option=None):
doc = QTextDocument()
- if option is not None and option.state & QStyle.State_Selected:
+ if option is not None and option.state & QStyle.StateFlag.State_Selected:
p = option.palette
- group = (p.Active if option.state & QStyle.State_Active else
+ group = (p.Active if option.state & QStyle.StateFlag.State_Active else
p.Inactive)
c = p.color(group, p.HighlightedText)
c = 'rgb(%d, %d, %d)'%c.getRgb()[:3]
@@ -92,8 +92,8 @@ class CoverDelegate(QStyledItemDelegate): # {{{
self.angle = 0
self.timer = QTimer(self)
self.timer.timeout.connect(self.frame_changed)
- self.dark_color = parent.palette().color(QPalette.WindowText)
- self.light_color = parent.palette().color(QPalette.Window)
+ self.dark_color = parent.palette().color(QPalette.ColorRole.WindowText)
+ self.light_color = parent.palette().color(QPalette.ColorRole.Window)
self.spinner_width = 64
def frame_changed(self, *args):
@@ -110,15 +110,15 @@ class CoverDelegate(QStyledItemDelegate): # {{{
def paint(self, painter, option, index):
QStyledItemDelegate.paint(self, painter, option, index)
style = QApplication.style()
- waiting = self.timer.isActive() and bool(index.data(Qt.UserRole))
+ waiting = self.timer.isActive() and bool(index.data(Qt.ItemDataRole.UserRole))
if waiting:
rect = QRect(0, 0, self.spinner_width, self.spinner_width)
rect.moveCenter(option.rect.center())
draw_snake_spinner(painter, rect, self.angle, self.light_color, self.dark_color)
else:
# Ensure the cover is rendered over any selection rect
- style.drawItemPixmap(painter, option.rect, Qt.AlignTop|Qt.AlignHCenter,
- QPixmap(index.data(Qt.DecorationRole)))
+ style.drawItemPixmap(painter, option.rect, Qt.AlignmentFlag.AlignTop|Qt.AlignmentFlag.AlignHCenter,
+ QPixmap(index.data(Qt.ItemDataRole.DecorationRole)))
# }}}
@@ -143,7 +143,7 @@ class ResultsModel(QAbstractTableModel): # {{{
return len(self.COLUMNS)
def headerData(self, section, orientation, role):
- if orientation == Qt.Horizontal and role == Qt.DisplayRole:
+ if orientation == Qt.Orientation.Horizontal and role == Qt.ItemDataRole.DisplayRole:
try:
return (self.COLUMNS[section])
except:
@@ -168,19 +168,19 @@ class ResultsModel(QAbstractTableModel): # {{{
book = self.results[row]
except:
return None
- if role == Qt.DisplayRole and col not in self.ICON_COLS:
+ if role == Qt.ItemDataRole.DisplayRole and col not in self.ICON_COLS:
res = self.data_as_text(book, col)
if res:
return (res)
return None
- elif role == Qt.DecorationRole and col in self.ICON_COLS:
+ elif role == Qt.ItemDataRole.DecorationRole and col in self.ICON_COLS:
if col == 3 and getattr(book, 'has_cached_cover_url', False):
return self.yes_icon
if col == 4 and book.comments:
return self.yes_icon
- elif role == Qt.UserRole:
+ elif role == Qt.ItemDataRole.UserRole:
return book
- elif role == Qt.ToolTipRole and col == 3:
+ elif role == Qt.ItemDataRole.ToolTipRole and col == 3:
return (
_('The "has cover" indication is not fully\n'
'reliable. Sometimes results marked as not\n'
@@ -189,7 +189,7 @@ class ResultsModel(QAbstractTableModel): # {{{
return None
- def sort(self, col, order=Qt.AscendingOrder):
+ def sort(self, col, order=Qt.SortOrder.AscendingOrder):
key = lambda x: x
if col == 0:
key = attrgetter('gui_rank')
@@ -208,7 +208,7 @@ class ResultsModel(QAbstractTableModel): # {{{
key = lambda x: bool(x.comments)
self.beginResetModel()
- self.results.sort(key=key, reverse=order==Qt.AscendingOrder)
+ self.results.sort(key=key, reverse=order==Qt.SortOrder.AscendingOrder)
self.endResetModel()
# }}}
@@ -237,7 +237,7 @@ class ResultsView(QTableView): # {{{
self.setItemDelegateForColumn(i, self.rt_delegate)
self.resizeRowsToContents()
self.resizeColumnsToContents()
- self.setFocus(Qt.OtherFocusReason)
+ self.setFocus(Qt.FocusReason.OtherFocusReason)
idx = self.model().index(0, 0)
if idx.isValid() and self.model().rowCount() > 0:
self.show_details(idx)
@@ -260,7 +260,7 @@ class ResultsView(QTableView): # {{{
def show_details(self, index):
f = rating_font()
- book = self.model().data(index, Qt.UserRole)
+ book = self.model().data(index, Qt.ItemDataRole.UserRole)
parts = [
'
'+
_('This plugin is useful only for Chinese'
@@ -102,7 +102,7 @@ class SourcesModel(QAbstractTableModel): # {{{
return ret
self.enabled_overrides[plugin] = int(val)
ret = True
- if col == 1 and role == Qt.EditRole:
+ if col == 1 and role == Qt.ItemDataRole.EditRole:
try:
self.cover_overrides[plugin] = max(1, int(val))
ret = True
@@ -116,14 +116,14 @@ class SourcesModel(QAbstractTableModel): # {{{
col = index.column()
ans = QAbstractTableModel.flags(self, index)
if col == 0:
- return ans | Qt.ItemIsUserCheckable
- return Qt.ItemIsEditable | ans
+ return ans | Qt.ItemFlag.ItemIsUserCheckable
+ return Qt.ItemFlag.ItemIsEditable | ans
def commit(self):
for plugin, val in iteritems(self.enabled_overrides):
- if val == Qt.Checked:
+ if val == Qt.CheckState.Checked:
enable_plugin(plugin)
- elif val == Qt.Unchecked:
+ elif val == Qt.CheckState.Unchecked:
disable_plugin(plugin)
if self.cover_overrides:
@@ -140,8 +140,8 @@ class SourcesModel(QAbstractTableModel): # {{{
def restore_defaults(self):
self.beginResetModel()
- self.enabled_overrides = dict([(p, (Qt.Unchecked if p.name in
- default_disabled_plugins else Qt.Checked)) for p in self.plugins])
+ self.enabled_overrides = dict([(p, (Qt.CheckState.Unchecked if p.name in
+ default_disabled_plugins else Qt.CheckState.Checked)) for p in self.plugins])
self.cover_overrides = dict([(p,
msprefs.defaults['cover_priorities'].get(p.name, 1))
for p in self.plugins])
@@ -189,37 +189,37 @@ class FieldsModel(QAbstractListModel): # {{{
def state(self, field, defaults=False):
src = msprefs.defaults if defaults else msprefs
- return (Qt.Unchecked if field in src['ignore_fields']
- else Qt.Checked)
+ return (Qt.CheckState.Unchecked if field in src['ignore_fields']
+ else Qt.CheckState.Checked)
def data(self, index, role):
try:
field = self.fields[index.row()]
except:
return None
- if role == Qt.DisplayRole:
+ if role == Qt.ItemDataRole.DisplayRole:
return self.descs.get(field, field)
- if role == Qt.CheckStateRole:
+ if role == Qt.ItemDataRole.CheckStateRole:
return self.overrides.get(field, self.state(field))
return None
def flags(self, index):
ans = QAbstractListModel.flags(self, index)
- return ans | Qt.ItemIsUserCheckable
+ return ans | Qt.ItemFlag.ItemIsUserCheckable
def restore_defaults(self):
self.beginResetModel()
- self.overrides = dict([(f, self.state(f, Qt.Checked)) for f in self.fields])
+ self.overrides = dict([(f, self.state(f, Qt.CheckState.Checked)) for f in self.fields])
self.endResetModel()
def select_all(self):
self.beginResetModel()
- self.overrides = dict([(f, Qt.Checked) for f in self.fields])
+ self.overrides = dict([(f, Qt.CheckState.Checked) for f in self.fields])
self.endResetModel()
def clear_all(self):
self.beginResetModel()
- self.overrides = dict([(f, Qt.Unchecked) for f in self.fields])
+ self.overrides = dict([(f, Qt.CheckState.Unchecked) for f in self.fields])
self.endResetModel()
def setData(self, index, val, role):
@@ -228,7 +228,7 @@ class FieldsModel(QAbstractListModel): # {{{
except:
return False
ret = False
- if role == Qt.CheckStateRole:
+ if role == Qt.ItemDataRole.CheckStateRole:
self.overrides[field] = int(val)
ret = True
if ret:
@@ -239,12 +239,12 @@ class FieldsModel(QAbstractListModel): # {{{
ignored_fields = {x for x in msprefs['ignore_fields'] if x not in
self.overrides}
changed = {k for k, v in iteritems(self.overrides) if v ==
- Qt.Unchecked}
+ Qt.CheckState.Unchecked}
msprefs['ignore_fields'] = list(ignored_fields.union(changed))
def user_default_state(self, field):
- return (Qt.Unchecked if field in msprefs.get('user_default_ignore_fields',[])
- else Qt.Checked)
+ return (Qt.CheckState.Unchecked if field in msprefs.get('user_default_ignore_fields',[])
+ else Qt.CheckState.Checked)
def select_user_defaults(self):
self.beginResetModel()
@@ -255,7 +255,7 @@ class FieldsModel(QAbstractListModel): # {{{
default_ignored_fields = {x for x in msprefs['user_default_ignore_fields'] if x not in
self.overrides}
changed = {k for k, v in iteritems(self.overrides) if v ==
- Qt.Unchecked}
+ Qt.CheckState.Unchecked}
msprefs['user_default_ignore_fields'] = list(default_ignored_fields.union(changed))
# }}}
@@ -274,7 +274,7 @@ class PluginConfig(QWidget): # {{{
self.setLayout(l)
self.c = c = QLabel(_('Configure %(name)s
%(desc)s') % dict(
name=plugin.name, desc=plugin.description))
- c.setAlignment(Qt.AlignHCenter)
+ c.setAlignment(Qt.AlignmentFlag.AlignHCenter)
l.addWidget(c)
self.config_widget = plugin.config_widget()
@@ -284,7 +284,7 @@ class PluginConfig(QWidget): # {{{
l.addWidget(sa)
self.bb = QDialogButtonBox(
- QDialogButtonBox.Save|QDialogButtonBox.Cancel,
+ QDialogButtonBox.StandardButton.Save|QDialogButtonBox.StandardButton.Cancel,
parent=self)
self.bb.accepted.connect(self.finished)
self.bb.rejected.connect(self.finished)
@@ -292,7 +292,7 @@ class PluginConfig(QWidget): # {{{
l.addWidget(self.bb)
self.f = QFrame(self)
- self.f.setFrameShape(QFrame.HLine)
+ self.f.setFrameShape(QFrame.Shape.HLine)
l.addWidget(self.f)
def commit(self):
@@ -338,7 +338,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
def configure_plugin(self):
for index in self.sources_view.selectionModel().selectedRows():
- plugin = self.sources_model.data(index, Qt.UserRole)
+ plugin = self.sources_model.data(index, Qt.ItemDataRole.UserRole)
if plugin is not None:
return self.do_config(plugin)
error_dialog(self, _('No source selected'),
diff --git a/src/calibre/gui2/preferences/plugboard.py b/src/calibre/gui2/preferences/plugboard.py
index afd146d62f..8affe64554 100644
--- a/src/calibre/gui2/preferences/plugboard.py
+++ b/src/calibre/gui2/preferences/plugboard.py
@@ -343,8 +343,8 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
self.refill_all_boxes()
def existing_pb_clicked(self, qitem):
- item = qitem.data(Qt.UserRole)
- if (qitem.flags() & Qt.ItemIsEnabled):
+ item = qitem.data(Qt.ItemDataRole.UserRole)
+ if (qitem.flags() & Qt.ItemFlag.ItemIsEnabled):
self.edit_format.setCurrentIndex(self.edit_format.findText(item[0]))
self.edit_device.setCurrentIndex(self.edit_device.findText(item[1]))
else:
@@ -379,9 +379,9 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
ops.append('([' + op[0] + '] -> ' + op[1] + ')')
txt = '%s:%s = %s\n'%(f, d, ', '.join(ops))
item = QListWidgetItem(txt)
- item.setData(Qt.UserRole, (f, d))
+ item.setData(Qt.ItemDataRole.UserRole, (f, d))
if d in self.disabled_devices:
- item.setFlags(item.flags() & ~Qt.ItemIsEnabled)
+ item.setFlags(item.flags() & ~Qt.ItemFlag.ItemIsEnabled)
self.existing_plugboards.addItem(item)
self.refilling = False
diff --git a/src/calibre/gui2/preferences/plugins.py b/src/calibre/gui2/preferences/plugins.py
index 060bb12192..bd99c042f5 100644
--- a/src/calibre/gui2/preferences/plugins.py
+++ b/src/calibre/gui2/preferences/plugins.py
@@ -39,7 +39,7 @@ class PluginModel(QAbstractItemModel, AdaptSQP): # {{{
SearchQueryParser.__init__(self, ['all'])
self.show_only_user_plugins = show_only_user_plugins
self.icon = QIcon(I('plugins.png'))
- p = QIcon(self.icon).pixmap(64, 64, QIcon.Disabled, QIcon.On)
+ p = QIcon(self.icon).pixmap(64, 64, QIcon.Mode.Disabled, QIcon.State.On)
self.disabled_icon = QIcon(p)
self._p = p
self.populate()
@@ -190,19 +190,19 @@ class PluginModel(QAbstractItemModel, AdaptSQP): # {{{
def flags(self, index):
if not index.isValid():
return 0
- flags = Qt.ItemIsSelectable | Qt.ItemIsEnabled
+ flags = Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEnabled
return flags
def data(self, index, role):
if not index.isValid():
return None
if index.internalId() == 0:
- if role == Qt.DisplayRole:
+ if role == Qt.ItemDataRole.DisplayRole:
return self.categories[index.row()]
else:
plugin = self.index_to_plugin(index)
disabled = is_disabled(plugin)
- if role == Qt.DisplayRole:
+ if role == Qt.ItemDataRole.DisplayRole:
ver = '.'.join(map(unicode_type, plugin.version))
desc = '\n'.join(textwrap.wrap(plugin.description, 100))
ans='%s (%s) %s %s\n%s'%(plugin.name, ver, _('by'), plugin.author, desc)
@@ -212,11 +212,11 @@ class PluginModel(QAbstractItemModel, AdaptSQP): # {{{
if disabled:
ans += _('\n\nThis plugin has been disabled')
return (ans)
- if role == Qt.DecorationRole:
+ if role == Qt.ItemDataRole.DecorationRole:
return self.disabled_icon if disabled else self.icon
- if role == Qt.ForegroundRole and disabled:
- return (QBrush(Qt.gray))
- if role == Qt.UserRole:
+ if role == Qt.ItemDataRole.ForegroundRole and disabled:
+ return (QBrush(Qt.GlobalColor.gray))
+ if role == Qt.ItemDataRole.UserRole:
return plugin
return None
@@ -263,7 +263,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
self.plugin_view.selectionModel().select(idx,
self.plugin_view.selectionModel().ClearAndSelect)
self.plugin_view.setCurrentIndex(idx)
- self.plugin_view.setFocus(Qt.OtherFocusReason)
+ self.plugin_view.setFocus(Qt.FocusReason.OtherFocusReason)
self.plugin_view.scrollTo(idx, self.plugin_view.EnsureVisible)
def find_next(self, *args):
diff --git a/src/calibre/gui2/preferences/server.py b/src/calibre/gui2/preferences/server.py
index ae294eb497..802ec5e8b0 100644
--- a/src/calibre/gui2/preferences/server.py
+++ b/src/calibre/gui2/preferences/server.py
@@ -246,7 +246,7 @@ class AdvancedTab(QWidget):
l.setFieldGrowthPolicy(l.AllNonFixedFieldsGrow)
self.widgets = []
self.widget_map = {}
- self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
+ self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
for name in sorted(options, key=lambda n: options[n].shortdoc.lower()):
if name in ('auth', 'port', 'allow_socket_preallocation', 'userdb'):
continue
@@ -458,7 +458,7 @@ class NewUser(QDialog):
self.p1, self.p2 = p1, p2 = QLineEdit(self), QLineEdit(self)
l.addRow(_('&Password:'), p1), l.addRow(_('&Repeat password:'), p2)
for p in p1, p2:
- p.setEchoMode(QLineEdit.PasswordEchoOnEdit)
+ p.setEchoMode(QLineEdit.EchoMode.PasswordEchoOnEdit)
p.setMinimumWidth(300)
if username:
p.setText(user_data[username]['pw'])
@@ -466,17 +466,17 @@ class NewUser(QDialog):
sp.stateChanged.connect(self.show_password)
l.addRow(sp)
self.bb = bb = QDialogButtonBox(
- QDialogButtonBox.Ok | QDialogButtonBox.Cancel
+ QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
)
l.addRow(bb)
bb.accepted.connect(self.accept), bb.rejected.connect(self.reject)
- (self.uw if not username else self.p1).setFocus(Qt.OtherFocusReason)
+ (self.uw if not username else self.p1).setFocus(Qt.FocusReason.OtherFocusReason)
def show_password(self):
for p in self.p1, self.p2:
p.setEchoMode(
- QLineEdit.Normal
- if self.showp.isChecked() else QLineEdit.PasswordEchoOnEdit
+ QLineEdit.EchoMode.Normal
+ if self.showp.isChecked() else QLineEdit.EchoMode.PasswordEchoOnEdit
)
@property
@@ -621,7 +621,7 @@ class ChangeRestriction(QDialog):
self.atype_changed()
self.bb = bb = QDialogButtonBox(
- QDialogButtonBox.Ok | QDialogButtonBox.Cancel
+ QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
)
bb.accepted.connect(self.accept), bb.rejected.connect(self.reject)
l.addWidget(bb)
@@ -717,9 +717,9 @@ class User(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
- self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
+ self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
self.l = l = QFormLayout(self)
- l.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
+ l.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
self.username_label = la = QLabel('')
l.addWidget(la)
self.ro_text = _('Allow {} to make &changes (i.e. grant write access)')
@@ -837,7 +837,7 @@ class Users(QWidget):
self.user_list = w = QListWidget(self)
w.setSpacing(1)
w.doubleClicked.connect(self.current_user_activated)
- w.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
+ w.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Expanding)
lp.addWidget(w)
self.user_display = u = User(self)
@@ -1161,7 +1161,7 @@ class SearchTheInternet(QWidget):
sb = self.sa.verticalScrollBar()
if sb:
sb.setValue(sb.maximum())
- self.items[-1].name_widget.setFocus(Qt.OtherFocusReason)
+ self.items[-1].name_widget.setFocus(Qt.FocusReason.OtherFocusReason)
@property
def serialized_urls(self):
@@ -1268,7 +1268,7 @@ class ConfigWidget(ConfigWidgetBase):
def start_server(self):
if not self.save_changes():
return
- self.setCursor(Qt.BusyCursor)
+ self.setCursor(Qt.CursorShape.BusyCursor)
try:
self.gui.start_content_server(check_started=False)
while (not self.server.is_running and self.server.exception is None):
@@ -1343,7 +1343,7 @@ class ConfigWidget(ConfigWidgetBase):
loc = QLabel(_('The server log files are in: {}').format(os.path.dirname(log_error_file)))
loc.setWordWrap(True)
layout.addWidget(loc)
- bx = QDialogButtonBox(QDialogButtonBox.Ok)
+ bx = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok)
layout.addWidget(bx)
bx.accepted.connect(d.accept)
b = bx.addButton(_('&Clear logs'), bx.ActionRole)
diff --git a/src/calibre/gui2/preferences/template_functions.py b/src/calibre/gui2/preferences/template_functions.py
index c2ff065e76..7171058b06 100644
--- a/src/calibre/gui2/preferences/template_functions.py
+++ b/src/calibre/gui2/preferences/template_functions.py
@@ -198,7 +198,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
'Setting it to zero means that this function cannot '
'be used in single function mode.'), det_msg='',
show=False)
- box.bb.setStandardButtons(box.bb.standardButtons() | QDialogButtonBox.Cancel)
+ box.bb.setStandardButtons(box.bb.standardButtons() | QDialogButtonBox.StandardButton.Cancel)
box.det_msg_toggle.setVisible(False)
if not box.exec_():
return
diff --git a/src/calibre/gui2/preferences/texture_chooser.py b/src/calibre/gui2/preferences/texture_chooser.py
index b61f68031a..402a9f1234 100644
--- a/src/calibre/gui2/preferences/texture_chooser.py
+++ b/src/calibre/gui2/preferences/texture_chooser.py
@@ -44,7 +44,7 @@ class TextureChooser(QDialog):
self.tdir = texture_dir()
self.images = il = QListWidget(self)
- il.itemDoubleClicked.connect(self.accept, type=Qt.QueuedConnection)
+ il.itemDoubleClicked.connect(self.accept, type=Qt.ConnectionType.QueuedConnection)
il.setIconSize(QSize(256, 256))
il.setViewMode(il.IconMode)
il.setFlow(il.LeftToRight)
@@ -57,7 +57,7 @@ class TextureChooser(QDialog):
ad.setOpenExternalLinks(True)
ad.setWordWrap(True)
l.addWidget(ad)
- 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)
b = self.add_button = bb.addButton(_('Add texture'), bb.ActionRole)
@@ -85,7 +85,7 @@ class TextureChooser(QDialog):
self.update_remove_state()
if initial:
- existing = {unicode_type(i.data(Qt.UserRole) or ''):i for i in (self.images.item(c) for c in range(self.images.count()))}
+ existing = {unicode_type(i.data(Qt.ItemDataRole.UserRole) or ''):i for i in (self.images.item(c) for c in range(self.images.count()))}
item = existing.get(initial, None)
if item is not None:
item.setSelected(True)
@@ -96,8 +96,8 @@ class TextureChooser(QDialog):
def create_item(self, data):
x = data
i = QListWidgetItem(QIcon(x['path']), x['name'], self.images)
- i.setData(Qt.UserRole, x['fname'])
- i.setData(Qt.UserRole+1, x['path'])
+ i.setData(Qt.ItemDataRole.UserRole, x['fname'])
+ i.setData(Qt.ItemDataRole.UserRole+1, x['path'])
return i
def update_remove_state(self):
@@ -116,7 +116,7 @@ class TextureChooser(QDialog):
path = path[0]
fname = os.path.basename(path)
name = fname.rpartition('.')[0]
- existing = {unicode_type(i.data(Qt.UserRole) or ''):i for i in (self.images.item(c) for c in range(self.images.count()))}
+ existing = {unicode_type(i.data(Qt.ItemDataRole.UserRole) or ''):i for i in (self.images.item(c) for c in range(self.images.count()))}
dest = os.path.join(self.tdir, fname)
with open(path, 'rb') as s, open(dest, 'wb') as f:
shutil.copyfileobj(s, f)
@@ -135,7 +135,7 @@ class TextureChooser(QDialog):
@property
def selected_fname(self):
try:
- return unicode_type(self.selected_item.data(Qt.UserRole) or '')
+ return unicode_type(self.selected_item.data(Qt.ItemDataRole.UserRole) or '')
except (AttributeError, TypeError):
pass
@@ -145,7 +145,7 @@ class TextureChooser(QDialog):
if self.selected_fname.startswith(':'):
return error_dialog(self, _('Cannot remove'),
_('Cannot remove builtin textures'), show=True)
- os.remove(unicode_type(self.selected_item.data(Qt.UserRole+1) or ''))
+ os.remove(unicode_type(self.selected_item.data(Qt.ItemDataRole.UserRole+1) or ''))
self.images.takeItem(self.images.row(self.selected_item))
diff --git a/src/calibre/gui2/preferences/toolbar.py b/src/calibre/gui2/preferences/toolbar.py
index 8999f2340a..03aa151361 100644
--- a/src/calibre/gui2/preferences/toolbar.py
+++ b/src/calibre/gui2/preferences/toolbar.py
@@ -63,13 +63,13 @@ class BaseModel(QAbstractListModel):
def data(self, index, role):
row = index.row()
action = self._data[row].action_spec
- if role == Qt.DisplayRole:
+ if role == Qt.ItemDataRole.DisplayRole:
text = action[0]
text = text.replace('&', '')
if text == _('%d books'):
text = _('Choose library')
return (text)
- if role == Qt.DecorationRole:
+ if role == Qt.ItemDataRole.DecorationRole:
if hasattr(self._data[row], 'qaction'):
icon = self._data[row].qaction.icon()
if not icon.isNull():
@@ -78,7 +78,7 @@ class BaseModel(QAbstractListModel):
if ic is None:
ic = 'blank.png'
return (QIcon(I(ic)))
- if role == Qt.ToolTipRole and action[2] is not None:
+ if role == Qt.ItemDataRole.ToolTipRole and action[2] is not None:
return (action[2])
return None
@@ -281,11 +281,11 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
self.current_actions.entered.connect(self.current_entered)
def all_entered(self, index):
- tt = self.all_actions.model().data(index, Qt.ToolTipRole) or ''
+ tt = self.all_actions.model().data(index, Qt.ItemDataRole.ToolTipRole) or ''
self.help_text.setText(tt)
def current_entered(self, index):
- tt = self.current_actions.model().data(index, Qt.ToolTipRole) or ''
+ tt = self.current_actions.model().data(index, Qt.ItemDataRole.ToolTipRole) or ''
self.help_text.setText(tt)
def what_changed(self, idx):
diff --git a/src/calibre/gui2/preferences/tweaks.py b/src/calibre/gui2/preferences/tweaks.py
index cb8dc7afdb..f13d110821 100644
--- a/src/calibre/gui2/preferences/tweaks.py
+++ b/src/calibre/gui2/preferences/tweaks.py
@@ -68,7 +68,7 @@ class Delegate(QStyledItemDelegate): # {{{
copy = QStyleOptionViewItem(opt)
copy.showDecorationSelected = True
if self.view.currentIndex() == idx:
- copy.state |= QStyle.State_HasFocus
+ copy.state |= QStyle.StateFlag.State_HasFocus
QStyledItemDelegate.paint(self, p, copy, idx)
# }}}
@@ -152,13 +152,13 @@ class Tweaks(QAbstractListModel, AdaptSQP): # {{{
tweak = self.tweaks[row]
except:
return None
- if role == Qt.DisplayRole:
+ if role == Qt.ItemDataRole.DisplayRole:
return textwrap.fill(tweak.name, 40)
- if role == Qt.FontRole and tweak.is_customized:
+ if role == Qt.ItemDataRole.FontRole and tweak.is_customized:
ans = QFont()
ans.setBold(True)
return ans
- if role == Qt.ToolTipRole:
+ if role == Qt.ItemDataRole.ToolTipRole:
tt = _('This tweak has its default value')
if tweak.is_customized:
tt = '
'+_('This tweak has been customized')
@@ -166,7 +166,7 @@ class Tweaks(QAbstractListModel, AdaptSQP): # {{{
for varn, val in iteritems(tweak.custom_values):
tt += '%s = %r\n\n'%(varn, val)
return textwrap.fill(tt)
- if role == Qt.UserRole:
+ if role == Qt.ItemDataRole.UserRole:
return tweak
return None
@@ -237,7 +237,7 @@ class Tweaks(QAbstractListModel, AdaptSQP): # {{{
return pos
def restore_to_default(self, idx):
- tweak = self.data(idx, Qt.UserRole)
+ tweak = self.data(idx, Qt.ItemDataRole.UserRole)
if tweak is not None:
tweak.restore_to_default()
self.dataChanged.emit(idx, idx)
@@ -248,7 +248,7 @@ class Tweaks(QAbstractListModel, AdaptSQP): # {{{
self.plugin_tweaks = {}
def update_tweak(self, idx, varmap):
- tweak = self.data(idx, Qt.UserRole)
+ tweak = self.data(idx, Qt.ItemDataRole.UserRole)
if tweak is not None:
tweak.update(varmap)
self.dataChanged.emit(idx, idx)
@@ -293,7 +293,7 @@ class Tweaks(QAbstractListModel, AdaptSQP): # {{{
return ans
query = lower(query)
for r in candidates:
- dat = self.data(self.index(r), Qt.UserRole)
+ dat = self.data(self.index(r), Qt.ItemDataRole.UserRole)
var_names = ' '.join(dat.default_values)
if query in lower(dat.name) or query in lower(var_names):
ans.add(r)
@@ -351,8 +351,8 @@ class PluginTweaks(QDialog): # {{{
self.l.addWidget(self.msg)
self.l.addWidget(self.edit)
self.edit.setPlainText(raw)
- self.bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel,
- Qt.Horizontal, self)
+ self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel,
+ Qt.Orientation.Horizontal, self)
self.bb.accepted.connect(self.accept)
self.bb.rejected.connect(self.reject)
self.l.addWidget(self.bb)
@@ -367,7 +367,7 @@ class TweaksView(QListView):
def __init__(self, parent=None):
QListView.__init__(self, parent)
- self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding)
+ self.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Expanding)
self.setAlternatingRowColors(True)
self.setSpacing(5)
self.setVerticalScrollMode(self.ScrollPerPixel)
@@ -434,7 +434,7 @@ class ConfigWidget(ConfigWidgetBase):
eb.g = ebg = QGridLayout(eb)
self.edit_tweak = et = QPlainTextEdit(self)
et.setMinimumWidth(400)
- et.setLineWrapMode(QPlainTextEdit.NoWrap)
+ et.setLineWrapMode(QPlainTextEdit.LineWrapMode.NoWrap)
ebg.addWidget(et, 0, 0, 1, 2)
self.restore_default_button = b = QPushButton(self)
b.setToolTip(_("Restore this tweak to its default value"))
@@ -461,7 +461,7 @@ class ConfigWidget(ConfigWidgetBase):
self.previous_button.clicked.connect(self.find_previous)
self.search.initialize('tweaks_search_history', help_text=_('Search for tweak'))
self.search.search.connect(self.find)
- self.view.setContextMenuPolicy(Qt.CustomContextMenu)
+ self.view.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.view.customContextMenuRequested.connect(self.show_context_menu)
self.copy_icon = QIcon(I('edit-copy.png'))
@@ -469,7 +469,7 @@ class ConfigWidget(ConfigWidgetBase):
idx = self.tweaks_view.currentIndex()
if not idx.isValid():
return True
- tweak = self.tweaks.data(idx, Qt.UserRole)
+ tweak = self.tweaks.data(idx, Qt.ItemDataRole.UserRole)
self.context_menu = QMenu(self)
self.context_menu.addAction(self.copy_icon,
_('Copy to clipboard'),
@@ -503,7 +503,7 @@ class ConfigWidget(ConfigWidgetBase):
def current_changed(self, current, previous):
self.tweaks_view.scrollTo(current)
- tweak = self.tweaks.data(current, Qt.UserRole)
+ tweak = self.tweaks.data(current, Qt.ItemDataRole.UserRole)
self.help.setPlainText(tweak.doc)
self.edit_tweak.setPlainText(tweak.edit_text)
@@ -518,7 +518,7 @@ class ConfigWidget(ConfigWidgetBase):
idx = self.tweaks_view.currentIndex()
if idx.isValid():
self.tweaks.restore_to_default(idx)
- tweak = self.tweaks.data(idx, Qt.UserRole)
+ tweak = self.tweaks.data(idx, Qt.ItemDataRole.UserRole)
self.edit_tweak.setPlainText(tweak.edit_text)
self.changed()
diff --git a/src/calibre/gui2/proceed.py b/src/calibre/gui2/proceed.py
index 9e6e585eeb..6581faa927 100644
--- a/src/calibre/gui2/proceed.py
+++ b/src/calibre/gui2/proceed.py
@@ -45,12 +45,12 @@ class Icon(QWidget):
def __init__(self, parent):
QWidget.__init__(self, parent)
- self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
+ self.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
self.set_icon('dialog_question.png')
self.default_icon = self.icon
self._fraction = 0.0
self.animation = a = QPropertyAnimation(self, b"fraction", self)
- a.setDuration(2000), a.setEasingCurve(QEasingCurve.Linear)
+ a.setDuration(2000), a.setEasingCurve(QEasingCurve.Type.Linear)
a.setStartValue(0.0), a.setEndValue(2.0), a.setLoopCount(10)
def set_icon(self, icon):
@@ -101,7 +101,7 @@ class ProceedQuestion(QWidget):
self._show_fraction = 0.0
self.show_animation = a = QPropertyAnimation(self, b"show_fraction", self)
- a.setDuration(1000), a.setEasingCurve(QEasingCurve.OutQuad)
+ a.setDuration(1000), a.setEasingCurve(QEasingCurve.Type.OutQuad)
a.setStartValue(0.0), a.setEndValue(1.0)
a.finished.connect(self.stop_show_animation)
self.rendered_pixmap = None
@@ -150,10 +150,10 @@ class ProceedQuestion(QWidget):
l.addWidget(self.bb)
self.ask_question.connect(self.do_ask_question,
- type=Qt.QueuedConnection)
- self.setFocusPolicy(Qt.NoFocus)
+ type=Qt.ConnectionType.QueuedConnection)
+ self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
for child in self.findChildren(QWidget):
- child.setFocusPolicy(Qt.NoFocus)
+ child.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.setFocusProxy(self.parent())
self.resize_timer = t = QTimer(self)
t.setSingleShot(True), t.setInterval(100), t.timeout.connect(self.parent_resized)
@@ -240,7 +240,7 @@ class ProceedQuestion(QWidget):
QIcon() if question.action_icon is None else question.action_icon)
# Force the button box to relayout its buttons, as button text
# might have changed
- self.bb.setOrientation(Qt.Vertical), self.bb.setOrientation(Qt.Horizontal)
+ self.bb.setOrientation(Qt.Orientation.Vertical), self.bb.setOrientation(Qt.Orientation.Horizontal)
self.det_msg.setPlainText(question.det_msg or '')
self.det_msg.setVisible(False)
self.det_msg_toggle.setVisible(bool(question.det_msg))
@@ -267,7 +267,7 @@ class ProceedQuestion(QWidget):
return
dpr = getattr(self, 'devicePixelRatioF', self.devicePixelRatio)()
- p = QImage(dpr * self.size(), QImage.Format_ARGB32_Premultiplied)
+ p = QImage(dpr * self.size(), QImage.Format.Format_ARGB32_Premultiplied)
p.setDevicePixelRatio(dpr)
# For some reason, Qt scrolls the book view when rendering this widget,
# for the very first time, so manually preserve its position
@@ -376,8 +376,8 @@ class ProceedQuestion(QWidget):
def paintEvent(self, ev):
painter = QPainter(self)
- painter.setRenderHint(QPainter.Antialiasing, True)
- painter.setRenderHint(QPainter.SmoothPixmapTransform, True)
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
+ painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform, True)
try:
if self.rendered_pixmap is None:
self.paint_background(painter)
diff --git a/src/calibre/gui2/progress_indicator/__init__.py b/src/calibre/gui2/progress_indicator/__init__.py
index 5a728391c2..96316eebf8 100644
--- a/src/calibre/gui2/progress_indicator/__init__.py
+++ b/src/calibre/gui2/progress_indicator/__init__.py
@@ -18,16 +18,16 @@ class WaitPanel(QWidget):
def __init__(self, msg, parent=None, size=256, interval=10):
QWidget.__init__(self, parent)
- self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
+ self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
self.l = l = QVBoxLayout(self)
self.spinner = ProgressIndicator(self, size, interval)
self.start, self.stop = self.spinner.start, self.spinner.stop
- l.addStretch(), l.addWidget(self.spinner, 0, Qt.AlignCenter)
+ l.addStretch(), l.addWidget(self.spinner, 0, Qt.AlignmentFlag.AlignCenter)
self.la = QLabel(msg)
f = self.la.font()
f.setPointSize(28)
self.la.setFont(f)
- l.addWidget(self.la, 0, Qt.AlignCenter), l.addStretch()
+ l.addWidget(self.la, 0, Qt.AlignmentFlag.AlignCenter), l.addStretch()
@property
def msg(self):
diff --git a/src/calibre/gui2/qt_file_dialogs.py b/src/calibre/gui2/qt_file_dialogs.py
index 696fb65235..85a99c6484 100644
--- a/src/calibre/gui2/qt_file_dialogs.py
+++ b/src/calibre/gui2/qt_file_dialogs.py
@@ -41,7 +41,7 @@ class FileDialog(QObject):
parent=None,
modal=True,
name='',
- mode=QFileDialog.ExistingFiles,
+ mode=QFileDialog.FileMode.ExistingFiles,
default_dir=u'~',
no_save_dir=False,
combine_file_and_saved_dir=False
@@ -85,27 +85,27 @@ class FileDialog(QObject):
if not isinstance(initial_dir, string_or_bytes):
initial_dir = os.path.expanduser(default_dir)
if not initial_dir or (not os.path.exists(initial_dir) and not (
- mode == QFileDialog.AnyFile and (no_save_dir or combine_file_and_saved_dir))):
+ mode == QFileDialog.FileMode.AnyFile and (no_save_dir or combine_file_and_saved_dir))):
initial_dir = select_initial_dir(initial_dir)
self.selected_files = []
use_native_dialog = 'CALIBRE_NO_NATIVE_FILEDIALOGS' not in os.environ
with sanitize_env_vars():
opts = QFileDialog.Option()
if not use_native_dialog:
- opts |= QFileDialog.DontUseNativeDialog
- if mode == QFileDialog.AnyFile:
+ opts |= QFileDialog.Option.DontUseNativeDialog
+ if mode == QFileDialog.FileMode.AnyFile:
with adapt_menubar:
f = QFileDialog.getSaveFileName(parent, title,
initial_dir, ftext, "", opts)
if f and f[0]:
self.selected_files.append(f[0])
- elif mode == QFileDialog.ExistingFile:
+ elif mode == QFileDialog.FileMode.ExistingFile:
with adapt_menubar:
f = QFileDialog.getOpenFileName(parent, title,
initial_dir, ftext, "", opts)
if f and f[0] and os.path.exists(f[0]):
self.selected_files.append(f[0])
- elif mode == QFileDialog.ExistingFiles:
+ elif mode == QFileDialog.FileMode.ExistingFiles:
with adapt_menubar:
fs = QFileDialog.getOpenFileNames(parent, title, initial_dir,
ftext, "", opts)
@@ -121,8 +121,8 @@ class FileDialog(QObject):
if f and os.path.exists(f):
self.selected_files.append(f)
else:
- if mode == QFileDialog.Directory:
- opts |= QFileDialog.ShowDirsOnly
+ if mode == QFileDialog.FileMode.Directory:
+ opts |= QFileDialog.Option.ShowDirsOnly
with adapt_menubar:
f = unicode_type(QFileDialog.getExistingDirectory(parent, title, initial_dir, opts))
if os.path.exists(f):
@@ -144,7 +144,7 @@ class FileDialog(QObject):
def choose_dir(window, name, title, default_dir='~', no_save_dir=False):
fd = FileDialog(title=title, filters=[], add_all_files_filter=False,
- parent=window, name=name, mode=QFileDialog.Directory,
+ parent=window, name=name, mode=QFileDialog.FileMode.Directory,
default_dir=default_dir, no_save_dir=no_save_dir)
dir = fd.get_files()
fd.setParent(None)
@@ -165,7 +165,7 @@ def choose_files(window, name, title,
:param all_files: If True add All files to filters.
:param select_only_single_file: If True only one file can be selected
'''
- mode = QFileDialog.ExistingFile if select_only_single_file else QFileDialog.ExistingFiles
+ mode = QFileDialog.FileMode.ExistingFile if select_only_single_file else QFileDialog.FileMode.ExistingFiles
fd = FileDialog(title=title, name=name, filters=filters, default_dir=default_dir,
parent=window, add_all_files_filter=all_files, mode=mode,
)
@@ -187,7 +187,7 @@ def choose_save_file(window, name, title, filters=[], all_files=True, initial_pa
:param initial_filename: If specified, the initially selected path is this filename in the previously used directory. Cannot be used with initial_path.
'''
kwargs = dict(title=title, name=name, filters=filters,
- parent=window, add_all_files_filter=all_files, mode=QFileDialog.AnyFile)
+ parent=window, add_all_files_filter=all_files, mode=QFileDialog.FileMode.AnyFile)
if initial_path is not None:
kwargs['no_save_dir'] = True
kwargs['default_dir'] = initial_path
@@ -205,7 +205,7 @@ def choose_save_file(window, name, title, filters=[], all_files=True, initial_pa
def choose_images(window, name, title, select_only_single_file=True, formats=None):
- mode = QFileDialog.ExistingFile if select_only_single_file else QFileDialog.ExistingFiles
+ mode = QFileDialog.FileMode.ExistingFile if select_only_single_file else QFileDialog.FileMode.ExistingFiles
if formats is None:
formats = image_extensions()
fd = FileDialog(title=title, name=name,
diff --git a/src/calibre/gui2/save.py b/src/calibre/gui2/save.py
index f980c32474..f5597fd6c0 100644
--- a/src/calibre/gui2/save.py
+++ b/src/calibre/gui2/save.py
@@ -80,7 +80,7 @@ class Saver(QObject):
self._book_id_data = {}
self.all_book_ids = frozenset(book_ids)
self.pd = ProgressDialog(_('Saving %d books...') % len(self.all_book_ids), _('Collecting metadata...'), min=0, max=0, parent=parent, icon='save.png')
- self.do_one_signal.connect(self.tick, type=Qt.QueuedConnection)
+ self.do_one_signal.connect(self.tick, type=Qt.ConnectionType.QueuedConnection)
self.do_one = self.do_one_collect
self.ids_to_collect = iter(self.all_book_ids)
self.tdir = PersistentTemporaryDirectory('_save_to_disk')
diff --git a/src/calibre/gui2/search_box.py b/src/calibre/gui2/search_box.py
index edad2304c9..59a6b7fff8 100644
--- a/src/calibre/gui2/search_box.py
+++ b/src/calibre/gui2/search_box.py
@@ -48,7 +48,7 @@ class SearchLineEdit(QLineEdit): # {{{
def contextMenuEvent(self, ev):
self.parent().normalize_state()
menu = self.createStandardContextMenu()
- menu.setAttribute(Qt.WA_DeleteOnClose)
+ menu.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
ac = menu.addAction(_('Paste and &search'))
ac.setEnabled(bool(QApplication.clipboard().text()))
ac.setIcon(QIcon(I('search.png')))
@@ -69,7 +69,7 @@ class SearchLineEdit(QLineEdit): # {{{
def paste_and_search(self):
self.paste()
- ev = QKeyEvent(QKeyEvent.KeyPress, Qt.Key_Enter, Qt.NoModifier)
+ ev = QKeyEvent(QKeyEvent.KeyPress, Qt.Key.Key_Enter, Qt.KeyboardModifier.NoModifier)
self.keyPressEvent(ev)
@pyqtSlot()
@@ -130,14 +130,14 @@ class SearchBox2(QComboBox): # {{{
c.setCompletionMode(c.PopupCompletion)
c.highlighted[native_string_type].connect(self.completer_used)
- self.line_edit.key_pressed.connect(self.key_pressed, type=Qt.DirectConnection)
+ self.line_edit.key_pressed.connect(self.key_pressed, type=Qt.ConnectionType.DirectConnection)
# QueuedConnection as workaround for https://bugreports.qt-project.org/browse/QTBUG-40807
- self.activated[native_string_type].connect(self.history_selected, type=Qt.QueuedConnection)
+ self.activated[native_string_type].connect(self.history_selected, type=Qt.ConnectionType.QueuedConnection)
self.setEditable(True)
self.as_you_type = True
self.timer = QTimer()
self.timer.setSingleShot(True)
- self.timer.timeout.connect(self.timer_event, type=Qt.QueuedConnection)
+ self.timer.timeout.connect(self.timer_event, type=Qt.ConnectionType.QueuedConnection)
self.setInsertPolicy(self.NoInsert)
self.setMaxCount(self.MAX_COUNT)
self.setSizeAdjustPolicy(self.AdjustToMinimumContentsLengthWithIcon)
@@ -145,7 +145,7 @@ class SearchBox2(QComboBox): # {{{
self._in_a_search = False
self.tool_tip_text = self.toolTip()
- def add_action(self, icon, position=QLineEdit.TrailingPosition):
+ def add_action(self, icon, position=QLineEdit.ActionPosition.TrailingPosition):
if not isinstance(icon, QIcon):
icon = QIcon(I(icon))
return self.lineEdit().addAction(icon, position)
@@ -190,7 +190,7 @@ class SearchBox2(QComboBox): # {{{
def clear_clicked(self, *args):
self.clear()
- self.setFocus(Qt.OtherFocusReason)
+ self.setFocus(Qt.FocusReason.OtherFocusReason)
def search_done(self, ok):
if isinstance(ok, string_or_bytes):
@@ -208,15 +208,15 @@ class SearchBox2(QComboBox): # {{{
# Comes from the lineEdit control
def key_pressed(self, event):
k = event.key()
- if k in (Qt.Key_Left, Qt.Key_Right, Qt.Key_Up, Qt.Key_Down,
- Qt.Key_Home, Qt.Key_End, Qt.Key_PageUp, Qt.Key_PageDown,
- Qt.Key_unknown):
+ if k in (Qt.Key.Key_Left, Qt.Key.Key_Right, Qt.Key.Key_Up, Qt.Key.Key_Down,
+ Qt.Key.Key_Home, Qt.Key.Key_End, Qt.Key.Key_PageUp, Qt.Key.Key_PageDown,
+ Qt.Key.Key_unknown):
return
self.normalize_state()
if self._in_a_search:
self.changed.emit()
self._in_a_search = False
- if event.key() in (Qt.Key_Return, Qt.Key_Enter):
+ if event.key() in (Qt.Key.Key_Return, Qt.Key.Key_Enter):
self.do_search()
self.focus_to_library.emit()
elif self.as_you_type and unicode_type(event.text()):
@@ -225,13 +225,13 @@ class SearchBox2(QComboBox): # {{{
# Comes from the combobox itself
def keyPressEvent(self, event):
k = event.key()
- if k in (Qt.Key_Enter, Qt.Key_Return):
+ if k in (Qt.Key.Key_Enter, Qt.Key.Key_Return):
return self.do_search()
- if k not in (Qt.Key_Up, Qt.Key_Down):
+ if k not in (Qt.Key.Key_Up, Qt.Key.Key_Down):
return QComboBox.keyPressEvent(self, event)
self.blockSignals(True)
self.normalize_state()
- if k == Qt.Key_Down and self.currentIndex() == 0 and not self.lineEdit().text():
+ if k == Qt.Key.Key_Down and self.currentIndex() == 0 and not self.lineEdit().text():
self.setCurrentIndex(1), self.setCurrentIndex(0)
event.accept()
else:
@@ -259,7 +259,7 @@ class SearchBox2(QComboBox): # {{{
self.search.emit(text)
if store_in_history:
- idx = self.findText(text, Qt.MatchFixedString|Qt.MatchCaseSensitive)
+ idx = self.findText(text, Qt.MatchFlag.MatchFixedString|Qt.MatchFlag.MatchCaseSensitive)
self.block_signals(True)
if idx < 0:
self.insertItem(0, text)
@@ -284,25 +284,25 @@ class SearchBox2(QComboBox): # {{{
if not store_in_history:
self.activated[native_string_type].disconnect()
try:
- self.setFocus(Qt.OtherFocusReason)
+ self.setFocus(Qt.FocusReason.OtherFocusReason)
if not txt:
self.clear()
else:
self.normalize_state()
# must turn on case sensitivity here so that tag browser strings
# are not case-insensitively replaced from history
- self.line_edit.completer().setCaseSensitivity(Qt.CaseSensitive)
+ self.line_edit.completer().setCaseSensitivity(Qt.CaseSensitivity.CaseSensitive)
self.setEditText(txt)
self.line_edit.end(False)
if emit_changed:
self.changed.emit()
self._do_search(store_in_history=store_in_history)
- self.line_edit.completer().setCaseSensitivity(Qt.CaseInsensitive)
+ self.line_edit.completer().setCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
self.focus_to_library.emit()
finally:
if not store_in_history:
# QueuedConnection as workaround for https://bugreports.qt-project.org/browse/QTBUG-40807
- self.activated[native_string_type].connect(self.history_selected, type=Qt.QueuedConnection)
+ self.activated[native_string_type].connect(self.history_selected, type=Qt.ConnectionType.QueuedConnection)
def search_as_you_type(self, enabled):
self.as_you_type = enabled
@@ -333,7 +333,7 @@ class SavedSearchBox(QComboBox): # {{{
self.line_edit = SearchLineEdit(self)
self.setLineEdit(self.line_edit)
- self.line_edit.key_pressed.connect(self.key_pressed, type=Qt.DirectConnection)
+ self.line_edit.key_pressed.connect(self.key_pressed, type=Qt.ConnectionType.DirectConnection)
self.activated[native_string_type].connect(self.saved_search_selected)
# Turn off auto-completion so that it doesn't interfere with typing
@@ -369,7 +369,7 @@ class SavedSearchBox(QComboBox): # {{{
self.line_edit.home(False)
def key_pressed(self, event):
- if event.key() in (Qt.Key_Return, Qt.Key_Enter):
+ if event.key() in (Qt.Key.Key_Return, Qt.Key.Key_Enter):
self.saved_search_selected(self.currentText())
def saved_search_selected(self, qname):
@@ -468,7 +468,7 @@ class SearchBoxMixin(object): # {{{
self.search.cleared.connect(self.search_box_cleared)
# Queued so that search.current_text will be correct
self.search.changed.connect(self.search_box_changed,
- type=Qt.QueuedConnection)
+ type=Qt.ConnectionType.QueuedConnection)
self.search.focus_to_library.connect(self.focus_to_library)
self.advanced_search_toggle_action.triggered.connect(self.do_advanced_search)
@@ -476,8 +476,8 @@ class SearchBoxMixin(object): # {{{
self.search.setMaximumWidth(self.width()-150)
self.action_focus_search = QAction(self)
shortcuts = list(
- map(lambda x:unicode_type(x.toString(QKeySequence.PortableText)),
- QKeySequence.keyBindings(QKeySequence.Find)))
+ map(lambda x:unicode_type(x.toString(QKeySequence.SequenceFormat.PortableText)),
+ QKeySequence.keyBindings(QKeySequence.StandardKey.Find)))
shortcuts += ['/', 'Alt+S']
self.keyboard.register_shortcut('start search', _('Start search'),
default_keys=shortcuts, action=self.action_focus_search)
@@ -517,7 +517,7 @@ class SearchBoxMixin(object): # {{{
self.library_view.model().set_highlight_only(config['highlight_search_matches'])
def focus_search_box(self, *args):
- self.search.setFocus(Qt.OtherFocusReason)
+ self.search.setFocus(Qt.FocusReason.OtherFocusReason)
self.search.lineEdit().selectAll()
def search_box_cleared(self):
@@ -531,7 +531,7 @@ class SearchBoxMixin(object): # {{{
def do_advanced_search(self, *args):
d = SearchDialog(self, self.library_view.model().db)
- if d.exec_() == QDialog.Accepted:
+ if d.exec_() == QDialog.DialogCode.Accepted:
self.search.set_search_string(d.search_string(), store_in_history=True)
def do_search_button(self):
@@ -539,7 +539,7 @@ class SearchBoxMixin(object): # {{{
self.focus_to_library()
def focus_to_library(self):
- self.current_view().setFocus(Qt.OtherFocusReason)
+ self.current_view().setFocus(Qt.FocusReason.OtherFocusReason)
# }}}
diff --git a/src/calibre/gui2/search_restriction_mixin.py b/src/calibre/gui2/search_restriction_mixin.py
index c9936a07d3..8ae7234eba 100644
--- a/src/calibre/gui2/search_restriction_mixin.py
+++ b/src/calibre/gui2/search_restriction_mixin.py
@@ -41,7 +41,7 @@ class SelectNames(QDialog): # {{{
l.addWidget(self._or)
l.addWidget(self._and)
- 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)
l.addWidget(self.bb)
@@ -51,7 +51,7 @@ class SelectNames(QDialog): # {{{
@property
def names(self):
for item in self._names.selectedItems():
- yield unicode_type(item.data(Qt.DisplayRole) or '')
+ yield unicode_type(item.data(Qt.ItemDataRole.DisplayRole) or '')
@property
def match_type(self):
@@ -137,7 +137,7 @@ class CreateVirtualLibrary(QDialog): # {{{
'{4}.').format(_('Authors'), _('Tags'),
_('Publishers'), ngettext('Series', 'Series', 2), _('Saved searches')))
sl.setWordWrap(True)
- sl.setTextInteractionFlags(Qt.LinksAccessibleByMouse)
+ sl.setTextInteractionFlags(Qt.TextInteractionFlag.LinksAccessibleByMouse)
sl.linkActivated.connect(self.link_activated)
gl.addWidget(sl, 3, 0, 1, 2)
gl.setRowStretch(3,10)
@@ -163,7 +163,7 @@ class CreateVirtualLibrary(QDialog): # {{{
hl.setFrameStyle(hl.StyledPanel)
gl.addWidget(hl, 0, 3, 4, 1)
- bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
+ bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
bb.accepted.connect(self.accept)
bb.rejected.connect(self.reject)
gl.addWidget(bb, 4, 0, 1, 0)
@@ -638,7 +638,7 @@ class SearchRestrictionMixin(object):
self.search.clear(emit_search=True)
self.tags_view.recount()
self.set_number_of_books_shown()
- self.current_view().setFocus(Qt.OtherFocusReason)
+ self.current_view().setFocus(Qt.FocusReason.OtherFocusReason)
self.set_window_title()
v = self.current_view()
if not v.currentIndex().isValid():
diff --git a/src/calibre/gui2/shortcuts.py b/src/calibre/gui2/shortcuts.py
index 5fd667c6dc..9711a6009b 100644
--- a/src/calibre/gui2/shortcuts.py
+++ b/src/calibre/gui2/shortcuts.py
@@ -19,10 +19,10 @@ from calibre.utils.config import XMLConfig
from calibre.utils.icu import sort_key
from polyglot.builtins import unicode_type
-DEFAULTS = Qt.UserRole
-DESCRIPTION = Qt.UserRole + 1
-CUSTOM = Qt.UserRole + 2
-KEY = Qt.UserRole + 3
+DEFAULTS = Qt.ItemDataRole.UserRole
+DESCRIPTION = Qt.ItemDataRole.UserRole + 1
+CUSTOM = Qt.ItemDataRole.UserRole + 2
+KEY = Qt.ItemDataRole.UserRole + 3
class Customize(QFrame):
@@ -31,7 +31,7 @@ class Customize(QFrame):
QFrame.__init__(self, parent)
self.setFrameShape(self.StyledPanel)
self.setFrameShadow(self.Raised)
- self.setFocusPolicy(Qt.StrongFocus)
+ self.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
self.setAutoFillBackground(True)
self.l = l = QVBoxLayout(self)
self.header = la = QLabel(self)
@@ -83,7 +83,7 @@ class Customize(QFrame):
def clear_button(self, which):
b = getattr(self, 'button%d' % which)
s = getattr(self, 'shortcut%d' % which, None)
- b.setText(_('None') if s is None else s.toString(QKeySequence.NativeText))
+ b.setText(_('None') if s is None else s.toString(QKeySequence.SequenceFormat.NativeText))
b.setFont(QFont())
def clear_clicked(self, which=0):
@@ -101,25 +101,25 @@ class Customize(QFrame):
self.clear_button(w)
button = getattr(self, 'button%d'%which)
button.setText(_('Press a key...'))
- button.setFocus(Qt.OtherFocusReason)
+ button.setFocus(Qt.FocusReason.OtherFocusReason)
font = QFont()
font.setBold(True)
button.setFont(font)
def key_press_event(self, ev, which=0):
code = ev.key()
- if self.capture == 0 or code in (0, Qt.Key_unknown,
- Qt.Key_Shift, Qt.Key_Control, Qt.Key_Alt, Qt.Key_Meta,
- Qt.Key_AltGr, Qt.Key_CapsLock, Qt.Key_NumLock, Qt.Key_ScrollLock):
+ if self.capture == 0 or code in (0, Qt.Key.Key_unknown,
+ Qt.Key.Key_Shift, Qt.Key.Key_Control, Qt.Key.Key_Alt, Qt.Key.Key_Meta,
+ Qt.Key.Key_AltGr, Qt.Key.Key_CapsLock, Qt.Key.Key_NumLock, Qt.Key.Key_ScrollLock):
return QWidget.keyPressEvent(self, ev)
- sequence = QKeySequence(code|(int(ev.modifiers()) & (~Qt.KeypadModifier)))
+ sequence = QKeySequence(code|(int(ev.modifiers()) & (~Qt.KeyboardModifier.KeypadModifier)))
setattr(self, 'shortcut%d'%which, sequence)
self.clear_button(which)
self.capture = 0
dup_desc = self.dup_check(sequence, self.key)
if dup_desc is not None:
error_dialog(self, _('Already assigned'),
- unicode_type(sequence.toString(QKeySequence.NativeText)) + ' ' +
+ unicode_type(sequence.toString(QKeySequence.SequenceFormat.NativeText)) + ' ' +
_('already assigned to') + ' ' + dup_desc, show=True)
self.clear_clicked(which=which)
@@ -155,8 +155,8 @@ class Delegate(QStyledItemDelegate):
painter.save()
painter.setClipRect(QRectF(option.rect))
if hasattr(QStyle, 'CE_ItemViewItem'):
- QApplication.style().drawControl(QStyle.CE_ItemViewItem, option, painter)
- elif option.state & QStyle.State_Selected:
+ QApplication.style().drawControl(QStyle.ControlElement.CE_ItemViewItem, option, painter)
+ elif option.state & QStyle.StateFlag.State_Selected:
painter.fillRect(option.rect, option.palette.highlight())
painter.translate(option.rect.topLeft())
self.to_doc(index).drawContents(painter)
@@ -237,11 +237,11 @@ class Shortcuts(QAbstractListModel):
def get_match(self, event_or_sequence, ignore=tuple()):
q = event_or_sequence
if isinstance(q, QKeyEvent):
- q = QKeySequence(q.key()|(int(q.modifiers()) & (~Qt.KeypadModifier)))
+ q = QKeySequence(q.key()|(int(q.modifiers()) & (~Qt.KeyboardModifier.KeypadModifier)))
for key in self.order:
if key not in ignore:
for seq in self.get_sequences(key):
- if seq.matches(q) == QKeySequence.ExactMatch:
+ if seq.matches(q) == QKeySequence.SequenceMatch.ExactMatch:
return key
return None
@@ -259,10 +259,10 @@ class Shortcuts(QAbstractListModel):
if row < 0 or row >= len(self.order):
return None
key = self.order[row]
- if role == Qt.DisplayRole:
+ if role == Qt.ItemDataRole.DisplayRole:
return self.TEMPLATE.format(self.descriptions[key],
_(' or ').join(self.get_shortcuts(key)), _('Keys'))
- if role == Qt.ToolTipRole:
+ if role == Qt.ItemDataRole.ToolTipRole:
return _('Double click to change')
if role == DEFAULTS:
return self.sequences[key]
@@ -280,14 +280,14 @@ class Shortcuts(QAbstractListModel):
def set_data(self, index, custom):
key = self.order[index.row()]
if custom:
- self.custom[key] = [unicode_type(x.toString(QKeySequence.PortableText)) for x in custom]
+ self.custom[key] = [unicode_type(x.toString(QKeySequence.SequenceFormat.PortableText)) for x in custom]
elif key in self.custom:
del self.custom[key]
def flags(self, index):
if not index.isValid():
- return Qt.ItemIsEnabled
- return QAbstractListModel.flags(self, index) | Qt.ItemIsEditable
+ return Qt.ItemFlag.ItemIsEnabled
+ return QAbstractListModel.flags(self, index) | Qt.ItemFlag.ItemIsEditable
class ShortcutConfig(QWidget):
@@ -302,7 +302,7 @@ class ShortcutConfig(QWidget):
self.delegate = Delegate()
self.view.setItemDelegate(self.delegate)
self.delegate.sizeHintChanged.connect(self.scrollTo,
- type=Qt.QueuedConnection)
+ type=Qt.ConnectionType.QueuedConnection)
def scrollTo(self, index):
self.view.scrollTo(index, self.view.EnsureVisible)
diff --git a/src/calibre/gui2/splash_screen.py b/src/calibre/gui2/splash_screen.py
index bd5c3d4714..00e18351f3 100644
--- a/src/calibre/gui2/splash_screen.py
+++ b/src/calibre/gui2/splash_screen.py
@@ -43,12 +43,12 @@ class SplashScreen(QSplashScreen):
self.dpr = QApplication.instance().devicePixelRatio()
self.pmap = QPixmap(I('library.png', allow_user_override=False))
self.pmap.setDevicePixelRatio(self.dpr)
- self.pmap = self.pmap.scaled(int(self.dpr * self.LOGO_SIZE), int(self.dpr * self.LOGO_SIZE), transformMode=Qt.SmoothTransformation)
+ self.pmap = self.pmap.scaled(int(self.dpr * self.LOGO_SIZE), int(self.dpr * self.LOGO_SIZE), transformMode=Qt.TransformationMode.SmoothTransformation)
self.light_brush = QBrush(QColor('#F6F3E9'))
self.dark_brush = QBrush(QColor('#39322B'))
pmap = QPixmap(int(self.WIDTH * self.dpr), int(self.total_height * self.dpr))
pmap.setDevicePixelRatio(self.dpr)
- pmap.fill(Qt.transparent)
+ pmap.fill(Qt.GlobalColor.transparent)
QSplashScreen.__init__(self, pmap)
self.setWindowTitle(__appname__)
@@ -72,22 +72,22 @@ class SplashScreen(QSplashScreen):
# Draw number
painter.setFont(self.num_font)
- num_width = painter.boundingRect(0, 0, 0, 0, Qt.AlignCenter | Qt.TextSingleLine, self.num_ch).width() + 12
+ num_width = painter.boundingRect(0, 0, 0, 0, Qt.AlignmentFlag.AlignCenter | Qt.TextFlag.TextSingleLine, self.num_ch).width() + 12
num_x = width - num_width
painter.setPen(QPen(QColor('#d6b865')))
- painter.drawText(num_x, y, num_width, height, Qt.AlignCenter | Qt.TextSingleLine, self.num_ch)
+ painter.drawText(num_x, y, num_width, height, Qt.AlignmentFlag.AlignCenter | Qt.TextFlag.TextSingleLine, self.num_ch)
# Draw title
x = pw + 10
width -= num_width + 5 + x
painter.setFont(self.title_font)
- painter.drawText(x, y, width, self.title_height, Qt.AlignLeft | Qt.AlignVCenter | Qt.TextSingleLine, "CALIBRE")
+ painter.drawText(x, y, width, self.title_height, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter | Qt.TextFlag.TextSingleLine, "CALIBRE")
# Draw starting up message
y += self.title_height + 5
painter.setPen(QPen(self.dark_brush.color()))
painter.setFont(self.body_font)
- br = painter.drawText(x, y, width, self.line_height, Qt.AlignLeft | Qt.AlignVCenter | Qt.TextSingleLine, _(
+ br = painter.drawText(x, y, width, self.line_height, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter | Qt.TextFlag.TextSingleLine, _(
'Starting up, please wait...'))
starting_up_bottom = br.bottom()
@@ -96,7 +96,7 @@ class SplashScreen(QSplashScreen):
if m and m.strip():
painter.setFont(self.footer_font)
b = max(starting_up_bottom + 5, bottom - self.line_height)
- painter.drawText(x, b, width, self.line_height, Qt.AlignLeft | Qt.AlignTop | Qt.TextSingleLine, m)
+ painter.drawText(x, b, width, self.line_height, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop | Qt.TextFlag.TextSingleLine, m)
painter.restore()
diff --git a/src/calibre/gui2/store/config/chooser/adv_search_builder.py b/src/calibre/gui2/store/config/chooser/adv_search_builder.py
index 61d8003fa3..003f54b137 100644
--- a/src/calibre/gui2/store/config/chooser/adv_search_builder.py
+++ b/src/calibre/gui2/store/config/chooser/adv_search_builder.py
@@ -39,9 +39,9 @@ class AdvSearchBuilderDialog(QDialog, Ui_Dialog):
def tab_changed(self, idx):
if idx == 1:
- self.tab_2_button_box.button(QDialogButtonBox.Ok).setDefault(True)
+ self.tab_2_button_box.button(QDialogButtonBox.StandardButton.Ok).setDefault(True)
else:
- self.buttonBox.button(QDialogButtonBox.Ok).setDefault(True)
+ self.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setDefault(True)
def advanced_search_button_pushed(self):
self.adv_search_used = True
diff --git a/src/calibre/gui2/store/config/chooser/chooser_dialog.py b/src/calibre/gui2/store/config/chooser/chooser_dialog.py
index dd6576e243..76c67efede 100644
--- a/src/calibre/gui2/store/config/chooser/chooser_dialog.py
+++ b/src/calibre/gui2/store/config/chooser/chooser_dialog.py
@@ -17,7 +17,7 @@ class StoreChooserDialog(QDialog):
self.setWindowTitle(_('Choose stores'))
- button_box = QDialogButtonBox(QDialogButtonBox.Close)
+ button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Close)
button_box.accepted.connect(self.accept)
button_box.rejected.connect(self.reject)
v = QVBoxLayout(self)
diff --git a/src/calibre/gui2/store/config/chooser/chooser_widget.py b/src/calibre/gui2/store/config/chooser/chooser_widget.py
index 177ed244d8..0740f00b4f 100644
--- a/src/calibre/gui2/store/config/chooser/chooser_widget.py
+++ b/src/calibre/gui2/store/config/chooser/chooser_widget.py
@@ -19,9 +19,9 @@ class StoreChooserWidget(QWidget, Ui_Form):
self.setupUi(self)
self.query.initialize('store_config_chooser_query')
- self.query.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLengthWithIcon)
+ self.query.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon)
self.query.setMinimumContentsLength(25)
- self.adv_search_action = ac = self.query.lineEdit().addAction(QIcon(I('gear.png')), QLineEdit.LeadingPosition)
+ self.adv_search_action = ac = self.query.lineEdit().addAction(QIcon(I('gear.png')), QLineEdit.ActionPosition.LeadingPosition)
ac.triggered.connect(self.build_adv_search)
ac.setToolTip(_('Advanced search'))
self.search.clicked.connect(self.do_search)
@@ -35,5 +35,5 @@ class StoreChooserWidget(QWidget, Ui_Form):
def build_adv_search(self):
adv = AdvSearchBuilderDialog(self)
- if adv.exec_() == QDialog.Accepted:
+ if adv.exec_() == QDialog.DialogCode.Accepted:
self.query.setText(adv.search_string())
diff --git a/src/calibre/gui2/store/config/chooser/models.py b/src/calibre/gui2/store/config/chooser/models.py
index e9f9ef5bb4..bd4fe77e1f 100644
--- a/src/calibre/gui2/store/config/chooser/models.py
+++ b/src/calibre/gui2/store/config/chooser/models.py
@@ -22,7 +22,7 @@ from polyglot.builtins import range, unicode_type
class Delegate(QStyledItemDelegate):
def paint(self, painter, option, index):
- icon = index.data(Qt.DecorationRole)
+ icon = index.data(Qt.ItemDataRole.DecorationRole)
if icon and not icon.isNull():
QStyledItemDelegate.paint(self, painter, option, QModelIndex())
pw, ph = option.rect.width(), option.rect.height()
@@ -57,7 +57,7 @@ class Matches(QAbstractItemModel):
self.search_filter = SearchFilter(self.all_matches)
self.sort_col = 1
- self.sort_order = Qt.AscendingOrder
+ self.sort_order = Qt.SortOrder.AscendingOrder
def get_plugin(self, index):
row = index.row()
@@ -82,13 +82,13 @@ class Matches(QAbstractItemModel):
for i in range(len(self.matches)):
index = self.createIndex(i, 0)
data = (True)
- self.setData(index, data, Qt.CheckStateRole)
+ self.setData(index, data, Qt.ItemDataRole.CheckStateRole)
def enable_none(self):
for i in range(len(self.matches)):
index = self.createIndex(i, 0)
data = (False)
- self.setData(index, data, Qt.CheckStateRole)
+ self.setData(index, data, Qt.ItemDataRole.CheckStateRole)
def enable_invert(self):
for i in range(len(self.matches)):
@@ -97,7 +97,7 @@ class Matches(QAbstractItemModel):
def toggle_plugin(self, index):
new_index = self.createIndex(index.row(), 0)
data = (is_disabled(self.get_plugin(index)))
- self.setData(new_index, data, Qt.CheckStateRole)
+ self.setData(new_index, data, Qt.ItemDataRole.CheckStateRole)
def index(self, row, column, parent=QModelIndex()):
return self.createIndex(row, column)
@@ -114,10 +114,10 @@ class Matches(QAbstractItemModel):
return len(self.HEADERS)
def headerData(self, section, orientation, role):
- if role != Qt.DisplayRole:
+ if role != Qt.ItemDataRole.DisplayRole:
return None
text = ''
- if orientation == Qt.Horizontal:
+ if orientation == Qt.Orientation.Horizontal:
if section < len(self.HEADERS):
text = self.HEADERS[section]
return (text)
@@ -127,30 +127,30 @@ class Matches(QAbstractItemModel):
def data(self, index, role):
row, col = index.row(), index.column()
result = self.matches[row]
- if role in (Qt.DisplayRole, Qt.EditRole):
+ if role in (Qt.ItemDataRole.DisplayRole, Qt.ItemDataRole.EditRole):
if col == 1:
return ('%s
%s' % (result.name, result.description))
elif col == 3:
return (result.headquarters)
elif col == 5:
return (', '.join(result.formats).upper())
- elif role == Qt.DecorationRole:
+ elif role == Qt.ItemDataRole.DecorationRole:
if col == 2:
if result.drm_free_only:
return (self.NO_DRM_ICON)
if col == 4:
if result.affiliate:
return (self.DONATE_ICON)
- elif role == Qt.CheckStateRole:
+ elif role == Qt.ItemDataRole.CheckStateRole:
if col == 0:
if is_disabled(result):
- return Qt.Unchecked
- return Qt.Checked
- elif role == Qt.TextAlignmentRole:
+ return Qt.CheckState.Unchecked
+ return Qt.CheckState.Checked
+ elif role == Qt.ItemDataRole.TextAlignmentRole:
if col in self.CENTERED_COLUMNS:
- return Qt.AlignHCenter
- return Qt.AlignLeft
- elif role == Qt.ToolTipRole:
+ return Qt.AlignmentFlag.AlignHCenter
+ return Qt.AlignmentFlag.AlignLeft
+ elif role == Qt.ItemDataRole.ToolTipRole:
if col == 0:
if is_disabled(result):
return ('
' + _('This store is currently disabled and cannot be used in other parts of calibre.') + '
') @@ -186,7 +186,7 @@ class Matches(QAbstractItemModel): def flags(self, index): if index.column() == 0: - return QAbstractItemModel.flags(self, index) | Qt.ItemIsUserCheckable + return QAbstractItemModel.flags(self, index) | Qt.ItemFlag.ItemIsUserCheckable return QAbstractItemModel.flags(self, index) def data_as_text(self, match, col): @@ -208,7 +208,7 @@ class Matches(QAbstractItemModel): self.sort_order = order if not self.matches: return - descending = order == Qt.DescendingOrder + descending = order == Qt.SortOrder.DescendingOrder self.matches.sort(key=lambda x: sort_key(unicode_type(self.data_as_text(x, col))), reverse=descending) if reset: self.beginResetModel(), self.endResetModel() diff --git a/src/calibre/gui2/store/config/chooser/results_view.py b/src/calibre/gui2/store/config/chooser/results_view.py index 647536b1c0..44f26439c2 100644 --- a/src/calibre/gui2/store/config/chooser/results_view.py +++ b/src/calibre/gui2/store/config/chooser/results_view.py @@ -35,7 +35,7 @@ class ResultsView(QTreeView): for i in range(self._model.columnCount()): self.resizeColumnToContents(i) - self.model().sort(1, Qt.AscendingOrder) + self.model().sort(1, Qt.SortOrder.AscendingOrder) self.header().setSortIndicator(self.model().sort_col, self.model().sort_order) def contextMenuEvent(self, event): diff --git a/src/calibre/gui2/store/search/adv_search_builder.py b/src/calibre/gui2/store/search/adv_search_builder.py index decbed987d..9cefca355a 100644 --- a/src/calibre/gui2/store/search/adv_search_builder.py +++ b/src/calibre/gui2/store/search/adv_search_builder.py @@ -39,9 +39,9 @@ class AdvSearchBuilderDialog(QDialog, Ui_Dialog): def tab_changed(self, idx): if idx == 1: - self.tab_2_button_box.button(QDialogButtonBox.Ok).setDefault(True) + self.tab_2_button_box.button(QDialogButtonBox.StandardButton.Ok).setDefault(True) else: - self.buttonBox.button(QDialogButtonBox.Ok).setDefault(True) + self.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setDefault(True) def advanced_search_button_pushed(self): self.adv_search_used = True diff --git a/src/calibre/gui2/store/search/models.py b/src/calibre/gui2/store/search/models.py index ab87877f92..b4c63fcb1a 100644 --- a/src/calibre/gui2/store/search/models.py +++ b/src/calibre/gui2/store/search/models.py @@ -67,7 +67,7 @@ class Matches(QAbstractItemModel): self.got_result_details_dispatcher = FunctionDispatcher(self.got_result_details) self.sort_col = 2 - self.sort_order = Qt.AscendingOrder + self.sort_order = Qt.SortOrder.AscendingOrder def closing(self): self.cover_pool.abort() @@ -183,10 +183,10 @@ class Matches(QAbstractItemModel): return len(self.HEADERS) def headerData(self, section, orientation, role): - if role != Qt.DisplayRole: + if role != Qt.ItemDataRole.DisplayRole: return None text = '' - if orientation == Qt.Horizontal: + if orientation == Qt.Orientation.Horizontal: if section < len(self.HEADERS): text = self.HEADERS[section] return (text) @@ -198,7 +198,7 @@ class Matches(QAbstractItemModel): if row >= len(self.matches): return None result = self.matches[row] - if role == Qt.DisplayRole: + if role == Qt.ItemDataRole.DisplayRole: if col == 1: t = result.title if result.title else _('Unknown') a = result.author if result.author else '' @@ -208,7 +208,7 @@ class Matches(QAbstractItemModel): elif col == 4: return ('%s%s
' % result.title) elif col == 2: @@ -253,7 +253,7 @@ class Matches(QAbstractItemModel): elif col == 6: if result.affiliate: return ('' + _('Buying from this store supports the calibre developer: %s.') % result.plugin_author + '
') - elif role == Qt.SizeHintRole: + elif role == Qt.ItemDataRole.SizeHintRole: return QSize(64, 64) return None @@ -289,7 +289,7 @@ class Matches(QAbstractItemModel): self.sort_order = order if not self.matches: return - descending = order == Qt.DescendingOrder + descending = order == Qt.SortOrder.DescendingOrder self.all_matches.sort( key=lambda x: sort_key(unicode_type(self.data_as_text(x, col))), reverse=descending) diff --git a/src/calibre/gui2/store/search/results_view.py b/src/calibre/gui2/store/search/results_view.py index 8fc7348493..5388a56e54 100644 --- a/src/calibre/gui2/store/search/results_view.py +++ b/src/calibre/gui2/store/search/results_view.py @@ -20,7 +20,7 @@ class ImageDelegate(QStyledItemDelegate): def paint(self, painter, option, index): QStyledItemDelegate.paint(self, painter, option, empty_index) - img = index.data(Qt.DecorationRole) + img = index.data(Qt.ItemDataRole.DecorationRole) if img: h = option.rect.height() - 4 w = option.rect.width() @@ -31,7 +31,7 @@ class ImageDelegate(QStyledItemDelegate): dpr = img.devicePixelRatio() scaled, nw, nh = fit_image(img.width(), img.height(), w, h) if scaled: - img = img.scaled(nw*dpr, nh*dpr, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) + img = img.scaled(nw*dpr, nh*dpr, Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation) iw, ih = int(img.width()/dpr), int(img.height()/dpr) dx, dy = (option.rect.width() - iw) // 2, (option.rect.height() - ih) // 2 painter.drawPixmap(option.rect.adjusted(dx, dy, -dx, -dy), img) diff --git a/src/calibre/gui2/store/search/search.py b/src/calibre/gui2/store/search/search.py index 2ecf6554b5..c5e712603d 100644 --- a/src/calibre/gui2/store/search/search.py +++ b/src/calibre/gui2/store/search/search.py @@ -53,7 +53,7 @@ class SearchDialog(QDialog, Ui_Dialog): self.cache_pool = CacheUpdateThreadPool(self.cache_thread_count) self.results_view.model().cover_pool.set_thread_count(self.cover_thread_count) self.results_view.model().details_pool.set_thread_count(self.details_thread_count) - self.results_view.setCursor(Qt.PointingHandCursor) + self.results_view.setCursor(Qt.CursorShape.PointingHandCursor) # Check for results and hung threads. self.checker = QTimer() @@ -79,8 +79,8 @@ class SearchDialog(QDialog, Ui_Dialog): # Create and add the progress indicator self.pi = ProgressIndicator(self, 24) self.button_layout.takeAt(0) - self.button_layout.setAlignment(Qt.AlignCenter) - self.button_layout.insertWidget(0, self.pi, 0, Qt.AlignCenter) + self.button_layout.setAlignment(Qt.AlignmentFlag.AlignCenter) + self.button_layout.insertWidget(0, self.pi, 0, Qt.AlignmentFlag.AlignCenter) self.adv_search_button.setIcon(QIcon(I('gear.png'))) self.adv_search_button.setToolTip(_('Advanced search')) @@ -139,7 +139,7 @@ class SearchDialog(QDialog, Ui_Dialog): def build_adv_search(self): adv = AdvSearchBuilderDialog(self) - if adv.exec_() == QDialog.Accepted: + if adv.exec_() == QDialog.DialogCode.Accepted: self.search_edit.setText(adv.search_string()) def resize_columns(self): @@ -289,7 +289,7 @@ class SearchDialog(QDialog, Ui_Dialog): self.store_checks[n].setChecked(store_check[n]) self.results_view.model().sort_col = self.config.get('sort_col', 2) - self.results_view.model().sort_order = self.config.get('sort_order', Qt.AscendingOrder) + self.results_view.model().sort_order = self.config.get('sort_order', Qt.SortOrder.AscendingOrder) self.results_view.header().setSortIndicator(self.results_view.model().sort_col, self.results_view.model().sort_order) def load_settings(self): @@ -315,7 +315,7 @@ class SearchDialog(QDialog, Ui_Dialog): # Create the config dialog. It's going to put two config widgets # into a QTabWidget for displaying all of the settings. d = QDialog(self) - button_box = QDialogButtonBox(QDialogButtonBox.Close) + button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) v = QVBoxLayout(d) button_box.accepted.connect(d.accept) button_box.rejected.connect(d.reject) diff --git a/src/calibre/gui2/store/stores/mobileread/adv_search_builder.py b/src/calibre/gui2/store/stores/mobileread/adv_search_builder.py index 063a55ad5e..0c69a55e98 100644 --- a/src/calibre/gui2/store/stores/mobileread/adv_search_builder.py +++ b/src/calibre/gui2/store/stores/mobileread/adv_search_builder.py @@ -33,9 +33,9 @@ class AdvSearchBuilderDialog(QDialog, Ui_Dialog): def tab_changed(self, idx): if idx == 1: - self.tab_2_button_box.button(QDialogButtonBox.Ok).setDefault(True) + self.tab_2_button_box.button(QDialogButtonBox.StandardButton.Ok).setDefault(True) else: - self.buttonBox.button(QDialogButtonBox.Ok).setDefault(True) + self.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setDefault(True) def advanced_search_button_pushed(self): self.adv_search_used = True diff --git a/src/calibre/gui2/store/stores/mobileread/models.py b/src/calibre/gui2/store/stores/mobileread/models.py index c1e378db4a..9d5f0495e0 100644 --- a/src/calibre/gui2/store/stores/mobileread/models.py +++ b/src/calibre/gui2/store/stores/mobileread/models.py @@ -29,7 +29,7 @@ class BooksModel(QAbstractItemModel): self.filter = '' self.search_filter = SearchFilter(all_books) self.sort_col = 0 - self.sort_order = Qt.AscendingOrder + self.sort_order = Qt.SortOrder.AscendingOrder def get_book(self, index): row = index.row() @@ -66,10 +66,10 @@ class BooksModel(QAbstractItemModel): return len(self.HEADERS) def headerData(self, section, orientation, role): - if role != Qt.DisplayRole: + if role != Qt.ItemDataRole.DisplayRole: return None text = '' - if orientation == Qt.Horizontal: + if orientation == Qt.Orientation.Horizontal: if section < len(self.HEADERS): text = self.HEADERS[section] return (text) @@ -79,7 +79,7 @@ class BooksModel(QAbstractItemModel): def data(self, index, role): row, col = index.row(), index.column() result = self.books[row] - if role == Qt.DisplayRole: + if role == Qt.ItemDataRole.DisplayRole: if col == 0: return (result.title) elif col == 1: @@ -103,7 +103,7 @@ class BooksModel(QAbstractItemModel): self.sort_order = order if not self.books: return - descending = order == Qt.DescendingOrder + descending = order == Qt.SortOrder.DescendingOrder self.books.sort(None, lambda x: sort_key(type(u'')(self.data_as_text(x, col))), descending) diff --git a/src/calibre/gui2/store/stores/mobileread/store_dialog.py b/src/calibre/gui2/store/stores/mobileread/store_dialog.py index 5b6133bd29..420dbc99ff 100644 --- a/src/calibre/gui2/store/stores/mobileread/store_dialog.py +++ b/src/calibre/gui2/store/stores/mobileread/store_dialog.py @@ -22,7 +22,7 @@ class MobileReadStoreDialog(QDialog, Ui_Dialog): self.plugin = plugin self.search_query.initialize('store_mobileread_search') - self.search_query.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLengthWithIcon) + self.search_query.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon) self.search_query.setMinimumContentsLength(25) self.adv_search_button.setIcon(QIcon(I('search.png'))) @@ -52,7 +52,7 @@ class MobileReadStoreDialog(QDialog, Ui_Dialog): def build_adv_search(self): adv = AdvSearchBuilderDialog(self) - if adv.exec_() == QDialog.Accepted: + if adv.exec_() == QDialog.DialogCode.Accepted: self.search_query.setText(adv.search_string()) def restore_state(self): @@ -71,7 +71,7 @@ class MobileReadStoreDialog(QDialog, Ui_Dialog): self.results_view.resizeColumnToContents(i) self.results_view.model().sort_col = self.plugin.config.get('dialog_sort_col', 0) - self.results_view.model().sort_order = self.plugin.config.get('dialog_sort_order', Qt.AscendingOrder) + self.results_view.model().sort_order = self.plugin.config.get('dialog_sort_order', Qt.SortOrder.AscendingOrder) self.results_view.model().sort(self.results_view.model().sort_col, self.results_view.model().sort_order) self.results_view.header().setSortIndicator(self.results_view.model().sort_col, self.results_view.model().sort_order) diff --git a/src/calibre/gui2/tag_browser/model.py b/src/calibre/gui2/tag_browser/model.py index 00f1a2187d..a78127c38c 100644 --- a/src/calibre/gui2/tag_browser/model.py +++ b/src/calibre/gui2/tag_browser/model.py @@ -32,7 +32,7 @@ from polyglot.builtins import iteritems, itervalues, map, range, unicode_type TAG_SEARCH_STATES = {'clear': 0, 'mark_plus': 1, 'mark_plusplus': 2, 'mark_minus': 3, 'mark_minusminus': 4} -DRAG_IMAGE_ROLE = Qt.UserRole + 1000 +DRAG_IMAGE_ROLE = Qt.ItemDataRole.UserRole + 1000 COUNT_ROLE = DRAG_IMAGE_ROLE + 1 _bf = None @@ -161,7 +161,7 @@ class TagTreeItem(object): # {{{ return self.cached_item_count def data(self, role): - if role == Qt.UserRole: + if role == Qt.ItemDataRole.UserRole: return self if self.type == self.TAG: return self.tag_data(role) @@ -170,17 +170,17 @@ class TagTreeItem(object): # {{{ return None def category_data(self, role): - if role == Qt.DisplayRole: + if role == Qt.ItemDataRole.DisplayRole: return self.py_name - if role == Qt.EditRole: + if role == Qt.ItemDataRole.EditRole: return (self.py_name) - if role == Qt.DecorationRole: + if role == Qt.ItemDataRole.DecorationRole: if not self.tag.state: self.ensure_icon() return self.icon_state_map[self.tag.state] - if role == Qt.FontRole: + if role == Qt.ItemDataRole.FontRole: return bf() - if role == Qt.ToolTipRole: + if role == Qt.ItemDataRole.ToolTipRole: return self.tooltip if gprefs['tag_browser_show_tooltips'] else None if role == DRAG_IMAGE_ROLE: self.ensure_icon() @@ -198,15 +198,15 @@ class TagTreeItem(object): # {{{ name = tag.original_name else: name = tag.name - if role == Qt.DisplayRole: + if role == Qt.ItemDataRole.DisplayRole: return unicode_type(name) - if role == Qt.EditRole: + if role == Qt.ItemDataRole.EditRole: return (tag.original_name) - if role == Qt.DecorationRole: + if role == Qt.ItemDataRole.DecorationRole: if not tag.state: self.ensure_icon() return self.icon_state_map[tag.state] - if role == Qt.ToolTipRole: + if role == Qt.ItemDataRole.ToolTipRole: if gprefs['tag_browser_show_tooltips']: tt = [self.tooltip] if self.tooltip else [] if tag.original_categories: @@ -333,7 +333,7 @@ class TagsModel(QAbstractItemModel): # {{{ self.db = None self._build_in_progress = False self.reread_collapse_model({}, rebuild=False) - self.show_error_after_event_loop_tick_signal.connect(self.on_show_error_after_event_loop_tick, type=Qt.QueuedConnection) + self.show_error_after_event_loop_tick_signal.connect(self.on_show_error_after_event_loop_tick, type=Qt.ConnectionType.QueuedConnection) @property def gui_parent(self): @@ -835,7 +835,7 @@ class TagsModel(QAbstractItemModel): # {{{ if not fmts.intersection(set(self.mimeTypes())): return False if "application/calibre+from_library" in fmts: - if action != Qt.CopyAction: + if action != Qt.DropAction.CopyAction: return False return self.do_drop_from_library(md, action, row, column, parent) elif 'application/calibre+from_tag_browser' in fmts: @@ -861,7 +861,7 @@ class TagsModel(QAbstractItemModel): # {{{ # dropped on itself return False src_item = self.get_node(src_index) - dest_item = parent.data(Qt.UserRole) + dest_item = parent.data(Qt.ItemDataRole.UserRole) # Here we do the real work. If src is a tag, src == dest, and src # is hierarchical then we can do a rename. if (src_item.type == TagTreeItem.TAG and @@ -894,7 +894,7 @@ class TagsModel(QAbstractItemModel): # {{{ full name, category key, path to node) The type must be TagTreeItem.TAG dest is the TagTreeItem node to receive the items - action is Qt.CopyAction or Qt.MoveAction + action is Qt.DropAction.CopyAction or Qt.DropAction.MoveAction ''' def process_source_node(user_cats, src_parent, src_parent_is_gst, is_uc, dest_key, idx): @@ -906,7 +906,7 @@ class TagsModel(QAbstractItemModel): # {{{ src_cat = idx.tag.category # delete the item if the source is a User category and action is move if is_uc and not src_parent_is_gst and src_parent in user_cats and \ - action == Qt.MoveAction: + action == Qt.DropAction.MoveAction: new_cat = [] for tup in user_cats[src_parent]: if src_name == tup[0] and src_cat == tup[1]: @@ -962,7 +962,7 @@ class TagsModel(QAbstractItemModel): # {{{ def do_drop_from_library(self, md, action, row, column, parent): idx = parent if idx.isValid(): - node = self.data(idx, Qt.UserRole) + node = self.data(idx, Qt.ItemDataRole.UserRole) if node.type == TagTreeItem.TAG: fm = self.db.metadata_for_field(node.tag.category) if node.tag.category in \ @@ -1192,7 +1192,7 @@ class TagsModel(QAbstractItemModel): # {{{ item = self.get_node(index) return item.data(role) - def setData(self, index, value, role=Qt.EditRole): + def setData(self, index, value, role=Qt.ItemDataRole.EditRole): if not index.isValid(): return False # set up to reposition at the same item. We can do this except if @@ -1357,24 +1357,24 @@ class TagsModel(QAbstractItemModel): # {{{ return None def flags(self, index, *args): - ans = Qt.ItemIsEnabled|Qt.ItemIsEditable + ans = Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsEditable if index.isValid(): - node = self.data(index, Qt.UserRole) + node = self.data(index, Qt.ItemDataRole.UserRole) if node.type == TagTreeItem.TAG: if node.tag.is_editable or node.tag.is_hierarchical: - ans |= Qt.ItemIsDragEnabled + ans |= Qt.ItemFlag.ItemIsDragEnabled fm = self.db.metadata_for_field(node.tag.category) if node.tag.category in \ ('tags', 'series', 'authors', 'rating', 'publisher', 'languages') or \ (fm['is_custom'] and fm['datatype'] in ['text', 'rating', 'series', 'enumeration']): - ans |= Qt.ItemIsDropEnabled + ans |= Qt.ItemFlag.ItemIsDropEnabled else: - ans |= Qt.ItemIsDropEnabled + ans |= Qt.ItemFlag.ItemIsDropEnabled return ans def supportedDropActions(self): - return Qt.CopyAction|Qt.MoveAction + return Qt.DropAction.CopyAction|Qt.DropAction.MoveAction def named_path_for_index(self, index): ans = [] diff --git a/src/calibre/gui2/tag_browser/ui.py b/src/calibre/gui2/tag_browser/ui.py index d042235fe9..51788a0dac 100644 --- a/src/calibre/gui2/tag_browser/ui.py +++ b/src/calibre/gui2/tag_browser/ui.py @@ -85,14 +85,14 @@ class TagBrowserMixin(object): # {{{ self.tags_view.search_item_renamed.connect(self.saved_searches_changed) self.tags_view.drag_drop_finished.connect(self.drag_drop_finished) self.tags_view.restriction_error.connect(self.do_restriction_error, - type=Qt.QueuedConnection) + type=Qt.ConnectionType.QueuedConnection) self.tags_view.tag_item_delete.connect(self.do_tag_item_delete) self.tags_view.apply_tag_to_selected.connect(self.apply_tag_to_selected) self.populate_tb_manage_menu(db) self.tags_view.model().user_categories_edited.connect(self.user_categories_edited, - type=Qt.QueuedConnection) + type=Qt.ConnectionType.QueuedConnection) self.tags_view.model().user_category_added.connect(self.user_categories_edited, - type=Qt.QueuedConnection) + type=Qt.ConnectionType.QueuedConnection) self.tags_view.edit_enum_values.connect(self.edit_enum_values) def user_categories_edited(self): @@ -442,10 +442,10 @@ class FindBox(HistoryLineEdit): # {{{ def keyPressEvent(self, event): k = event.key() - if k not in (Qt.Key_Up, Qt.Key_Down): + if k not in (Qt.Key.Key_Up, Qt.Key.Key_Down): return HistoryLineEdit.keyPressEvent(self, event) self.blockSignals(True) - if k == Qt.Key_Down and self.currentIndex() == 0 and not self.lineEdit().text(): + if k == Qt.Key.Key_Down and self.currentIndex() == 0 and not self.lineEdit().text(): self.setCurrentIndex(1), self.setCurrentIndex(0) event.accept() else: @@ -460,14 +460,14 @@ class TagBrowserBar(QWidget): # {{{ def __init__(self, parent): QWidget.__init__(self, parent) - self.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Preferred) + self.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred) parent = parent.parent() self.l = l = QHBoxLayout(self) l.setContentsMargins(0, 0, 0, 0) self.alter_tb = parent.alter_tb = b = QToolButton(self) b.setAutoRaise(True) - b.setText(_('Configure')), b.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) - b.setCursor(Qt.PointingHandCursor) + b.setText(_('Configure')), b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) + b.setCursor(Qt.CursorShape.PointingHandCursor) b.setPopupMode(b.InstantPopup) b.setToolTip(textwrap.fill(_( 'Change how the Tag browser works, such as,' @@ -482,7 +482,7 @@ class TagBrowserBar(QWidget): # {{{ self.item_search.setMinimumContentsLength(5) self.item_search.setSizeAdjustPolicy(self.item_search.AdjustToMinimumContentsLengthWithIcon) self.item_search.initialize('tag_browser_search') - self.item_search.completer().setCaseSensitivity(Qt.CaseSensitive) + self.item_search.completer().setCaseSensitivity(Qt.CaseSensitivity.CaseSensitive) self.item_search.setToolTip( '' +_( 'Search for items. If the text begins with equals (=) the search is ' @@ -502,7 +502,7 @@ class TagBrowserBar(QWidget): # {{{ self.search_button = QToolButton() self.search_button.setAutoRaise(True) - self.search_button.setCursor(Qt.PointingHandCursor) + self.search_button.setCursor(Qt.CursorShape.PointingHandCursor) self.search_button.setIcon(QIcon(I('search.png'))) self.search_button.setToolTip(_('Find the first/next matching item')) ac = QAction(parent) @@ -515,8 +515,8 @@ class TagBrowserBar(QWidget): # {{{ self.toggle_search_button = b = QToolButton(self) le = self.item_search.lineEdit() le.addAction(QIcon(I('window-close.png')), le.LeadingPosition).triggered.connect(self.close_find_box) - b.setText(_('Find')), b.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) - b.setCursor(Qt.PointingHandCursor) + b.setText(_('Find')), b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) + b.setCursor(Qt.CursorShape.PointingHandCursor) b.setIcon(QIcon(I('search.png'))) b.setCheckable(True) b.setChecked(gprefs.get('tag browser search box visible', False)) @@ -544,16 +544,16 @@ class TagBrowserBar(QWidget): # {{{ tuple(map(l.removeItem, items)) if find_shown: l.addWidget(self.alter_tb) - self.alter_tb.setToolButtonStyle(Qt.ToolButtonIconOnly) + self.alter_tb.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonIconOnly) l.addWidget(self.item_search, 10) l.addWidget(self.search_button) - self.item_search.setFocus(Qt.OtherFocusReason) + self.item_search.setFocus(Qt.FocusReason.OtherFocusReason) self.toggle_search_button.setVisible(False) self.search_button.setVisible(True) self.item_search.setVisible(True) else: l.addWidget(self.alter_tb) - self.alter_tb.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) + self.alter_tb.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) l.addStretch(10) l.addStretch(10) l.addWidget(self.toggle_search_button) @@ -568,7 +568,7 @@ class TagBrowserWidget(QFrame): # {{{ def __init__(self, parent): QFrame.__init__(self, parent) - self.setFrameStyle(QFrame.NoFrame if gprefs['tag_browser_old_look'] else QFrame.StyledPanel) + self.setFrameStyle(QFrame.Shape.NoFrame if gprefs['tag_browser_old_look'] else QFrame.Shape.StyledPanel) self._parent = parent self._layout = QVBoxLayout(self) self._layout.setContentsMargins(0,0,0,0) @@ -593,10 +593,10 @@ class TagBrowserWidget(QFrame): # {{{ # Now the floating 'not found' box l = QLabel(self.tags_view) self.not_found_label = l - l.setFrameStyle(QFrame.StyledPanel) + l.setFrameStyle(QFrame.Shape.StyledPanel) l.setAutoFillBackground(True) l.setText('
'+_('No more matches.
Click Find again to go to first match')) - l.setAlignment(Qt.AlignVCenter) + l.setAlignment(Qt.AlignmentFlag.AlignVCenter) l.setWordWrap(True) l.resize(l.sizeHint()) l.move(10,20) @@ -604,7 +604,7 @@ class TagBrowserWidget(QFrame): # {{{ 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) + type=Qt.ConnectionType.QueuedConnection) # The Alter Tag Browser button l = self.alter_tb self.collapse_all_action = ac = QAction(parent) @@ -798,7 +798,7 @@ class TagBrowserWidget(QFrame): # {{{ self.not_found_label.setVisible(False) def keyPressEvent(self, ev): - if ev.key() in (Qt.Key_Enter, Qt.Key_Return) and self.find_text: + if ev.key() in (Qt.Key.Key_Enter, Qt.Key.Key_Return) and self.find_text: self.find() ev.accept() return diff --git a/src/calibre/gui2/tag_browser/view.py b/src/calibre/gui2/tag_browser/view.py index 83375b8fb6..1e438ff3c3 100644 --- a/src/calibre/gui2/tag_browser/view.py +++ b/src/calibre/gui2/tag_browser/view.py @@ -68,7 +68,7 @@ class TagDelegate(QStyledItemDelegate): # {{{ if set_color: painter.save() pen = painter.pen() - pen.setColor(QColor(Qt.black)) + pen.setColor(QColor(Qt.GlobalColor.black)) painter.setPen(pen) painter.drawText(rect, flags, text) if set_color: @@ -76,7 +76,7 @@ class TagDelegate(QStyledItemDelegate): # {{{ def draw_text(self, style, painter, option, widget, index, item): tr = style.subElementRect(style.SE_ItemViewItemText, option, widget) - text = index.data(Qt.DisplayRole) + text = index.data(Qt.ItemDataRole.DisplayRole) hover = option.state & style.State_MouseOver is_search = (True if item.type == TagTreeItem.TAG and item.tag.category == 'search' else False) @@ -85,20 +85,20 @@ class TagDelegate(QStyledItemDelegate): # {{{ width = painter.fontMetrics().boundingRect(count).width() r = QRect(tr) r.setRight(r.right() - 1), r.setLeft(r.right() - width - 4) - self.paint_text(painter, r, Qt.AlignCenter | Qt.TextSingleLine, count, hover) + self.paint_text(painter, r, Qt.AlignmentFlag.AlignCenter | Qt.TextFlag.TextSingleLine, count, hover) tr.setRight(r.left() - 1) else: tr.setRight(tr.right() - 1) is_rating = item.type == TagTreeItem.TAG and not self.rating_pat.sub('', text) if is_rating: painter.setFont(self.rating_font) - flags = Qt.AlignVCenter | Qt.AlignLeft | Qt.TextSingleLine + flags = Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft | Qt.TextFlag.TextSingleLine lr = QRect(tr) lr.setRight(lr.right() * 2) br = painter.boundingRect(lr, flags, text) if br.width() > tr.width(): g = QLinearGradient(tr.topLeft(), tr.topRight()) - c = option.palette.color(QPalette.WindowText) + c = option.palette.color(QPalette.ColorRole.WindowText) g.setColorAt(0, c), g.setColorAt(0.8, c) c = QColor(c) c.setAlpha(0) @@ -113,7 +113,7 @@ class TagDelegate(QStyledItemDelegate): # {{{ widget = self.parent() style = QApplication.style() if widget is None else widget.style() self.initStyleOption(option, index) - item = index.data(Qt.UserRole) + item = index.data(Qt.ItemDataRole.UserRole) self.draw_icon(style, painter, option, widget) painter.save() self.draw_text(style, painter, option, widget, index, item) @@ -201,14 +201,14 @@ class TagsView(QTreeView): # {{{ self._model = TagsModel(self) self._model.search_item_renamed.connect(self.search_item_renamed) self._model.refresh_required.connect(self.refresh_required, - type=Qt.QueuedConnection) + type=Qt.ConnectionType.QueuedConnection) self._model.tag_item_renamed.connect(self.tag_item_renamed) self._model.restriction_error.connect(self.restriction_error) self._model.user_categories_edited.connect(self.user_categories_edited, - type=Qt.QueuedConnection) + type=Qt.ConnectionType.QueuedConnection) self._model.drag_drop_finished.connect(self.drag_drop_finished) self.set_look_and_feel(first=True) - QApplication.instance().palette_changed.connect(self.set_style_sheet, type=Qt.QueuedConnection) + QApplication.instance().palette_changed.connect(self.set_style_sheet, type=Qt.ConnectionType.QueuedConnection) def set_style_sheet(self): stylish_tb = ''' @@ -239,9 +239,9 @@ class TagsView(QTreeView): # {{{ self.itemDelegate().old_look = gprefs['tag_browser_old_look'] if gprefs['tag_browser_allow_keyboard_focus']: - self.setFocusPolicy(Qt.StrongFocus) + self.setFocusPolicy(Qt.FocusPolicy.StrongFocus) else: - self.setFocusPolicy(Qt.NoFocus) + self.setFocusPolicy(Qt.FocusPolicy.NoFocus) # Ensure the TB doesn't keep the focus it might already have. When this # method is first called during GUI initialization not everything is # set up, in which case don't try to change the focus. @@ -299,7 +299,7 @@ class TagsView(QTreeView): # {{{ self.alter_tb = alter_tb self.pane_is_visible = True # because TagsModel.set_database did a recount self.setModel(self._model) - self.setContextMenuPolicy(Qt.CustomContextMenu) + self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) pop = self.db.CATEGORY_SORTS.index(config['sort_tags_by']) self.alter_tb.sort_menu.actions()[pop].setChecked(True) try: @@ -310,7 +310,7 @@ class TagsView(QTreeView): # {{{ if not self.made_connections: self.clicked.connect(self.toggle) self.customContextMenuRequested.connect(self.show_context_menu) - self.refresh_required.connect(self.recount, type=Qt.QueuedConnection) + self.refresh_required.connect(self.recount, type=Qt.ConnectionType.QueuedConnection) self.alter_tb.sort_menu.triggered.connect(self.sort_changed) self.alter_tb.match_menu.triggered.connect(self.match_changed) self.made_connections = True @@ -320,7 +320,7 @@ class TagsView(QTreeView): # {{{ self.collapsed.connect(self.collapse_node_and_children) def keyPressEvent(self, event): - if (gprefs['tag_browser_allow_keyboard_focus'] and event.key() == Qt.Key_Return and self.state() != self.EditingState and + if (gprefs['tag_browser_allow_keyboard_focus'] and event.key() == Qt.Key.Key_Return and self.state() != self.EditingState and # I don't see how current_index can ever be not valid, but ... self.currentIndex().isValid()): self.toggle_current_index() @@ -359,17 +359,17 @@ class TagsView(QTreeView): # {{{ pass def mousePressEvent(self, event): - if event.buttons() & Qt.LeftButton: + if event.buttons() & Qt.MouseButton.LeftButton: self.possible_drag_start = event.pos() return QTreeView.mousePressEvent(self, event) def mouseMoveEvent(self, event): dex = self.indexAt(event.pos()) if dex.isValid(): - self.setCursor(Qt.PointingHandCursor) + self.setCursor(Qt.CursorShape.PointingHandCursor) else: self.unsetCursor() - if not event.buttons() & Qt.LeftButton: + if not event.buttons() & Qt.MouseButton.LeftButton: return if not dex.isValid(): QTreeView.mouseMoveEvent(self, event) @@ -380,7 +380,7 @@ class TagsView(QTreeView): # {{{ QTreeView.mouseMoveEvent(self, event) return - if not self._model.flags(dex) & Qt.ItemIsDragEnabled: + if not self._model.flags(dex) & Qt.ItemFlag.ItemIsDragEnabled: QTreeView.mouseMoveEvent(self, event) return md = self._model.mimeData([dex]) @@ -396,9 +396,9 @@ class TagsView(QTreeView): # {{{ categories stops working. Don't know why. To avoid the problem we fix the action in dragMoveEvent. ''' - drag.exec_(Qt.CopyAction|Qt.MoveAction, Qt.CopyAction) + drag.exec_(Qt.DropAction.CopyAction|Qt.DropAction.MoveAction, Qt.DropAction.CopyAction) else: - drag.exec_(Qt.CopyAction) + drag.exec_(Qt.DropAction.CopyAction) def mouseDoubleClickEvent(self, event): # swallow these to avoid toggling and editing at the same time @@ -424,7 +424,7 @@ class TagsView(QTreeView): # {{{ in TAG_SEARCH_STATES ''' modifiers = int(QApplication.keyboardModifiers()) - exclusive = modifiers not in (Qt.CTRL, Qt.SHIFT) + exclusive = modifiers not in (Qt.Modifier.CTRL, Qt.Modifier.SHIFT) if self._model.toggle(index, exclusive, set_to=set_to): # Reset the focus back to TB if it has it before the toggle # Must ask this question before starting the search because @@ -636,7 +636,7 @@ class TagsView(QTreeView): # {{{ search_submenu = None if index.isValid(): - item = index.data(Qt.UserRole) + item = index.data(Qt.ItemDataRole.UserRole) tag = None tag_item = item @@ -980,7 +980,7 @@ class TagsView(QTreeView): # {{{ if not index.isValid(): return src_is_tb = event.mimeData().hasFormat('application/calibre+from_tag_browser') - item = index.data(Qt.UserRole) + item = index.data(Qt.ItemDataRole.UserRole) if item.type == TagTreeItem.ROOT: return @@ -997,14 +997,14 @@ class TagsView(QTreeView): # {{{ src_item.tag.category == item.tag.category and not item.temporary and self._model.is_key_a_hierarchical_category(src_item.tag.category)): - event.setDropAction(Qt.MoveAction) + event.setDropAction(Qt.DropAction.MoveAction) self.setDropIndicatorShown(True) return # We aren't dropping an item on its own category. Check if the dest is # not a user category and can be dropped on. This covers drops from the # booklist. It is OK to drop onto virtual nodes - if item.type == TagTreeItem.TAG and self._model.flags(index) & Qt.ItemIsDropEnabled: - event.setDropAction(Qt.CopyAction) + if item.type == TagTreeItem.TAG and self._model.flags(index) & Qt.ItemFlag.ItemIsDropEnabled: + event.setDropAction(Qt.DropAction.CopyAction) self.setDropIndicatorShown(not src_is_tb) return # Now see if we are on a user category and the source can be dropped there @@ -1013,7 +1013,7 @@ class TagsView(QTreeView): # {{{ if fm_dest['kind'] == 'user': if src_is_tb: # src_md and src_item are initialized above - if event.dropAction() == Qt.MoveAction: + if event.dropAction() == Qt.DropAction.MoveAction: # can move only from user categories if (src_md[0] == TagTreeItem.TAG and (not src_md[1].startswith('@') or src_md[2])): @@ -1040,7 +1040,7 @@ class TagsView(QTreeView): # {{{ self.model().clear_state() def is_visible(self, idx): - item = idx.data(Qt.UserRole) + item = idx.data(Qt.ItemDataRole.UserRole) if getattr(item, 'type', None) == TagTreeItem.TAG: idx = idx.parent() return self.isExpanded(idx) @@ -1104,7 +1104,7 @@ class TagsView(QTreeView): # {{{ def show_item_at_index(self, idx, box=False, position=QTreeView.PositionAtCenter): - if idx.isValid() and idx.data(Qt.UserRole) is not self._model.root_item: + if idx.isValid() and idx.data(Qt.ItemDataRole.UserRole) is not self._model.root_item: self.expand_parent(idx) self.setCurrentIndex(idx) self.scrollTo(idx, position) diff --git a/src/calibre/gui2/tag_mapper.py b/src/calibre/gui2/tag_mapper.py index b3bba22afc..254c04e8d9 100644 --- a/src/calibre/gui2/tag_mapper.py +++ b/src/calibre/gui2/tag_mapper.py @@ -215,7 +215,7 @@ class RuleEditDialog(Dialog): Dialog.accept(self) -DATA_ROLE = Qt.UserRole +DATA_ROLE = Qt.ItemDataRole.UserRole RENDER_ROLE = DATA_ROLE + 1 @@ -256,7 +256,7 @@ class Delegate(QStyledItemDelegate): def paint(self, painter, option, index): QStyledItemDelegate.paint(self, painter, option, index) pal = option.palette - color = pal.color(pal.HighlightedText if option.state & QStyle.State_Selected else pal.Text).name() + color = pal.color(pal.HighlightedText if option.state & QStyle.StateFlag.State_Selected else pal.Text).name() text = '
'+_('No matches for %(text)s found in the current file [%(current)s].' ' Do you want to search in the %(which)s file [%(next)s]?') msg = msg%dict(text=text, current=current, next=next, @@ -231,7 +231,7 @@ class ItemEdit(QWidget): self.dest_list.addItems(spine_names) def current_changed(self, item): - name = self.current_name = unicode_type(item.data(Qt.DisplayRole) or '') + name = self.current_name = unicode_type(item.data(Qt.ItemDataRole.DisplayRole) or '') path = self.container.name_to_abspath(name) # Ensure encoding map is populated root = self.container.parsed(name) @@ -257,13 +257,13 @@ class ItemEdit(QWidget): dest_index, frag = 0, None if item is not None: if where is None: - self.name.setText(item.data(0, Qt.DisplayRole) or '') + self.name.setText(item.data(0, Qt.ItemDataRole.DisplayRole) or '') self.name.setCursorPosition(0) - toc = item.data(0, Qt.UserRole) + toc = item.data(0, Qt.ItemDataRole.UserRole) if toc.dest: for i in range(self.dest_list.count()): litem = self.dest_list.item(i) - if unicode_type(litem.data(Qt.DisplayRole) or '') == toc.dest: + if unicode_type(litem.data(Qt.ItemDataRole.DisplayRole) or '') == toc.dest: dest_index = i frag = toc.frag break diff --git a/src/calibre/gui2/toc/main.py b/src/calibre/gui2/toc/main.py index a7bdd4bf8d..668b4b5ab3 100644 --- a/src/calibre/gui2/toc/main.py +++ b/src/calibre/gui2/toc/main.py @@ -56,7 +56,7 @@ class XPathDialog(QDialog): # {{{ self.widgets.append(xp) l.addWidget(xp) - 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.ssb = b = bb.addButton(_('&Save settings'), bb.ActionRole) @@ -353,12 +353,12 @@ class ItemView(QStackedWidget): # {{{ def populate_item_pane(self): item = self.current_item - name = unicode_type(item.data(0, Qt.DisplayRole) or '') + name = unicode_type(item.data(0, Qt.ItemDataRole.DisplayRole) or '') self.item_pane.heading.setText('
…' + escape(result.before, False) + '' + escape( result.text, False) + '' + escape(result.after, False) + '…' - item.setData(0, Qt.ToolTipRole, tt) + item.setData(0, Qt.ItemDataRole.ToolTipRole, tt) item.setIcon(0, self.blank_icon) self.item_map[len(self.search_results)] = item self.search_results.append(result) @@ -493,7 +493,7 @@ class Results(QTreeWidget): # {{{ def item_activated(self): i = self.currentItem() if i: - sr = i.data(0, Qt.UserRole) + sr = i.data(0, Qt.ItemDataRole.UserRole) if isinstance(sr, SearchResult): if not sr.is_hidden: self.show_search_result.emit(sr) @@ -504,7 +504,7 @@ class Results(QTreeWidget): # {{{ item = self.currentItem() if item is None: return - i = int(item.data(0, Qt.UserRole + 1)) + i = int(item.data(0, Qt.ItemDataRole.UserRole + 1)) i += -1 if previous else 1 i %= self.number_of_results self.setCurrentItem(self.item_map[i]) @@ -513,7 +513,7 @@ class Results(QTreeWidget): # {{{ def search_result_not_found(self, sr): for i in range(self.number_of_results): item = self.item_map[i] - r = item.data(0, Qt.UserRole) + r = item.data(0, Qt.ItemDataRole.UserRole) if r.is_result(sr): r.is_hidden = True item.setIcon(0, self.not_found_icon) @@ -523,7 +523,7 @@ class Results(QTreeWidget): # {{{ def current_result_is_hidden(self): item = self.currentItem() if item is not None: - sr = item.data(0, Qt.UserRole) + sr = item.data(0, Qt.ItemDataRole.UserRole) if isinstance(sr, SearchResult) and sr.is_hidden: return True return False @@ -565,14 +565,14 @@ class SearchPanel(QWidget): # {{{ self.search_input = si = SearchInput(self) self.searcher = None self.search_tasks = Queue() - self.results_found.connect(self.on_result_found, type=Qt.QueuedConnection) + self.results_found.connect(self.on_result_found, type=Qt.ConnectionType.QueuedConnection) si.do_search.connect(self.search_requested) si.cleared.connect(self.search_cleared) si.go_back.connect(self.go_back) l.addWidget(si) self.results = r = Results(self) r.count_changed.connect(self.count_changed) - r.show_search_result.connect(self.do_show_search_result, type=Qt.QueuedConnection) + r.show_search_result.connect(self.do_show_search_result, type=Qt.ConnectionType.QueuedConnection) r.current_result_changed.connect(self.update_hidden_message) l.addWidget(r, 100) self.spinner = s = BusySpinner(self) @@ -700,7 +700,7 @@ class SearchPanel(QWidget): # {{{ warning_dialog(self, _('No matches found'), msg + ' {}'.format(self.current_search.text), show=True) def keyPressEvent(self, ev): - if ev.key() == Qt.Key_Escape: + if ev.key() == Qt.Key.Key_Escape: self.hide_search_panel.emit() ev.accept() return diff --git a/src/calibre/gui2/viewer/shortcuts.py b/src/calibre/gui2/viewer/shortcuts.py index 7063cd6312..6ed978918f 100644 --- a/src/calibre/gui2/viewer/shortcuts.py +++ b/src/calibre/gui2/viewer/shortcuts.py @@ -24,7 +24,7 @@ def index_to_key_sequence(idx): def key_to_text(key): - return QKeySequence(key).toString(QKeySequence.PortableText).lower() + return QKeySequence(key).toString(QKeySequence.SequenceFormat.PortableText).lower() def ev_to_index(ev): diff --git a/src/calibre/gui2/viewer/toc.py b/src/calibre/gui2/viewer/toc.py index 78fbaf2bcf..a1f2424015 100644 --- a/src/calibre/gui2/viewer/toc.py +++ b/src/calibre/gui2/viewer/toc.py @@ -27,7 +27,7 @@ class Delegate(QStyledItemDelegate): rect = view.visualRect(index) size = self.sizeHint(option, index) if rect.width() < size.width(): - tooltip = index.data(Qt.DisplayRole) + tooltip = index.data(Qt.ItemDataRole.DisplayRole) QToolTip.showText(ev.globalPos(), tooltip, view) return True return QStyledItemDelegate.helpEvent(self, ev, view, option, index) @@ -39,20 +39,20 @@ class TOCView(QTreeView): def __init__(self, *args): QTreeView.__init__(self, *args) - self.setFocusPolicy(Qt.NoFocus) + self.setFocusPolicy(Qt.FocusPolicy.NoFocus) self.delegate = Delegate(self) self.setItemDelegate(self.delegate) self.setMinimumWidth(80) self.header().close() self.setMouseTracking(True) self.set_style_sheet() - self.setContextMenuPolicy(Qt.CustomContextMenu) + self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.customContextMenuRequested.connect(self.context_menu) - QApplication.instance().palette_changed.connect(self.set_style_sheet, type=Qt.QueuedConnection) + QApplication.instance().palette_changed.connect(self.set_style_sheet, type=Qt.ConnectionType.QueuedConnection) def setModel(self, model): QTreeView.setModel(self, model) - model.auto_expand_nodes.connect(self.auto_expand_indices, type=Qt.QueuedConnection) + model.auto_expand_nodes.connect(self.auto_expand_indices, type=Qt.ConnectionType.QueuedConnection) def auto_expand_indices(self, indices): for idx in indices: @@ -82,7 +82,7 @@ class TOCView(QTreeView): def mouseMoveEvent(self, ev): if self.indexAt(ev.pos()).isValid(): - self.setCursor(Qt.PointingHandCursor) + self.setCursor(Qt.CursorShape.PointingHandCursor) else: self.unsetCursor() return QTreeView.mouseMoveEvent(self, ev) @@ -164,7 +164,7 @@ class TOCItem(QStandardItem): self.normal_font, self.emphasis_font = normal_font, emphasis_font for t in toc['children']: self.appendRow(TOCItem(t, depth+1, all_items, normal_font, emphasis_font, parent=self)) - self.setFlags(Qt.ItemIsEnabled) + self.setFlags(Qt.ItemFlag.ItemIsEnabled) self.is_current_search_result = False self.depth = depth self.set_being_viewed(False) @@ -182,7 +182,7 @@ class TOCItem(QStandardItem): @classmethod def type(cls): - return QStandardItem.UserType+10 + return QStandardItem.ItemType.UserType+10 def set_current_search_result(self, yes): if yes and not self.is_current_search_result: diff --git a/src/calibre/gui2/viewer/toolbars.py b/src/calibre/gui2/viewer/toolbars.py index 806cbb959f..27ef167af6 100644 --- a/src/calibre/gui2/viewer/toolbars.py +++ b/src/calibre/gui2/viewer/toolbars.py @@ -90,10 +90,10 @@ class ToolBar(QToolBar): QToolBar.__init__(self, parent) self.setWindowTitle(_('Toolbar')) self.shortcut_actions = {} - self.setToolButtonStyle(Qt.ToolButtonIconOnly) + self.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonIconOnly) self.setVisible(False) - self.setAllowedAreas(Qt.AllToolBarAreas) - self.setContextMenuPolicy(Qt.CustomContextMenu) + self.setAllowedAreas(Qt.ToolBarArea.AllToolBarAreas) + self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) def create_shortcut_action(self, name): a = getattr(all_actions(), name) @@ -135,13 +135,13 @@ class ActionsToolBar(ToolBar): web_view.reference_mode_changed.connect(self.update_reference_mode_action) web_view.standalone_misc_settings_changed.connect(self.update_visibility) web_view.autoscroll_state_changed.connect(self.update_autoscroll_action) - web_view.customize_toolbar.connect(self.customize, type=Qt.QueuedConnection) + web_view.customize_toolbar.connect(self.customize, type=Qt.ConnectionType.QueuedConnection) web_view.view_created.connect(self.on_view_created) - self.back_action = page.action(QWebEnginePage.Back) + self.back_action = page.action(QWebEnginePage.WebAction.Back) self.back_action.setIcon(aa.back.icon) self.back_action.setText(aa.back.text) - self.forward_action = page.action(QWebEnginePage.Forward) + self.forward_action = page.action(QWebEnginePage.WebAction.Forward) self.forward_action.setIcon(aa.forward.icon) self.forward_action.setText(aa.forward.text) @@ -238,7 +238,7 @@ class ActionsToolBar(ToolBar): if x is not None: def as_text(idx): - return index_to_key_sequence(idx).toString(QKeySequence.NativeText) + return index_to_key_sequence(idx).toString(QKeySequence.SequenceFormat.NativeText) keys = sorted(filter(None, map(as_text, x))) if keys: @@ -310,7 +310,7 @@ class ActionsList(QListWidget): self.viewport().setAcceptDrops(True) self.setDropIndicatorShown(True) self.setDragDropMode(self.InternalMove) - self.setDefaultDropAction(Qt.CopyAction if ismacos else Qt.MoveAction) + self.setDefaultDropAction(Qt.DropAction.CopyAction if ismacos else Qt.DropAction.MoveAction) self.setMinimumHeight(400) self.is_source = is_source if is_source: @@ -332,7 +332,7 @@ class ActionsList(QListWidget): except AttributeError: return i = QListWidgetItem(a.icon, a.text, self) - i.setData(Qt.UserRole, action) + i.setData(Qt.ItemDataRole.UserRole, action) return i def set_names(self, names): @@ -343,7 +343,7 @@ class ActionsList(QListWidget): def remove_selected(self): ans = [] for item in tuple(self.selectedItems()): - action = item.data(Qt.UserRole) + action = item.data(Qt.ItemDataRole.UserRole) if action is not None or not self.is_source: self.takeItem(self.row(item)) ans.append(action) @@ -361,7 +361,7 @@ class ActionsList(QListWidget): def names(self): for i in range(self.count()): item = self.item(i) - yield item.data(Qt.UserRole) + yield item.data(Qt.ItemDataRole.UserRole) class ConfigureToolBar(Dialog): diff --git a/src/calibre/gui2/viewer/ui.py b/src/calibre/gui2/viewer/ui.py index 9fd0e31e2c..335efdd398 100644 --- a/src/calibre/gui2/viewer/ui.py +++ b/src/calibre/gui2/viewer/ui.py @@ -60,15 +60,15 @@ def dock_defs(): Dock = namedtuple('Dock', 'name title initial_area allowed_areas') ans = {} - def d(title, name, area, allowed=Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea): + def d(title, name, area, allowed=Qt.DockWidgetArea.LeftDockWidgetArea | Qt.DockWidgetArea.RightDockWidgetArea): ans[name] = Dock(name + '-dock', title, area, allowed) - d(_('Table of Contents'), 'toc', Qt.LeftDockWidgetArea), - d(_('Lookup'), 'lookup', Qt.RightDockWidgetArea), - d(_('Bookmarks'), 'bookmarks', Qt.RightDockWidgetArea) - d(_('Search'), 'search', Qt.LeftDockWidgetArea) - d(_('Inspector'), 'inspector', Qt.RightDockWidgetArea, Qt.AllDockWidgetAreas) - d(_('Highlights'), 'highlights', Qt.RightDockWidgetArea) + d(_('Table of Contents'), 'toc', Qt.DockWidgetArea.LeftDockWidgetArea), + d(_('Lookup'), 'lookup', Qt.DockWidgetArea.RightDockWidgetArea), + d(_('Bookmarks'), 'bookmarks', Qt.DockWidgetArea.RightDockWidgetArea) + d(_('Search'), 'search', Qt.DockWidgetArea.LeftDockWidgetArea) + d(_('Inspector'), 'inspector', Qt.DockWidgetArea.RightDockWidgetArea, Qt.DockWidgetArea.AllDockWidgetAreas) + d(_('Highlights'), 'highlights', Qt.DockWidgetArea.RightDockWidgetArea) return ans @@ -90,10 +90,10 @@ class EbookViewer(MainWindow): self.shutting_down = self.close_forced = self.shutdown_done = False self.force_reload = force_reload connect_lambda(self.book_preparation_started, self, lambda self: self.loading_overlay(_( - 'Preparing book for first read, please wait')), type=Qt.QueuedConnection) + 'Preparing book for first read, please wait')), type=Qt.ConnectionType.QueuedConnection) self.maximized_at_last_fullscreen = False self.save_pos_timer = t = QTimer(self) - t.setSingleShot(True), t.setInterval(3000), t.setTimerType(Qt.VeryCoarseTimer) + t.setSingleShot(True), t.setInterval(3000), t.setTimerType(Qt.TimerType.VeryCoarseTimer) connect_lambda(t.timeout, self, lambda self: self.save_annotations(in_book_file=False)) self.pending_open_at = open_at self.base_window_title = _('E-book viewer') @@ -103,16 +103,16 @@ class EbookViewer(MainWindow): self.image_popup = ImagePopup(self) self.actions_toolbar = at = ActionsToolBar(self) at.open_book_at_path.connect(self.ask_for_open) - self.addToolBar(Qt.LeftToolBarArea, at) + self.addToolBar(Qt.ToolBarArea.LeftToolBarArea, at) try: os.makedirs(annotations_dir) except EnvironmentError: pass self.current_book_data = {} - self.book_prepared.connect(self.load_finished, type=Qt.QueuedConnection) + self.book_prepared.connect(self.load_finished, type=Qt.ConnectionType.QueuedConnection) self.dock_defs = dock_defs() - def create_dock(title, name, area, areas=Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea): + def create_dock(title, name, area, areas=Qt.DockWidgetArea.LeftDockWidgetArea | Qt.DockWidgetArea.RightDockWidgetArea): ans = QDockWidget(title, self) ans.setObjectName(name) self.addDockWidget(area, ans) @@ -174,16 +174,16 @@ class EbookViewer(MainWindow): self.web_view.quit.connect(self.quit) self.web_view.update_current_toc_nodes.connect(self.toc.update_current_toc_nodes) self.web_view.toggle_full_screen.connect(self.toggle_full_screen) - self.web_view.ask_for_open.connect(self.ask_for_open, type=Qt.QueuedConnection) - self.web_view.selection_changed.connect(self.lookup_widget.selected_text_changed, type=Qt.QueuedConnection) - self.web_view.selection_changed.connect(self.highlights_widget.selected_text_changed, type=Qt.QueuedConnection) - self.web_view.view_image.connect(self.view_image, type=Qt.QueuedConnection) - self.web_view.copy_image.connect(self.copy_image, type=Qt.QueuedConnection) + self.web_view.ask_for_open.connect(self.ask_for_open, type=Qt.ConnectionType.QueuedConnection) + self.web_view.selection_changed.connect(self.lookup_widget.selected_text_changed, type=Qt.ConnectionType.QueuedConnection) + self.web_view.selection_changed.connect(self.highlights_widget.selected_text_changed, type=Qt.ConnectionType.QueuedConnection) + self.web_view.view_image.connect(self.view_image, type=Qt.ConnectionType.QueuedConnection) + self.web_view.copy_image.connect(self.copy_image, type=Qt.ConnectionType.QueuedConnection) self.web_view.show_loading_message.connect(self.show_loading_message) self.web_view.show_error.connect(self.show_error) - self.web_view.print_book.connect(self.print_book, type=Qt.QueuedConnection) - self.web_view.reset_interface.connect(self.reset_interface, type=Qt.QueuedConnection) - self.web_view.quit.connect(self.quit, type=Qt.QueuedConnection) + self.web_view.print_book.connect(self.print_book, type=Qt.ConnectionType.QueuedConnection) + self.web_view.reset_interface.connect(self.reset_interface, type=Qt.ConnectionType.QueuedConnection) + self.web_view.quit.connect(self.quit, type=Qt.ConnectionType.QueuedConnection) self.web_view.shortcuts_changed.connect(self.shortcuts_changed) self.web_view.scrollbar_context_menu.connect(self.scrollbar_context_menu) self.web_view.close_prep_finished.connect(self.close_prep_finished) @@ -277,7 +277,7 @@ class EbookViewer(MainWindow): self.showNormal() def changeEvent(self, ev): - if ev.type() == QEvent.WindowStateChange: + if ev.type() == QEvent.Type.WindowStateChange: in_full_screen_mode = self.isFullScreen() if self.in_full_screen_mode is None or self.in_full_screen_mode != in_full_screen_mode: self.in_full_screen_mode = in_full_screen_mode @@ -321,21 +321,21 @@ class EbookViewer(MainWindow): if name: self.web_view.get_current_cfi(self.search_widget.set_anchor_cfi) self.search_widget.start_search(search_query, name) - self.web_view.setFocus(Qt.OtherFocusReason) + self.web_view.setFocus(Qt.FocusReason.OtherFocusReason) def toggle_bookmarks(self): is_visible = self.bookmarks_dock.isVisible() self.bookmarks_dock.setVisible(not is_visible) if is_visible: - self.web_view.setFocus(Qt.OtherFocusReason) + self.web_view.setFocus(Qt.FocusReason.OtherFocusReason) else: - self.bookmarks_widget.bookmarks_list.setFocus(Qt.OtherFocusReason) + self.bookmarks_widget.bookmarks_list.setFocus(Qt.FocusReason.OtherFocusReason) def toggle_highlights(self): is_visible = self.highlights_dock.isVisible() self.highlights_dock.setVisible(not is_visible) if is_visible: - self.web_view.setFocus(Qt.OtherFocusReason) + self.web_view.setFocus(Qt.FocusReason.OtherFocusReason) else: self.highlights_widget.focus() @@ -417,7 +417,7 @@ class EbookViewer(MainWindow): @property def dock_widgets(self): - return self.findChildren(QDockWidget, options=Qt.FindDirectChildrenOnly) + return self.findChildren(QDockWidget, options=Qt.FindChildOption.FindDirectChildrenOnly) def reset_interface(self): for dock in self.dock_widgets: @@ -430,7 +430,7 @@ class EbookViewer(MainWindow): for toolbar in self.findChildren(QToolBar): toolbar.setVisible(False) self.removeToolBar(toolbar) - self.addToolBar(Qt.LeftToolBarArea, toolbar) + self.addToolBar(Qt.ToolBarArea.LeftToolBarArea, toolbar) def ask_for_open(self, path=None): if path is None: @@ -709,5 +709,5 @@ class EbookViewer(MainWindow): def hide_cursor(self): if get_session_pref('auto_hide_mouse', True): self.cursor_hidden = True - QApplication.instance().setOverrideCursor(Qt.BlankCursor) + QApplication.instance().setOverrideCursor(Qt.CursorShape.BlankCursor) # }}} diff --git a/src/calibre/gui2/viewer/web_view.py b/src/calibre/gui2/viewer/web_view.py index d57ccc3f6e..54c649b043 100644 --- a/src/calibre/gui2/viewer/web_view.py +++ b/src/calibre/gui2/viewer/web_view.py @@ -351,7 +351,7 @@ class WebPage(QWebEnginePage): QApplication.instance().clipboard().setMimeData(md) def javaScriptConsoleMessage(self, level, msg, linenumber, source_id): - prefix = {QWebEnginePage.InfoMessageLevel: 'INFO', QWebEnginePage.WarningMessageLevel: 'WARNING'}.get( + prefix = {QWebEnginePage.JavaScriptConsoleMessageLevel.InfoMessageLevel: 'INFO', QWebEnginePage.JavaScriptConsoleMessageLevel.WarningMessageLevel: 'WARNING'}.get( level, 'ERROR') prints('%s: %s:%s: %s' % (prefix, source_id, linenumber, msg), file=sys.stderr) try: @@ -376,9 +376,9 @@ class WebPage(QWebEnginePage): def runjs(self, src, callback=None): if callback is None: - self.runJavaScript(src, QWebEngineScript.ApplicationWorld) + self.runJavaScript(src, QWebEngineScript.ScriptWorldId.ApplicationWorld) else: - self.runJavaScript(src, QWebEngineScript.ApplicationWorld, callback) + self.runJavaScript(src, QWebEngineScript.ScriptWorldId.ApplicationWorld, callback) def viewer_html(): @@ -570,14 +570,14 @@ class WebView(RestartingWebEngineView): child = event.child() if 'HostView' in child.metaObject().className(): self._host_widget = child - self._host_widget.setFocus(Qt.OtherFocusReason) + self._host_widget.setFocus(Qt.FocusReason.OtherFocusReason) return QWebEngineView.event(self, event) def sizeHint(self): return self._size_hint def refresh(self): - self.pageAction(QWebEnginePage.ReloadAndBypassCache).trigger() + self.pageAction(QWebEnginePage.WebAction.ReloadAndBypassCache).trigger() @property def bridge(self): @@ -707,7 +707,7 @@ class WebView(RestartingWebEngineView): def highlight_action(self, uuid, which): self.execute_when_ready('highlight_action', uuid, which) - self.setFocus(Qt.OtherFocusReason) + self.setFocus(Qt.FocusReason.OtherFocusReason) def generic_action(self, which, data): self.execute_when_ready('generic_action', which, data) diff --git a/src/calibre/gui2/viewer/widgets.py b/src/calibre/gui2/viewer/widgets.py index d262dda0f1..cf3693fe2b 100644 --- a/src/calibre/gui2/viewer/widgets.py +++ b/src/calibre/gui2/viewer/widgets.py @@ -24,15 +24,15 @@ class ResultsDelegate(QStyledItemDelegate): # {{{ def paint(self, painter, option, index): QStyledItemDelegate.paint(self, painter, option, index) - result = index.data(Qt.UserRole) + result = index.data(Qt.ItemDataRole.UserRole) is_hidden, result_before, result_text, result_after = self.result_data(result) if result_text is None: return painter.save() try: p = option.palette - c = p.HighlightedText if option.state & QStyle.State_Selected else p.Text - group = (p.Active if option.state & QStyle.State_Active else p.Inactive) + c = p.HighlightedText if option.state & QStyle.StateFlag.State_Selected else p.Text + group = (p.Active if option.state & QStyle.StateFlag.State_Active else p.Inactive) c = p.color(group, c) painter.setPen(c) font = option.font @@ -41,7 +41,7 @@ class ResultsDelegate(QStyledItemDelegate): # {{{ emphasis_font.setBold(True) else: emphasis_font = font - flags = Qt.AlignTop | Qt.TextSingleLine | Qt.TextIncludeTrailingSpaces + flags = Qt.AlignmentFlag.AlignTop | Qt.TextFlag.TextSingleLine | Qt.TextFlag.TextIncludeTrailingSpaces rect = option.rect.adjusted(option.decorationSize.width() + 4 if is_hidden else 0, 0, 0, 0) painter.setClipRect(rect) before = re.sub(r'\s+', ' ', result_before) @@ -58,7 +58,7 @@ class ResultsDelegate(QStyledItemDelegate): # {{{ match_width = painter.boundingRect(rect, flags, text).width() if match_width >= rect.width() - 3 * ellipsis_width: efm = QFontMetrics(emphasis_font) - text = efm.elidedText(text, Qt.ElideRight, rect.width()) + text = efm.elidedText(text, Qt.TextElideMode.ElideRight, rect.width()) painter.drawText(rect, flags, text) else: self.draw_match( @@ -82,7 +82,7 @@ class ResultsDelegate(QStyledItemDelegate): # {{{ r = rect.adjusted(0, 0, 0, 0) r.setRight(x + left_width) painter.setFont(normal_font) - ebefore = nfm.elidedText(before, Qt.ElideLeft, left_width) + ebefore = nfm.elidedText(before, Qt.TextElideMode.ElideLeft, left_width) if self.add_ellipsis and ebefore == before: ebefore = '…' + before[1:] r.setLeft(x) @@ -96,7 +96,7 @@ class ResultsDelegate(QStyledItemDelegate): # {{{ painter.setFont(normal_font) r = rect.adjusted(0, 0, 0, 0) r.setLeft(x) - eafter = nfm.elidedText(after, Qt.ElideRight, right_width) + eafter = nfm.elidedText(after, Qt.TextElideMode.ElideRight, right_width) if self.add_ellipsis and eafter == after: eafter = after[:-1] + '…' painter.setFont(normal_font) diff --git a/src/calibre/gui2/webengine.py b/src/calibre/gui2/webengine.py index 709f1a17fe..26df029a31 100644 --- a/src/calibre/gui2/webengine.py +++ b/src/calibre/gui2/webengine.py @@ -41,7 +41,7 @@ def insert_scripts(profile, *scripts): sc.insert(script) -def create_script(name, src, world=QWebEngineScript.ApplicationWorld, injection_point=QWebEngineScript.DocumentReady, on_subframes=True): +def create_script(name, src, world=QWebEngineScript.ScriptWorldId.ApplicationWorld, injection_point=QWebEngineScript.InjectionPoint.DocumentReady, on_subframes=True): script = QWebEngineScript() if isinstance(src, bytes): src = src.decode('utf-8') @@ -71,7 +71,7 @@ class to_js_bound(QObject): def __call__(self, *args): self.parent().page.runJavaScript('if (window.python_comm) python_comm._from_python({}, {})'.format( - json.dumps(self.name), json.dumps(args)), QWebEngineScript.ApplicationWorld) + json.dumps(self.name), json.dumps(args)), QWebEngineScript.ScriptWorldId.ApplicationWorld) emit = __call__ @@ -105,11 +105,11 @@ class Bridge(QObject): for k, v in iteritems(self.__class__.__dict__): if isinstance(v, to_js): setattr(self, k, to_js_bound(self, k)) - self.page.runJavaScript('python_comm._register_signals(' + self._signals + ')', QWebEngineScript.ApplicationWorld) + self.page.runJavaScript('python_comm._register_signals(' + self._signals + ')', QWebEngineScript.ScriptWorldId.ApplicationWorld) self.bridge_ready.emit() def _poll_for_messages(self): - self.page.runJavaScript('python_comm._poll()', QWebEngineScript.ApplicationWorld, self._dispatch_messages) + self.page.runJavaScript('python_comm._poll()', QWebEngineScript.ScriptWorldId.ApplicationWorld, self._dispatch_messages) def _dispatch_messages(self, messages): try: @@ -143,10 +143,10 @@ class RestartingWebEngineView(QWebEngineView): QWebEngineView.__init__(self, parent) self._last_reload_at = None self.renderProcessTerminated.connect(self.render_process_terminated) - self.render_process_restarted.connect(self.reload, type=Qt.QueuedConnection) + self.render_process_restarted.connect(self.reload, type=Qt.ConnectionType.QueuedConnection) def render_process_terminated(self, termination_type, exit_code): - if termination_type == QWebEnginePage.NormalTerminationStatus: + if termination_type == QWebEnginePage.RenderProcessTerminationStatus.NormalTerminationStatus: return self.webengine_crash_message = 'The Qt WebEngine Render process crashed with termination type: {} and exit code: {}'.format( termination_type, exit_code) diff --git a/src/calibre/gui2/widgets.py b/src/calibre/gui2/widgets.py index 92838d637e..330c01400a 100644 --- a/src/calibre/gui2/widgets.py +++ b/src/calibre/gui2/widgets.py @@ -38,7 +38,7 @@ class ProgressIndicator(QWidget): # {{{ self.pi = _ProgressIndicator(self) self.status = QLabel(self) self.status.setWordWrap(True) - self.status.setAlignment(Qt.AlignHCenter|Qt.AlignTop) + self.status.setAlignment(Qt.AlignmentFlag.AlignHCenter|Qt.AlignmentFlag.AlignTop) self.setVisible(False) self.pos = None @@ -188,7 +188,7 @@ class FormatList(QListWidget): # {{{ event.acceptProposedAction() def dropEvent(self, event): - event.setDropAction(Qt.CopyAction) + event.setDropAction(Qt.DropAction.CopyAction) md = event.mimeData() # Now look for ebook files urls, filenames = dnd_get_files(md, self.DROPABBLE_EXTENSIONS, allow_all_extensions=True) @@ -210,7 +210,7 @@ class FormatList(QListWidget): # {{{ event.acceptProposedAction() def keyPressEvent(self, event): - if event.key() == Qt.Key_Delete: + if event.key() == Qt.Key.Key_Delete: self.delete_format.emit() else: return QListWidget.keyPressEvent(self, event) @@ -236,7 +236,7 @@ class ImageDropMixin(object): # {{{ event.acceptProposedAction() def dropEvent(self, event): - event.setDropAction(Qt.CopyAction) + event.setDropAction(Qt.DropAction.CopyAction) md = event.mimeData() pmap, data = dnd_get_local_image_and_pixmap(md) if pmap is not None: @@ -311,7 +311,7 @@ def draw_size(p, rect, w, h): f.setBold(True) p.setFont(f) sz = '\u00a0%d x %d\u00a0'%(w, h) - flags = Qt.AlignBottom|Qt.AlignRight|Qt.TextSingleLine + flags = Qt.AlignmentFlag.AlignBottom|Qt.AlignmentFlag.AlignRight|Qt.TextFlag.TextSingleLine szrect = p.boundingRect(rect, flags, sz) p.fillRect(szrect.adjusted(0, 0, 0, 4), QColor(0, 0, 0, 200)) p.setPen(QPen(QColor(255,255,255))) @@ -372,14 +372,14 @@ class ImageView(QWidget, ImageDropMixin): cw, ch = self.rect().width(), self.rect().height() scaled, nw, nh = fit_image(w, h, cw, ch) if scaled: - pmap = pmap.scaled(int(nw*pmap.devicePixelRatio()), int(nh*pmap.devicePixelRatio()), Qt.IgnoreAspectRatio, - Qt.SmoothTransformation) + pmap = pmap.scaled(int(nw*pmap.devicePixelRatio()), int(nh*pmap.devicePixelRatio()), Qt.AspectRatioMode.IgnoreAspectRatio, + Qt.TransformationMode.SmoothTransformation) w, h = int(pmap.width()/pmap.devicePixelRatio()), int(pmap.height()/pmap.devicePixelRatio()) x = int(abs(cw - w)/2) y = int(abs(ch - h)/2) target = QRect(x, y, w, h) p = QPainter(self) - p.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform) + p.setRenderHints(QPainter.RenderHint.Antialiasing | QPainter.RenderHint.SmoothPixmapTransform) p.drawPixmap(target, pmap) if self.draw_border: pen = QPen() @@ -524,7 +524,7 @@ class EnLineEdit(LineEditECM, QLineEdit): # {{{ def event(self, ev): # See https://bugreports.qt.io/browse/QTBUG-46911 if ev.type() == ev.ShortcutOverride and ( - hasattr(ev, 'key') and ev.key() in (Qt.Key_Left, Qt.Key_Right) and (ev.modifiers() & ~Qt.KeypadModifier) == Qt.ControlModifier): + hasattr(ev, 'key') and ev.key() in (Qt.Key.Key_Left, Qt.Key.Key_Right) and (ev.modifiers() & ~Qt.KeyboardModifier.KeypadModifier) == Qt.KeyboardModifier.ControlModifier): ev.accept() return QLineEdit.event(self, ev) @@ -574,7 +574,7 @@ class CompleteLineEdit(EnLineEdit): # {{{ self.textChanged.connect(self.text_changed) self.completer = ItemsCompleter(self, complete_items) - self.completer.setCaseSensitivity(Qt.CaseInsensitive) + self.completer.setCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive) self.completer.activated[native_string_type].connect(self.complete_text) @@ -630,14 +630,14 @@ class EnComboBox(QComboBox): # {{{ def __init__(self, *args): QComboBox.__init__(self, *args) self.setLineEdit(EnLineEdit(self)) - self.completer().setCaseSensitivity(Qt.CaseInsensitive) + self.completer().setCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive) self.setMinimumContentsLength(20) def text(self): return unicode_type(self.currentText()) def setText(self, text): - idx = self.findText(text, Qt.MatchFixedString|Qt.MatchCaseSensitive) + idx = self.findText(text, Qt.MatchFlag.MatchFixedString|Qt.MatchFlag.MatchCaseSensitive) if idx == -1: self.insertItem(0, text) idx = 0 @@ -881,7 +881,7 @@ class PythonHighlighter(QSyntaxHighlighter): # {{{ if color is not None: fmt.setForeground(QColor(color)) if bold: - fmt.setFontWeight(QFont.Bold) + fmt.setFontWeight(QFont.Weight.Bold) if italic: fmt.setFontItalic(italic) cls.Formats[name] = fmt @@ -957,7 +957,7 @@ class PythonHighlighter(QSyntaxHighlighter): # {{{ PythonHighlighter.Formats["string"]) def rehighlight(self): - QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) + QApplication.setOverrideCursor(QCursor(Qt.CursorShape.WaitCursor)) QSyntaxHighlighter.rehighlight(self) QApplication.restoreOverrideCursor() @@ -974,9 +974,9 @@ class SplitterHandle(QSplitterHandle): def __init__(self, orientation, splitter): QSplitterHandle.__init__(self, orientation, splitter) splitter.splitterMoved.connect(self.splitter_moved, - type=Qt.QueuedConnection) + type=Qt.ConnectionType.QueuedConnection) self.double_clicked.connect(splitter.double_clicked, - type=Qt.QueuedConnection) + type=Qt.ConnectionType.QueuedConnection) self.highlight = False self.setToolTip(_('Drag to resize')+' '+splitter.label) @@ -1002,7 +1002,7 @@ class LayoutButton(QToolButton): self.splitter = splitter if splitter is not None: splitter.state_changed.connect(self.update_state) - self.setCursor(Qt.PointingHandCursor) + self.setCursor(Qt.CursorShape.PointingHandCursor) self.shortcut = shortcut or '' def update_shortcut(self, action_toggle=None): @@ -1035,7 +1035,7 @@ class LayoutButton(QToolButton): self.set_state_to_hide() def mouseReleaseEvent(self, ev): - if ev.button() == Qt.RightButton: + if ev.button() == Qt.MouseButton.RightButton: from calibre.gui2.ui import get_gui gui = get_gui() if self.icname == 'search': @@ -1058,7 +1058,7 @@ class Splitter(QSplitter): def __init__(self, name, label, icon, initial_show=True, initial_side_size=120, connect_button=True, - orientation=Qt.Horizontal, side_index=0, parent=None, + orientation=Qt.Orientation.Horizontal, side_index=0, parent=None, shortcut=None, hide_handle_on_single_panel=True): QSplitter.__init__(self, parent) if hide_handle_on_single_panel: @@ -1076,7 +1076,7 @@ class Splitter(QSplitter): self.label = label self.initial_side_size = initial_side_size self.initial_show = initial_show - self.splitterMoved.connect(self.splitter_moved, type=Qt.QueuedConnection) + self.splitterMoved.connect(self.splitter_moved, type=Qt.ConnectionType.QueuedConnection) self.button = LayoutButton(icon, label, self, shortcut=shortcut) if connect_button: self.button.clicked.connect(self.double_clicked) @@ -1130,7 +1130,7 @@ class Splitter(QSplitter): @property def save_name(self): - ori = 'horizontal' if self.orientation() == Qt.Horizontal \ + ori = 'horizontal' if self.orientation() == Qt.Orientation.Horizontal \ else 'vertical' return self._name + '_' + ori @@ -1252,14 +1252,14 @@ class PaperSizes(QComboBox): # {{{ if iswindows or ismacos: # On Linux, this can cause Qt to load the system cups plugin # which can crash: https://bugs.launchpad.net/calibre/+bug/1861741 - PaperSizes.system_default_paper_size = 'letter' if QPrinter().pageSize() == QPagedPaintDevice.Letter else 'a4' + PaperSizes.system_default_paper_size = 'letter' if QPrinter().pageSize() == QPagedPaintDevice.PageSize.Letter else 'a4' if not choices: from calibre.ebooks.conversion.plugins.pdf_output import PAPER_SIZES choices = PAPER_SIZES for a in sorted(choices, key=numeric_sort_key): s = getattr(QPageSize, a.capitalize()) sz = QPageSize.definitionSize(s) - unit = {QPageSize.Millimeter: 'mm', QPageSize.Inch: 'inch'}[QPageSize.definitionUnits(s)] + unit = {QPageSize.Unit.Millimeter: 'mm', QPageSize.Unit.Inch: 'inch'}[QPageSize.definitionUnits(s)] name = '{} ({:g} x {:g} {})'.format(QPageSize.name(s), sz.width(), sz.height(), unit) self.addItem(name, a) diff --git a/src/calibre/gui2/widgets2.py b/src/calibre/gui2/widgets2.py index e7b1572ec1..850b64ee30 100644 --- a/src/calibre/gui2/widgets2.py +++ b/src/calibre/gui2/widgets2.py @@ -122,7 +122,7 @@ class ColorButton(QPushButton): self.color_changed.emit(self._color) def choose_color(self): - col = QColorDialog.getColor(QColor(self._color or Qt.white), self, _('Choose a color')) + col = QColorDialog.getColor(QColor(self._color or Qt.GlobalColor.white), self, _('Choose a color')) if col.isValid(): self.color = unicode_type(col.name()) @@ -130,7 +130,7 @@ class ColorButton(QPushButton): def access_key(k): 'Return shortcut text suitable for adding to a menu item' if QKeySequence.keyBindings(k): - return '\t' + QKeySequence(k).toString(QKeySequence.NativeText) + return '\t' + QKeySequence(k).toString(QKeySequence.SequenceFormat.NativeText) return '' @@ -138,22 +138,22 @@ def populate_standard_spinbox_context_menu(spinbox, menu, add_clear=False, use_s m = menu le = spinbox.lineEdit() ca = spinbox if use_self_for_copy_actions else le - m.addAction(_('Cu&t') + access_key(QKeySequence.Cut), ca.cut).setEnabled(not le.isReadOnly() and le.hasSelectedText()) - m.addAction(_('&Copy') + access_key(QKeySequence.Copy), ca.copy).setEnabled(le.hasSelectedText()) - m.addAction(_('&Paste') + access_key(QKeySequence.Paste), ca.paste).setEnabled(not le.isReadOnly()) - m.addAction(_('Delete') + access_key(QKeySequence.Delete), le.del_).setEnabled(not le.isReadOnly() and le.hasSelectedText()) + m.addAction(_('Cu&t') + access_key(QKeySequence.StandardKey.Cut), ca.cut).setEnabled(not le.isReadOnly() and le.hasSelectedText()) + m.addAction(_('&Copy') + access_key(QKeySequence.StandardKey.Copy), ca.copy).setEnabled(le.hasSelectedText()) + m.addAction(_('&Paste') + access_key(QKeySequence.StandardKey.Paste), ca.paste).setEnabled(not le.isReadOnly()) + m.addAction(_('Delete') + access_key(QKeySequence.StandardKey.Delete), le.del_).setEnabled(not le.isReadOnly() and le.hasSelectedText()) m.addSeparator() - m.addAction(_('Select &all') + access_key(QKeySequence.SelectAll), spinbox.selectAll) + m.addAction(_('Select &all') + access_key(QKeySequence.StandardKey.SelectAll), spinbox.selectAll) m.addSeparator() m.addAction(_('&Step up'), spinbox.stepUp) m.addAction(_('Step &down'), spinbox.stepDown) - m.setAttribute(Qt.WA_DeleteOnClose) + m.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose) class RightClickButton(QToolButton): def mousePressEvent(self, ev): - if ev.button() == Qt.RightButton and self.menu() is not None: + if ev.button() == Qt.MouseButton.RightButton and self.menu() is not None: self.showMenu() ev.accept() return @@ -178,7 +178,7 @@ class Dialog(QDialog): self.prefs_for_persistence = prefs self.setWindowTitle(title) self.name = name - 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) @@ -297,10 +297,10 @@ class RatingEditor(QComboBox): self.setCurrentIndex(val) def keyPressEvent(self, ev): - if ev == QKeySequence.Undo: + if ev == QKeySequence.StandardKey.Undo: self.undo() return ev.accept() - if ev == QKeySequence.Redo: + if ev == QKeySequence.StandardKey.Redo: self.redo() return ev.accept() k = ev.key() @@ -372,7 +372,7 @@ class FlowLayout(QLayout): # {{{ if p is None: return -1 if p.isWidgetType(): - which = QStyle.PM_LayoutHorizontalSpacing if horizontal else QStyle.PM_LayoutVerticalSpacing + which = QStyle.PixelMetric.PM_LayoutHorizontalSpacing if horizontal else QStyle.PixelMetric.PM_LayoutVerticalSpacing return p.style().pixelMetric(which, None, p) return p.spacing() @@ -389,7 +389,7 @@ class FlowLayout(QLayout): # {{{ return ans if wid is None: return 0 - return wid.style().layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Horizontal if horizontal else Qt.Vertical) + return wid.style().layoutSpacing(QSizePolicy.ControlType.PushButton, QSizePolicy.ControlType.PushButton, Qt.Orientation.Horizontal if horizontal else Qt.Orientation.Vertical) lines, current_line = [], [] gmap = {} @@ -457,9 +457,9 @@ class HTMLDisplay(QTextBrowser): self.setFont(font) self.setFrameShape(self.NoFrame) self.setOpenLinks(False) - self.setAttribute(Qt.WA_OpaquePaintEvent, False) + self.setAttribute(Qt.WidgetAttribute.WA_OpaquePaintEvent, False) palette = self.palette() - palette.setBrush(QPalette.Base, Qt.transparent) + palette.setBrush(QPalette.ColorRole.Base, Qt.GlobalColor.transparent) self.setPalette(palette) self.setAcceptDrops(False) self.anchorClicked.connect(self.on_anchor_clicked) @@ -589,7 +589,7 @@ class DateTimeEdit(QDateTimeEdit): md = QMimeData() text = self.lineEdit().selectedText() md.setText(text or self.dateTime().toString()) - md.setData(self.MIME_TYPE, self.dateTime().toString(Qt.ISODate).encode('ascii')) + md.setData(self.MIME_TYPE, self.dateTime().toString(Qt.DateFormat.ISODate).encode('ascii')) return md def copy(self): @@ -603,15 +603,15 @@ class DateTimeEdit(QDateTimeEdit): def paste(self): md = QApplication.instance().clipboard().mimeData() if md.hasFormat(self.MIME_TYPE): - self.setDateTime(QDateTime.fromString(md.data(self.MIME_TYPE).data().decode('ascii'), Qt.ISODate)) + self.setDateTime(QDateTime.fromString(md.data(self.MIME_TYPE).data().decode('ascii'), Qt.DateFormat.ISODate)) else: self.lineEdit().paste() def create_context_menu(self): m = QMenu(self) - m.addAction(_('Set date to undefined') + '\t' + QKeySequence(Qt.Key_Minus).toString(QKeySequence.NativeText), + m.addAction(_('Set date to undefined') + '\t' + QKeySequence(Qt.Key.Key_Minus).toString(QKeySequence.SequenceFormat.NativeText), self.clear_date) - m.addAction(_('Set date to today') + '\t' + QKeySequence(Qt.Key_Equal).toString(QKeySequence.NativeText), + m.addAction(_('Set date to today') + '\t' + QKeySequence(Qt.Key.Key_Equal).toString(QKeySequence.SequenceFormat.NativeText), self.today_date) m.addSeparator() populate_standard_spinbox_context_menu(self, m, use_self_for_copy_actions=True) @@ -628,19 +628,19 @@ class DateTimeEdit(QDateTimeEdit): self.setDateTime(UNDEFINED_QDATETIME) def keyPressEvent(self, ev): - if ev.key() == Qt.Key_Minus: + if ev.key() == Qt.Key.Key_Minus: ev.accept() self.clear_date() - elif ev.key() == Qt.Key_Equal: + elif ev.key() == Qt.Key.Key_Equal: self.today_date() ev.accept() - elif ev.matches(QKeySequence.Copy): + elif ev.matches(QKeySequence.StandardKey.Copy): self.copy() ev.accept() - elif ev.matches(QKeySequence.Cut): + elif ev.matches(QKeySequence.StandardKey.Cut): self.cut() ev.accept() - elif ev.matches(QKeySequence.Paste): + elif ev.matches(QKeySequence.StandardKey.Paste): self.paste() ev.accept() else: diff --git a/src/calibre/gui2/win_file_dialogs.py b/src/calibre/gui2/win_file_dialogs.py index 6ef132f48c..7952e3fd81 100644 --- a/src/calibre/gui2/win_file_dialogs.py +++ b/src/calibre/gui2/win_file_dialogs.py @@ -180,7 +180,7 @@ def run_file_dialog( def __init__(self): QEventLoop.__init__(self) - self.dialog_closed.connect(self.exit, type=Qt.QueuedConnection) + self.dialog_closed.connect(self.exit, type=Qt.ConnectionType.QueuedConnection) loop = Loop() server = PipeServer(pipename) @@ -190,7 +190,7 @@ def run_file_dialog( [HELPER], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE), data, loop.dialog_closed.emit) h.start() - loop.exec_(QEventLoop.ExcludeUserInputEvents) + loop.exec_(QEventLoop.ProcessEventsFlag.ExcludeUserInputEvents) def decode(x): x = x or b'' diff --git a/src/calibre/gui2/wizard/__init__.py b/src/calibre/gui2/wizard/__init__.py index ed01642d59..dccf0f0945 100644 --- a/src/calibre/gui2/wizard/__init__.py +++ b/src/calibre/gui2/wizard/__init__.py @@ -448,12 +448,12 @@ class ManufacturerModel(QAbstractListModel): return 1 def data(self, index, role): - if role == Qt.DisplayRole: + if role == Qt.ItemDataRole.DisplayRole: ans = self.manufacturers[index.row()] if ans == Device.manufacturer: ans = _('Generic') return ans - if role == Qt.UserRole: + if role == Qt.ItemDataRole.UserRole: return self.manufacturers[index.row()] return None @@ -476,9 +476,9 @@ class DeviceModel(QAbstractListModel): return 1 def data(self, index, role): - if role == Qt.DisplayRole: + if role == Qt.ItemDataRole.DisplayRole: return (self.devices[index.row()].name) - if role == Qt.UserRole: + if role == Qt.ItemDataRole.UserRole: return self.devices[index.row()] return None @@ -616,31 +616,31 @@ class DevicePage(QWizardPage, DeviceUI): idx = self.man_model.index_of(Device.manufacturer) previous = Device self.manufacturer_view.selectionModel().select(idx, - QItemSelectionModel.Select) - self.dev_model = DeviceModel(self.man_model.data(idx, Qt.UserRole)) + QItemSelectionModel.SelectionFlag.Select) + self.dev_model = DeviceModel(self.man_model.data(idx, Qt.ItemDataRole.UserRole)) idx = self.dev_model.index_of(previous) self.device_view.setModel(self.dev_model) self.device_view.selectionModel().select(idx, - QItemSelectionModel.Select) + QItemSelectionModel.SelectionFlag.Select) self.manufacturer_view.selectionModel().selectionChanged[(QItemSelection, QItemSelection)].connect(self.manufacturer_changed) def manufacturer_changed(self, current, previous): new = list(current.indexes())[0] - man = self.man_model.data(new, Qt.UserRole) + man = self.man_model.data(new, Qt.ItemDataRole.UserRole) self.dev_model = DeviceModel(man) self.device_view.setModel(self.dev_model) self.device_view.selectionModel().select(self.dev_model.index(0), - QItemSelectionModel.Select) + QItemSelectionModel.SelectionFlag.Select) def commit(self): idx = list(self.device_view.selectionModel().selectedIndexes())[0] - dev = self.dev_model.data(idx, Qt.UserRole) + dev = self.dev_model.data(idx, Qt.ItemDataRole.UserRole) dev.commit() dynamic.set('welcome_wizard_device', dev.id) def nextId(self): idx = list(self.device_view.selectionModel().selectedIndexes())[0] - dev = self.dev_model.data(idx, Qt.UserRole) + dev = self.dev_model.data(idx, Qt.ItemDataRole.UserRole) if dev in (Kindle, KindleDX, KindleFire, KindlePW, KindleVoyage): return KindlePage.ID if dev is iPhone: diff --git a/src/calibre/gui2/wizard/send_email.py b/src/calibre/gui2/wizard/send_email.py index 1023a50914..e4e4a4b46b 100644 --- a/src/calibre/gui2/wizard/send_email.py +++ b/src/calibre/gui2/wizard/send_email.py @@ -42,7 +42,7 @@ class TestEmail(QDialog): self.to.setText(pa) self.test_button = b = QPushButton(_('&Test'), self) b.clicked.connect(self.start_test) - self.test_done.connect(self.on_test_done, type=Qt.QueuedConnection) + self.test_done.connect(self.on_test_done, type=Qt.ConnectionType.QueuedConnection) self.h = h = QHBoxLayout() h.addWidget(le), h.addWidget(b) l.addLayout(h) @@ -53,7 +53,7 @@ class TestEmail(QDialog): l.addWidget(la) self.log = QPlainTextEdit(self) l.addWidget(self.log) - self.bb = bb = QDialogButtonBox(QDialogButtonBox.Close) + self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) bb.rejected.connect(self.reject), bb.accepted.connect(self.accept) l.addWidget(bb) @@ -89,7 +89,7 @@ class RelaySetup(QDialog): self.l = l = QGridLayout() 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) self.tl = QLabel(('
'+_('Setup sending email using') + @@ -117,7 +117,7 @@ class RelaySetup(QDialog): self.ptoggle = QCheckBox(_('&Show password'), self) l.addWidget(self.ptoggle, r, 2) self.ptoggle.stateChanged.connect( - lambda s: self.password.setEchoMode(self.password.Normal if s == Qt.Checked else self.password.Password)) + lambda s: self.password.setEchoMode(self.password.Normal if s == Qt.CheckState.Checked else self.password.Password)) self.username.setText(service['username']) self.password.setEchoMode(self.password.Password) self.bl = QLabel('
' + _( diff --git a/src/calibre/linux.py b/src/calibre/linux.py index a315fa6bc1..9a8b11db27 100644 --- a/src/calibre/linux.py +++ b/src/calibre/linux.py @@ -1302,7 +1302,7 @@ def write_appdata(key, entry, base, translators): def render_img(image, dest, width=128, height=128): from PyQt5.Qt import QImage, Qt - img = QImage(I(image)).scaled(width, height, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) + img = QImage(I(image)).scaled(width, height, Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation) img.save(dest) diff --git a/src/calibre/srv/metadata.py b/src/calibre/srv/metadata.py index 806d009b48..dbf875f2fc 100644 --- a/src/calibre/srv/metadata.py +++ b/src/calibre/srv/metadata.py @@ -572,7 +572,7 @@ def dump_tags_model(m): def dump_node(index, level=-1): if level > -1: - ans.append(indent*level + index.data(Qt.UserRole).dump_data()) + ans.append(indent*level + index.data(Qt.ItemDataRole.UserRole).dump_data()) for i in range(m.rowCount(index)): dump_node(m.index(i, 0, index), level + 1) if level == 0: diff --git a/src/calibre/utils/img.py b/src/calibre/utils/img.py index 67bf000735..74f8ce71ea 100644 --- a/src/calibre/utils/img.py +++ b/src/calibre/utils/img.py @@ -254,7 +254,7 @@ def save_cover_data_to( changed = fmt != orig_fmt if resize_to is not None: changed = True - img = img.scaled(resize_to[0], resize_to[1], Qt.IgnoreAspectRatio, Qt.SmoothTransformation) + img = img.scaled(resize_to[0], resize_to[1], Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation) owidth, oheight = img.width(), img.height() nwidth, nheight = tweaks['maximum_cover_size'] if minify_to is None else minify_to if letterbox: @@ -266,7 +266,7 @@ def save_cover_data_to( scaled, nwidth, nheight = fit_image(owidth, oheight, nwidth, nheight) if scaled: changed = True - img = img.scaled(nwidth, nheight, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) + img = img.scaled(nwidth, nheight, Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation) if img.hasAlphaChannel(): changed = True img = blend_image(img, bgcolor) @@ -293,9 +293,9 @@ def blend_on_canvas(img, width, height, bgcolor='#ffffff'): w, h = img.width(), img.height() scaled, nw, nh = fit_image(w, h, width, height) if scaled: - img = img.scaled(nw, nh, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) + img = img.scaled(nw, nh, Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation) w, h = nw, nh - canvas = QImage(width, height, QImage.Format_RGB32) + canvas = QImage(width, height, QImage.Format.Format_RGB32) canvas.fill(QColor(bgcolor)) overlay_image(img, canvas, (width - w)//2, (height - h)//2) return canvas @@ -304,7 +304,7 @@ def blend_on_canvas(img, width, height, bgcolor='#ffffff'): class Canvas(object): def __init__(self, width, height, bgcolor='#ffffff'): - self.img = QImage(width, height, QImage.Format_RGB32) + self.img = QImage(width, height, QImage.Format.Format_RGB32) self.img.fill(QColor(bgcolor)) def __enter__(self): @@ -323,7 +323,7 @@ class Canvas(object): def create_canvas(width, height, bgcolor='#ffffff'): 'Create a blank canvas of the specified size and color ' - img = QImage(width, height, QImage.Format_RGB32) + img = QImage(width, height, QImage.Format.Format_RGB32) img.fill(QColor(bgcolor)) return img @@ -331,8 +331,8 @@ def create_canvas(width, height, bgcolor='#ffffff'): def overlay_image(img, canvas=None, left=0, top=0): ' Overlay the `img` onto the canvas at the specified position ' if canvas is None: - canvas = QImage(img.size(), QImage.Format_RGB32) - canvas.fill(Qt.white) + canvas = QImage(img.size(), QImage.Format.Format_RGB32) + canvas.fill(Qt.GlobalColor.white) left, top = int(left), int(top) imageops.overlay(img, canvas, left, top) return canvas @@ -347,7 +347,7 @@ def texture_image(canvas, texture): def blend_image(img, bgcolor='#ffffff'): ' Used to convert images that have semi-transparent pixels to opaque by blending with the specified color ' - canvas = QImage(img.size(), QImage.Format_RGB32) + canvas = QImage(img.size(), QImage.Format.Format_RGB32) canvas.fill(QColor(bgcolor)) overlay_image(img, canvas) return canvas @@ -360,7 +360,7 @@ def add_borders_to_image(img, left=0, top=0, right=0, bottom=0, border_color='#f img = image_from_data(img) if not (left > 0 or right > 0 or top > 0 or bottom > 0): return img - canvas = QImage(img.width() + left + right, img.height() + top + bottom, QImage.Format_RGB32) + canvas = QImage(img.width() + left + right, img.height() + top + bottom, QImage.Format.Format_RGB32) canvas.fill(QColor(border_color)) overlay_image(img, canvas, left, top) return canvas @@ -381,7 +381,7 @@ def remove_borders_from_image(img, fuzz=None): def resize_image(img, width, height): - return img.scaled(int(width), int(height), Qt.IgnoreAspectRatio, Qt.SmoothTransformation) + return img.scaled(int(width), int(height), Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation) def resize_to_fit(img, width, height): @@ -408,10 +408,10 @@ def scale_image(data, width=60, height=80, compression_quality=70, as_png=False, if preserve_aspect_ratio: scaled, nwidth, nheight = fit_image(img.width(), img.height(), width, height) if scaled: - img = img.scaled(nwidth, nheight, Qt.KeepAspectRatio, Qt.SmoothTransformation) + img = img.scaled(nwidth, nheight, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation) else: if img.width() != width or img.height() != height: - img = img.scaled(width, height, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) + img = img.scaled(width, height, Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation) fmt = 'PNG' if as_png else 'JPEG' w, h = img.width(), img.height() return w, h, image_to_data(img, compression_quality=compression_quality, fmt=fmt) diff --git a/src/calibre/utils/open_with/osx.py b/src/calibre/utils/open_with/osx.py index d4c2de968c..930004568c 100644 --- a/src/calibre/utils/open_with/osx.py +++ b/src/calibre/utils/open_with/osx.py @@ -339,7 +339,7 @@ def get_icon(path, pixmap_to_data=None, as_data=False, size=64): break else: return - ans = ans.scaled(size, size, transformMode=Qt.SmoothTransformation) + ans = ans.scaled(size, size, transformMode=Qt.TransformationMode.SmoothTransformation) if as_data: ans = pixmap_to_data(ans) return ans diff --git a/src/calibre/utils/open_with/windows.py b/src/calibre/utils/open_with/windows.py index ac674dbf99..9479305035 100644 --- a/src/calibre/utils/open_with/windows.py +++ b/src/calibre/utils/open_with/windows.py @@ -63,8 +63,8 @@ def load_icon_resource_as_pixmap(icon_resource, size=ICON_SIZE): if area(pmap) >= q: if area(pmap) == q: return pmap - return pmap.scaled(size, size, aspectRatioMode=Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation) - return pixmaps[-1].scaled(size, size, aspectRatioMode=Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation) + return pmap.scaled(size, size, aspectRatioMode=Qt.AspectRatioMode.KeepAspectRatio, transformMode=Qt.TransformationMode.SmoothTransformation) + return pixmaps[-1].scaled(size, size, aspectRatioMode=Qt.AspectRatioMode.KeepAspectRatio, transformMode=Qt.TransformationMode.SmoothTransformation) def load_icon_resource(icon_resource, as_data=False, size=ICON_SIZE): @@ -84,7 +84,7 @@ def load_icon_for_file(path: str, as_data=False, size=ICON_SIZE): pmap = hicon_to_pixmap(hicon) if not pmap.isNull(): if pmap.width() != size: - pmap = pmap.scaled(size, size, aspectRatioMode=Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation) + pmap = pmap.scaled(size, size, aspectRatioMode=Qt.AspectRatioMode.KeepAspectRatio, transformMode=Qt.TransformationMode.SmoothTransformation) return pixmap_to_data(pmap) if as_data else pmap diff --git a/src/calibre/utils/rapydscript.py b/src/calibre/utils/rapydscript.py index d00c0c7ec7..28a03c0b1c 100644 --- a/src/calibre/utils/rapydscript.py +++ b/src/calibre/utils/rapydscript.py @@ -116,8 +116,8 @@ document.title = 'compiler initialized'; def create_script(src, name): s = QWebEngineScript() s.setName(name) - s.setInjectionPoint(QWebEngineScript.DocumentReady) - s.setWorldId(QWebEngineScript.ApplicationWorld) + s.setInjectionPoint(QWebEngineScript.InjectionPoint.DocumentReady) + s.setWorldId(QWebEngineScript.ScriptWorldId.ApplicationWorld) s.setRunsOnSubFrames(True) s.setSourceCode(src) return s @@ -136,7 +136,7 @@ document.title = 'compiler initialized'; self.spin_loop() def spin_loop(self): - QApplication.instance().processEvents(QEventLoop.ExcludeUserInputEvents) + QApplication.instance().processEvents(QEventLoop.ProcessEventsFlag.ExcludeUserInputEvents) def javaScriptConsoleMessage(self, level, msg, line_num, source_id): if level: @@ -152,7 +152,7 @@ document.title = 'compiler initialized'; options['write_name'] = True options['keep_docstrings'] = False src = 'var js = window.compiler.compile({}, {}); [js, window.write_cache]'.format(*map(json.dumps, (src, options))) - self.runJavaScript(src, QWebEngineScript.ApplicationWorld, self.compilation_done) + self.runJavaScript(src, QWebEngineScript.ScriptWorldId.ApplicationWorld, self.compilation_done) while self.working: self.spin_loop() if self.compiler_result is null or self.compiler_result is None: @@ -166,7 +166,7 @@ document.title = 'compiler initialized'; self.compiler_result = null = object() self.errors = [] self.working = True - self.runJavaScript(js, QWebEngineScript.ApplicationWorld, self.compilation_done) + self.runJavaScript(js, QWebEngineScript.ScriptWorldId.ApplicationWorld, self.compilation_done) while self.working: self.spin_loop() if self.compiler_result is null: @@ -346,8 +346,8 @@ def run_rapydscript_tests(): def create_script(src, name): s = QWebEngineScript() s.setName(name) - s.setInjectionPoint(QWebEngineScript.DocumentReady) - s.setWorldId(QWebEngineScript.ApplicationWorld) + s.setInjectionPoint(QWebEngineScript.InjectionPoint.DocumentReady) + s.setWorldId(QWebEngineScript.ScriptWorldId.ApplicationWorld) s.setRunsOnSubFrames(False) s.setSourceCode(src) return s @@ -365,11 +365,11 @@ def run_rapydscript_tests(): def title_changed(self, title): if title == 'initialized': self.titleChanged.disconnect() - self.runJavaScript('window.main()', QWebEngineScript.ApplicationWorld, self.callback) + self.runJavaScript('window.main()', QWebEngineScript.ScriptWorldId.ApplicationWorld, self.callback) def spin_loop(self): while self.working: - QApplication.instance().processEvents(QEventLoop.ExcludeUserInputEvents) + QApplication.instance().processEvents(QEventLoop.ProcessEventsFlag.ExcludeUserInputEvents) return self.result def callback(self, result): diff --git a/src/calibre/web/feeds/recipes/model.py b/src/calibre/web/feeds/recipes/model.py index 3db2bc31fe..76cacb1046 100644 --- a/src/calibre/web/feeds/recipes/model.py +++ b/src/calibre/web/feeds/recipes/model.py @@ -48,7 +48,7 @@ class NewsTreeItem(object): return None def flags(self): - return Qt.ItemIsEnabled|Qt.ItemIsSelectable + return Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsSelectable def sort(self): self.children.sort() @@ -80,18 +80,18 @@ class NewsCategory(NewsTreeItem): self.bold_font = (self.bold_font) def data(self, role): - if role == Qt.DisplayRole: + if role == Qt.ItemDataRole.DisplayRole: return (self.cdata + ' [%d]'%len(self.children)) - elif role == Qt.FontRole: + elif role == Qt.ItemDataRole.FontRole: return self.bold_font - elif role == Qt.ForegroundRole and self.category == _('Scheduled'): + elif role == Qt.ItemDataRole.ForegroundRole and self.category == _('Scheduled'): return (QColor(0, 255, 0)) - elif role == Qt.UserRole: + elif role == Qt.ItemDataRole.UserRole: return '::category::{}'.format(self.sortq[0]) return None def flags(self): - return Qt.ItemIsEnabled + return Qt.ItemFlag.ItemIsEnabled def __eq__(self, other): return self.cdata == other.cdata @@ -117,9 +117,9 @@ class NewsItem(NewsTreeItem): self.icon = custom_icon def data(self, role): - if role == Qt.DisplayRole: + if role == Qt.ItemDataRole.DisplayRole: return (self.title) - if role == Qt.DecorationRole: + if role == Qt.ItemDataRole.DecorationRole: if self.icon is None: icon = '%s.png'%self.urn[8:] p = QPixmap() @@ -134,7 +134,7 @@ class NewsItem(NewsTreeItem): else: self.icon = self.default_icon return self.icon - if role == Qt.UserRole: + if role == Qt.ItemDataRole.UserRole: return self.urn def __eq__(self, other): @@ -335,7 +335,7 @@ class RecipeModel(QAbstractItemModel, AdaptSQP): def flags(self, index): if not index.isValid(): - return Qt.ItemIsEnabled|Qt.ItemIsSelectable + return Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsSelectable item = index.internalPointer() return item.flags()