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.') + '

') self.series_increment.setPrefix('+') layout.addWidget(self.series_increment) - layout.addItem(QSpacerItem(20, 10, QSizePolicy.Expanding, QSizePolicy.Minimum)) + layout.addItem(QSpacerItem(20, 10, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum)) self.widgets.append(w) self.idx_widget.stateChanged.connect(self.a_c_checkbox_changed) self.force_number.stateChanged.connect(self.a_c_checkbox_changed) @@ -1363,7 +1363,7 @@ class BulkText(BulkBase): if self.col_metadata['is_multiple']: is_tags = not self.col_metadata['display'].get('is_names', False) self.make_widgets(parent, EditWithComplete, add_tags_edit_button=is_tags) - self.main_widget.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) + self.main_widget.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Preferred) self.adding_widget = self.main_widget if is_tags: @@ -1464,7 +1464,7 @@ class BulkText(BulkBase): _('You have entered values. In order to use this ' 'editor you must first discard them. ' 'Discard the values?')) - if d == QMessageBox.Cancel or d == QMessageBox.No: + if d == QMessageBox.StandardButton.Cancel or d == QMessageBox.StandardButton.No: return widget.setText('') d = TagEditor(self.parent, self.db, key=('#'+self.col_metadata['label'])) diff --git a/src/calibre/gui2/dbus_export/demo.py b/src/calibre/gui2/dbus_export/demo.py index aac3e88236..517ea20995 100644 --- a/src/calibre/gui2/dbus_export/demo.py +++ b/src/calibre/gui2/dbus_export/demo.py @@ -41,19 +41,19 @@ class MainWindow(QMainWindow): m.aboutToShow.connect(self.about_to_show_one) s = self.style() self.q = q = QAction('&Quit', self) - q.setShortcut(QKeySequence.Quit), q.setIcon(s.standardIcon(s.SP_DialogCancelButton)) + q.setShortcut(QKeySequence.StandardKey.Quit), q.setIcon(s.standardIcon(s.SP_DialogCancelButton)) q.triggered.connect(QApplication.quit) self.addAction(q) QApplication.instance().setWindowIcon(s.standardIcon(s.SP_ComputerIcon)) for i, icon in zip(range(3), map(s.standardIcon, (s.SP_DialogOkButton, s.SP_DialogHelpButton, s.SP_ArrowUp))): ac = m.addAction('One - &%d' % (i + 1)) - ac.setShortcut(QKeySequence(Qt.CTRL | (Qt.Key_1 + i), Qt.SHIFT | (Qt.Key_1 + i))) + ac.setShortcut(QKeySequence(Qt.Modifier.CTRL | (Qt.Key.Key_1 + i), Qt.Modifier.SHIFT | (Qt.Key.Key_1 + i))) ac.setIcon(icon) m.addSeparator() self.menu_two = m2 = m.addMenu('A &submenu') for i, icon in zip(range(3), map(s.standardIcon, (s.SP_DialogOkButton, s.SP_DialogCancelButton, s.SP_ArrowUp))): ac = m2.addAction('Two - &%d' % (i + 1)) - ac.setShortcut(QKeySequence(Qt.CTRL | (Qt.Key_A + i))) + ac.setShortcut(QKeySequence(Qt.Modifier.CTRL | (Qt.Key.Key_A + i))) ac.setIcon(icon) m2.aboutToShow.connect(self.about_to_show_two) m2.addSeparator(), m.addSeparator() @@ -162,7 +162,7 @@ class MainWindow(QMainWindow): app=QApplication([]) -app.setAttribute(Qt.AA_DontUseNativeMenuBar, False) +app.setAttribute(Qt.ApplicationAttribute.AA_DontUseNativeMenuBar, False) app.setApplicationName('com.calibre-ebook.DBusExportDemo') mw=MainWindow() mw.show() diff --git a/src/calibre/gui2/dbus_export/menu.py b/src/calibre/gui2/dbus_export/menu.py index a06acf6330..f97e3b09b2 100644 --- a/src/calibre/gui2/dbus_export/menu.py +++ b/src/calibre/gui2/dbus_export/menu.py @@ -83,7 +83,7 @@ class DBusMenu(QObject): QObject.__init__(self, parent) # Unity barfs is the Event DBUS method does not return immediately, so # handle it asynchronously - self.handle_event_signal.connect(self.handle_event, type=Qt.QueuedConnection) + self.handle_event_signal.connect(self.handle_event, type=Qt.ConnectionType.QueuedConnection) self.dbus_api = DBusMenuAPI(self, object_path, bus=bus) self.set_status = self.dbus_api.set_status self._next_id = 0 @@ -169,15 +169,15 @@ class DBusMenu(QObject): ac_id = self.action_to_id(ac) if ac_id is not None and hasattr(ev, 'action'): etype = ev.type() - if etype == QEvent.ActionChanged: + if etype == QEvent.Type.ActionChanged: ac_id = self.action_to_id(ev.action()) self.action_changes.add(ac_id) self.action_changed_timer.start() - elif etype == QEvent.ActionAdded: + elif etype == QEvent.Type.ActionAdded: self.layout_changes.add(ac_id) self.layout_changed_timer.start() self.add_action(ev.action()) - elif etype == QEvent.ActionRemoved: + elif etype == QEvent.Type.ActionRemoved: self.layout_changes.add(ac_id) self.layout_changed_timer.start() self.action_removed(ev.action()) diff --git a/src/calibre/gui2/dbus_export/menu2.py b/src/calibre/gui2/dbus_export/menu2.py index 531146d16f..958e3b0bf5 100644 --- a/src/calibre/gui2/dbus_export/menu2.py +++ b/src/calibre/gui2/dbus_export/menu2.py @@ -36,7 +36,7 @@ class DBusMenu(QObject): QObject.__init__(self, parent) # Unity barfs is the Event DBUS method does not return immediately, so # handle it asynchronously - self.handle_event_signal.connect(self.handle_event, type=Qt.QueuedConnection) + self.handle_event_signal.connect(self.handle_event, type=Qt.ConnectionType.QueuedConnection) self.dbus_api = DBusMenuAPI(self, object_path, bus=bus) self.set_status = self.dbus_api.set_status self._next_id = 0 diff --git a/src/calibre/gui2/dbus_export/tray.py b/src/calibre/gui2/dbus_export/tray.py index 36a10e2150..1478d93c59 100644 --- a/src/calibre/gui2/dbus_export/tray.py +++ b/src/calibre/gui2/dbus_export/tray.py @@ -43,7 +43,7 @@ class StatusNotifierItem(QObject): self._icon = QIcon(path) else: self._icon = QApplication.instance().windowIcon() - self.show_menu.connect(self._show_menu, type=Qt.QueuedConnection) + self.show_menu.connect(self._show_menu, type=Qt.ConnectionType.QueuedConnection) _sni_count += 1 kw['num'] = _sni_count self.dbus_api = StatusNotifierItemAPI(self, **kw) @@ -99,7 +99,7 @@ class StatusNotifierItem(QObject): return False def emit_activated(self): - self.activated.emit(QSystemTrayIcon.Trigger) + self.activated.emit(QSystemTrayIcon.ActivationReason.Trigger) _status_item_menu_count = 0 @@ -201,16 +201,16 @@ class StatusNotifierItemAPI(Object): @dbus_method(IFACE, in_signature='ii', out_signature='') def Activate(self, x, y): - self.notifier.activated.emit(QSystemTrayIcon.Trigger) + self.notifier.activated.emit(QSystemTrayIcon.ActivationReason.Trigger) @dbus_method(IFACE, in_signature='u', out_signature='') def XAyatanaSecondaryActivate(self, timestamp): # This is called when the user middle clicks the icon in Unity - self.notifier.activated.emit(QSystemTrayIcon.MiddleClick) + self.notifier.activated.emit(QSystemTrayIcon.ActivationReason.MiddleClick) @dbus_method(IFACE, in_signature='ii', out_signature='') def SecondaryActivate(self, x, y): - self.notifier.activated.emit(QSystemTrayIcon.MiddleClick) + self.notifier.activated.emit(QSystemTrayIcon.ActivationReason.MiddleClick) @dbus_method(IFACE, in_signature='is', out_signature='') def Scroll(self, delta, orientation): diff --git a/src/calibre/gui2/dbus_export/utils.py b/src/calibre/gui2/dbus_export/utils.py index 7e0d499aff..4bbb5dee12 100644 --- a/src/calibre/gui2/dbus_export/utils.py +++ b/src/calibre/gui2/dbus_export/utils.py @@ -81,7 +81,7 @@ def qicon_to_sni_image_list(qicon): for size in sizes: # Convert to DBUS struct of width, height, and image data in ARGB32 # in network endianness - i = qicon.pixmap(size).toImage().convertToFormat(QImage.Format_ARGB32) + i = qicon.pixmap(size).toImage().convertToFormat(QImage.Format.Format_ARGB32) w, h = i.width(), i.height() data = i.constBits().asstring(4 * w * h) if socket.htonl(1) != 1: @@ -106,13 +106,13 @@ def swap_mnemonic_char(text, from_char='&', to_char='_'): def key_sequence_to_dbus_shortcut(qks): for key in qks: - if key == -1 or key == Qt.Key_unknown: + if key == -1 or key == Qt.Key.Key_unknown: continue items = [] - for mod, name in iteritems({Qt.META:'Super', Qt.CTRL:'Control', Qt.ALT:'Alt', Qt.SHIFT:'Shift'}): + for mod, name in iteritems({Qt.Modifier.META:'Super', Qt.Modifier.CTRL:'Control', Qt.Modifier.ALT:'Alt', Qt.Modifier.SHIFT:'Shift'}): if key & mod == mod: items.append(name) - key &= int(~(Qt.ShiftModifier | Qt.ControlModifier | Qt.AltModifier | Qt.MetaModifier | Qt.KeypadModifier)) + key &= int(~(Qt.KeyboardModifier.ShiftModifier | Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.AltModifier | Qt.KeyboardModifier.MetaModifier | Qt.KeyboardModifier.KeypadModifier)) text = QKeySequence(key).toString() if text: text = {'+':'plus', '-':'minus'}.get(text, text) diff --git a/src/calibre/gui2/dbus_export/widgets.py b/src/calibre/gui2/dbus_export/widgets.py index 0cfe34b790..5e7416a6ef 100644 --- a/src/calibre/gui2/dbus_export/widgets.py +++ b/src/calibre/gui2/dbus_export/widgets.py @@ -100,11 +100,11 @@ class ExportedMenuBar(QMenuBar): # {{{ def eventFilter(self, obj, ev): etype = ev.type() - if etype == QEvent.Show: + if etype == QEvent.Type.Show: # Hiding a window causes the registrar to auto-unregister it, so we # have to re-register it on show events. self.register() - elif etype == QEvent.WinIdChange: + elif etype == QEvent.Type.WinIdChange: self.unregister() self.register() return False @@ -206,7 +206,7 @@ class Factory(QObject): self.status_notifier = bool(self.bus.call_blocking(*args, timeout=0.1)) def create_window_menubar(self, parent): - if not QApplication.instance().testAttribute(Qt.AA_DontUseNativeMenuBar) and self.has_global_menu: + if not QApplication.instance().testAttribute(Qt.ApplicationAttribute.AA_DontUseNativeMenuBar) and self.has_global_menu: ans = ExportedMenuBar(parent, self.menu_registrar, self.bus) self.prune_dead_refs() self.window_menus.append(weakref.ref(ans)) diff --git a/src/calibre/gui2/device.py b/src/calibre/gui2/device.py index 91dee36e3d..f73edec0f9 100644 --- a/src/calibre/gui2/device.py +++ b/src/calibre/gui2/device.py @@ -128,7 +128,7 @@ def device_name_for_plugboards(device_class): class BusyCursor(object): def __enter__(self): - QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) + QApplication.setOverrideCursor(QCursor(Qt.CursorShape.WaitCursor)) def __exit__(self, *args): QApplication.restoreOverrideCursor() @@ -893,7 +893,7 @@ class DeviceMixin(object): # {{{ def init_device_mixin(self): self.device_error_dialog = error_dialog(self, _('Error'), _('Error communicating with device'), ' ') - self.device_error_dialog.setModal(Qt.NonModal) + self.device_error_dialog.setModal(Qt.WindowModality.NonModal) self.device_manager = DeviceManager(FunctionDispatcher(self.device_detected), self.job_manager, Dispatcher(self.status_bar.show_message), Dispatcher(self.show_open_feedback), @@ -973,7 +973,7 @@ class DeviceMixin(object): # {{{ config_dialog.setWindowIcon(QIcon(I('config.png'))) l = QVBoxLayout(config_dialog) config_dialog.setLayout(l) - bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel) + bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel) bb.accepted.connect(config_dialog.accept) bb.rejected.connect(config_dialog.reject) l.addWidget(cw) @@ -1259,7 +1259,7 @@ class DeviceMixin(object): # {{{ elif f in aval_out_formats: formats.append((f, _('0 of %i books') % len(rows), True)) d = ChooseFormatDeviceDialog(self, _('Choose format to send to device'), formats) - if d.exec_() != QDialog.Accepted: + if d.exec_() != QDialog.DialogCode.Accepted: return if d.format(): fmt = d.format().lower() @@ -1891,7 +1891,7 @@ class DeviceMixin(object): # {{{ # loop with preventing App Not Responding errors if current_book_count % 10 == 0: QCoreApplication.processEvents( - flags=QEventLoop.ExcludeUserInputEvents|QEventLoop.ExcludeSocketNotifiers) + flags=QEventLoop.ProcessEventsFlag.ExcludeUserInputEvents|QEventLoop.ProcessEventsFlag.ExcludeSocketNotifiers) current_book_count += 1 book.in_library = None if getattr(book, 'uuid', None) in self.db_book_uuid_cache: diff --git a/src/calibre/gui2/device_drivers/configwidget.py b/src/calibre/gui2/device_drivers/configwidget.py index c8b5efb062..ab91042450 100644 --- a/src/calibre/gui2/device_drivers/configwidget.py +++ b/src/calibre/gui2/device_drivers/configwidget.py @@ -42,9 +42,9 @@ class ConfigWidget(QWidget, Ui_ConfigWidget): disabled_formats = all_formats.difference(format_map) for format in format_map + sorted(disabled_formats): item = QListWidgetItem(format, self.columns) - item.setData(Qt.UserRole, (format)) - item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable|Qt.ItemIsSelectable) - item.setCheckState(Qt.Checked if format in format_map else Qt.Unchecked) + item.setData(Qt.ItemDataRole.UserRole, (format)) + item.setFlags(Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsUserCheckable|Qt.ItemFlag.ItemIsSelectable) + item.setCheckState(Qt.CheckState.Checked if format in format_map else Qt.CheckState.Unchecked) self.column_up.clicked.connect(self.up_column) self.column_down.clicked.connect(self.down_column) @@ -138,9 +138,9 @@ class ConfigWidget(QWidget, Ui_ConfigWidget): def format_map(self): formats = [ - unicode_type(self.columns.item(i).data(Qt.UserRole) or '') + unicode_type(self.columns.item(i).data(Qt.ItemDataRole.UserRole) or '') for i in range(self.columns.count()) - if self.columns.item(i).checkState()==Qt.Checked + if self.columns.item(i).checkState()==Qt.CheckState.Checked ] return formats diff --git a/src/calibre/gui2/device_drivers/mtp_config.py b/src/calibre/gui2/device_drivers/mtp_config.py index 578614164c..8a0667931b 100644 --- a/src/calibre/gui2/device_drivers/mtp_config.py +++ b/src/calibre/gui2/device_drivers/mtp_config.py @@ -34,9 +34,9 @@ class FormatsConfig(QWidget): # {{{ unchecked_formats = sorted(all_formats - set(format_map)) for fmt in format_map + unchecked_formats: item = QListWidgetItem(fmt, f) - item.setData(Qt.UserRole, fmt) - item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable|Qt.ItemIsSelectable) - item.setCheckState(Qt.Checked if fmt in format_map else Qt.Unchecked) + item.setData(Qt.ItemDataRole.UserRole, fmt) + item.setFlags(Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsUserCheckable|Qt.ItemFlag.ItemIsSelectable) + item.setCheckState(Qt.CheckState.Checked if fmt in format_map else Qt.CheckState.Unchecked) self.button_up = b = QToolButton(self) b.setIcon(QIcon(I('arrow-up.png'))) @@ -50,8 +50,8 @@ class FormatsConfig(QWidget): # {{{ @property def format_map(self): - return [unicode_type(self.f.item(i).data(Qt.UserRole) or '') for i in - range(self.f.count()) if self.f.item(i).checkState()==Qt.Checked] + return [unicode_type(self.f.item(i).data(Qt.ItemDataRole.UserRole) or '') for i in + range(self.f.count()) if self.f.item(i).checkState()==Qt.CheckState.Checked] def validate(self): if not self.format_map: @@ -181,21 +181,21 @@ class IgnoredDevices(QWidget): # {{{ name = x[0] name = '%s [%s]'%(name, dev) item = QListWidgetItem(name, f) - item.setData(Qt.UserRole, dev) - item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable|Qt.ItemIsSelectable) - item.setCheckState(Qt.Checked if dev in blacklist else Qt.Unchecked) + item.setData(Qt.ItemDataRole.UserRole, dev) + item.setFlags(Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsUserCheckable|Qt.ItemFlag.ItemIsSelectable) + item.setCheckState(Qt.CheckState.Checked if dev in blacklist else Qt.CheckState.Unchecked) @property def blacklist(self): - return [unicode_type(self.f.item(i).data(Qt.UserRole) or '') for i in - range(self.f.count()) if self.f.item(i).checkState()==Qt.Checked] + return [unicode_type(self.f.item(i).data(Qt.ItemDataRole.UserRole) or '') for i in + range(self.f.count()) if self.f.item(i).checkState()==Qt.CheckState.Checked] def ignore_device(self, snum): for i in range(self.f.count()): i = self.f.item(i) - c = unicode_type(i.data(Qt.UserRole) or '') + c = unicode_type(i.data(Qt.ItemDataRole.UserRole) or '') if c == snum: - i.setCheckState(Qt.Checked) + i.setCheckState(Qt.CheckState.Checked) break # }}} @@ -306,7 +306,7 @@ class FormatRules(QGroupBox): self.b = b = QPushButton(QIcon(I('plus.png')), _('Add a &new rule')) l.addWidget(b) b.clicked.connect(self.add_rule) - self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Ignored) + self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Ignored) @property def device(self): @@ -421,7 +421,7 @@ class MTPConfig(QTabWidget): v.setMinimumWidth(400) v.setMinimumHeight(350) l.addWidget(v) - bb = d.bb = QDialogButtonBox(QDialogButtonBox.Close) + bb = d.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) bb.accepted.connect(d.accept) bb.rejected.connect(d.reject) l.addWidget(bb) @@ -509,7 +509,7 @@ class SendError(QDialog): la.setWordWrap(True) la.setMinimumWidth(500) l.addWidget(la) - self.bb = bb = QDialogButtonBox(QDialogButtonBox.Close) + self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) self.b = bb.addButton(_('Configure'), bb.AcceptRole) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) @@ -543,7 +543,7 @@ if __name__ == '__main__': d.l = QVBoxLayout() d.setLayout(d.l) d.l.addWidget(cw) - bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel) + bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel) d.l.addWidget(bb) bb.accepted.connect(d.accept) bb.rejected.connect(d.reject) diff --git a/src/calibre/gui2/device_drivers/mtp_folder_browser.py b/src/calibre/gui2/device_drivers/mtp_folder_browser.py index cc5062c7ff..120bfe58b7 100644 --- a/src/calibre/gui2/device_drivers/mtp_folder_browser.py +++ b/src/calibre/gui2/device_drivers/mtp_folder_browser.py @@ -20,12 +20,12 @@ def browser_item(f, parent): if not f.is_folder: name += ' [%s]'%f.last_mod_string ans = QTreeWidgetItem(parent, [name]) - ans.setData(0, Qt.UserRole, f.full_path) + ans.setData(0, Qt.ItemDataRole.UserRole, f.full_path) if f.is_folder: ext = 'dir' else: ext = f.name.rpartition('.')[-1] - ans.setData(0, Qt.DecorationRole, file_icon_provider().icon_from_ext(ext)) + ans.setData(0, Qt.ItemDataRole.DecorationRole, file_icon_provider().icon_from_ext(ext)) return ans @@ -55,7 +55,7 @@ class Storage(QTreeWidget): def current_item(self): item = self.currentItem() if item is not None: - return (self.object_id, item.data(0, Qt.UserRole)) + return (self.object_id, item.data(0, Qt.ItemDataRole.UserRole)) return None @@ -88,7 +88,7 @@ class Browser(QDialog): self.setLayout(l) self.folders = cw = Folders(filesystem_cache, show_files=show_files) l.addWidget(cw) - bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel) + bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel) l.addWidget(bb) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) @@ -131,8 +131,8 @@ class IgnoredFolders(QDialog): l.addWidget(la) la.setWordWrap(True) - self.bb = QDialogButtonBox(QDialogButtonBox.Ok | - QDialogButtonBox.Cancel) + self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | + QDialogButtonBox.StandardButton.Cancel) self.bb.accepted.connect(self.accept) self.bb.rejected.connect(self.reject) self.sab = self.bb.addButton(_('Select &all'), self.bb.ActionRole) @@ -150,11 +150,11 @@ class IgnoredFolders(QDialog): root = w.invisibleRootItem() w.itemChanged.disconnect(self.item_changed) try: - if item.checkState(0) == Qt.Checked: + if item.checkState(0) == Qt.CheckState.Checked: # Ensure that the parents of this item are checked p = item.parent() while p is not None and p is not root: - p.setCheckState(0, Qt.Checked) + p.setCheckState(0, Qt.CheckState.Checked) p = p.parent() # Set the state of all descendants to the same state as this item for child in self.iterchildren(item): @@ -173,24 +173,24 @@ class IgnoredFolders(QDialog): def create_item(self, f, parent): name = f.name ans = QTreeWidgetItem(parent, [name]) - ans.setData(0, Qt.UserRole, '/'.join(f.full_path[1:])) - ans.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) + ans.setData(0, Qt.ItemDataRole.UserRole, '/'.join(f.full_path[1:])) + ans.setFlags(Qt.ItemFlag.ItemIsUserCheckable | Qt.ItemFlag.ItemIsEnabled) ans.setCheckState(0, - Qt.Unchecked if self.dev.is_folder_ignored(f.storage_id, f.full_path[1:]) else Qt.Checked) - ans.setData(0, Qt.DecorationRole, file_icon_provider().icon_from_ext('dir')) + Qt.CheckState.Unchecked if self.dev.is_folder_ignored(f.storage_id, f.full_path[1:]) else Qt.CheckState.Checked) + ans.setData(0, Qt.ItemDataRole.DecorationRole, file_icon_provider().icon_from_ext('dir')) return ans def select_all(self): w = self.tabs.currentWidget() for i in range(w.invisibleRootItem().childCount()): c = w.invisibleRootItem().child(i) - c.setCheckState(0, Qt.Checked) + c.setCheckState(0, Qt.CheckState.Checked) def select_none(self): w = self.tabs.currentWidget() for i in range(w.invisibleRootItem().childCount()): c = w.invisibleRootItem().child(i) - c.setCheckState(0, Qt.Unchecked) + c.setCheckState(0, Qt.CheckState.Unchecked) @property def ignored_folders(self): @@ -198,9 +198,9 @@ class IgnoredFolders(QDialog): for w in self.widgets: folders = set() for node in self.iterchildren(w.invisibleRootItem()): - if node.checkState(0) == Qt.Checked: + if node.checkState(0) == Qt.CheckState.Checked: continue - path = unicode_type(node.data(0, Qt.UserRole) or '') + path = unicode_type(node.data(0, Qt.ItemDataRole.UserRole) or '') parent = path.rpartition('/')[0] if '/' not in path or icu_lower(parent) not in folders: folders.add(icu_lower(path)) diff --git a/src/calibre/gui2/device_drivers/tabbed_device_config.py b/src/calibre/gui2/device_drivers/tabbed_device_config.py index d6bff765a2..b227e99cef 100644 --- a/src/calibre/gui2/device_drivers/tabbed_device_config.py +++ b/src/calibre/gui2/device_drivers/tabbed_device_config.py @@ -311,7 +311,7 @@ class ExtraCustomization(DeviceConfigTab): # {{{ self.extra_layout.addWidget(l, row_func(i + 2, 0), col_func(i)) self.extra_layout.addWidget(self.opt_extra_customization[i], row_func(i + 2, 1), col_func(i)) - spacerItem1 = QSpacerItem(10, 10, QSizePolicy.Minimum, QSizePolicy.Expanding) + spacerItem1 = QSpacerItem(10, 10, QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Expanding) self.extra_layout.addItem(spacerItem1, row_func(i + 2 + 2, 1), 0, 1, 2) self.extra_layout.setRowStretch(row_func(i + 2 + 2, 1), 2) else: @@ -386,7 +386,7 @@ if __name__ == '__main__': d.l = QVBoxLayout() d.setLayout(d.l) d.l.addWidget(cw) - bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel) + bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel) d.l.addWidget(bb) bb.accepted.connect(d.accept) bb.rejected.connect(d.reject) diff --git a/src/calibre/gui2/dialogs/add_empty_book.py b/src/calibre/gui2/dialogs/add_empty_book.py index ea4bc0ef3c..03aaf1288f 100644 --- a/src/calibre/gui2/dialogs/add_empty_book.py +++ b/src/calibre/gui2/dialogs/add_empty_book.py @@ -105,7 +105,7 @@ class AddEmptyBookDialog(QDialog): cf.setChecked(gprefs.get('create_empty_copy_dup_formats', False)) self._layout.addWidget(cf, 10, 0, 1, -1) - button_box = self.bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) + button_box = self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) button_box.accepted.connect(self.accept) button_box.rejected.connect(self.reject) self._layout.addWidget(button_box, 11, 0, 1, -1) diff --git a/src/calibre/gui2/dialogs/add_from_isbn.py b/src/calibre/gui2/dialogs/add_from_isbn.py index f2a5ec164f..65675f5923 100644 --- a/src/calibre/gui2/dialogs/add_from_isbn.py +++ b/src/calibre/gui2/dialogs/add_from_isbn.py @@ -40,13 +40,13 @@ class AddFromISBN(QDialog): self.l = l = QVBoxLayout(self) self.h = h = QHBoxLayout() l.addLayout(h) - self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel, self) + self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel, self) bb.button(bb.Ok).setText(_('&OK')) l.addWidget(bb), bb.accepted.connect(self.accept), bb.rejected.connect(self.reject) self.ll = l = QVBoxLayout() h.addLayout(l) self.isbn_box = i = QPlainTextEdit(self) - i.setFocus(Qt.OtherFocusReason) + i.setFocus(Qt.FocusReason.OtherFocusReason) l.addWidget(i) self.paste_button = b = QPushButton(_("&Paste from clipboard"), self) l.addWidget(b), b.clicked.connect(self.paste) diff --git a/src/calibre/gui2/dialogs/authors_edit.py b/src/calibre/gui2/dialogs/authors_edit.py index d5f8b81a86..b5dcc4844f 100644 --- a/src/calibre/gui2/dialogs/authors_edit.py +++ b/src/calibre/gui2/dialogs/authors_edit.py @@ -30,7 +30,7 @@ class ItemDelegate(QStyledItemDelegate): return QStyledItemDelegate.sizeHint(self, *args) + QSize(0, 15) def setEditorData(self, editor, index): - name = unicode_type(index.data(Qt.DisplayRole) or '') + name = unicode_type(index.data(Qt.ItemDataRole.DisplayRole) or '') editor.setText(name) editor.lineEdit().selectAll() @@ -41,7 +41,7 @@ class ItemDelegate(QStyledItemDelegate): def createEditor(self, parent, option, index): self.ed = EditWithComplete(parent) - self.ed.setFocusPolicy(Qt.StrongFocus) + self.ed.setFocusPolicy(Qt.FocusPolicy.StrongFocus) init_line_edit(self.ed, self.all_authors) return self.ed @@ -56,7 +56,7 @@ class List(QListWidget): self.setDragDropMode(self.InternalMove) self.setAlternatingRowColors(True) self.d = ItemDelegate(all_authors, self) - self.d.edited.connect(self.edited, type=Qt.QueuedConnection) + self.d.edited.connect(self.edited, type=Qt.ConnectionType.QueuedConnection) self.setItemDelegate(self.d) def delete_selected(self): @@ -64,7 +64,7 @@ class List(QListWidget): self.takeItem(self.row(item)) def keyPressEvent(self, ev): - if ev.key() == Qt.Key_Delete: + if ev.key() == Qt.Key.Key_Delete: self.delete_selected() ev.accept() return @@ -85,7 +85,7 @@ class List(QListWidget): def mark_as_editable(self): for i in range(self.count()): item = self.item(i) - item.setFlags(item.flags() | Qt.ItemIsEditable) + item.setFlags(item.flags() | Qt.ItemFlag.ItemIsEditable) def edited(self, i): item = self.item(i) @@ -103,7 +103,7 @@ class Edit(EditWithComplete): returnPressed = pyqtSignal() def keyPressEvent(self, ev): - if ev.key() in (Qt.Key_Return, Qt.Key_Enter): + if ev.key() in (Qt.Key.Key_Return, Qt.Key.Key_Enter): ev.accept() self.returnPressed.emit() return @@ -150,7 +150,7 @@ class AuthorsEdit(QDialog): b.setIcon(QIcon(I('minus.png'))) b.clicked.connect(self.al.delete_selected) - self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) + self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) l.addWidget(bb, 3, 0, 1, 3) @@ -160,7 +160,7 @@ class AuthorsEdit(QDialog): geom = gprefs.get('authors-edit-geometry', None) if geom is not None: QApplication.instance().safe_restore_geometry(self, geom) - self.author.setFocus(Qt.OtherFocusReason) + self.author.setFocus(Qt.FocusReason.OtherFocusReason) def save_geometry(self): gprefs.set('authors-edit-geometry', bytearray(self.saveGeometry())) diff --git a/src/calibre/gui2/dialogs/book_info.py b/src/calibre/gui2/dialogs/book_info.py index fa62dd670f..78f0f406f0 100644 --- a/src/calibre/gui2/dialogs/book_info.py +++ b/src/calibre/gui2/dialogs/book_info.py @@ -125,8 +125,8 @@ class BookInfo(QDialog): def __init__(self, parent, view, row, link_delegate): QDialog.__init__(self, parent) - self.normal_brush = QBrush(Qt.white) - self.marked_brush = QBrush(Qt.lightGray) + self.normal_brush = QBrush(Qt.GlobalColor.white) + self.marked_brush = QBrush(Qt.GlobalColor.lightGray) self.marked = None self.gui = parent self.splitter = QSplitter(self) @@ -146,10 +146,10 @@ class BookInfo(QDialog): self.details = Details(parent.book_details.book_info, self) self.details.anchor_clicked.connect(self.on_link_clicked) self.link_delegate = link_delegate - self.details.setAttribute(Qt.WA_OpaquePaintEvent, False) + self.details.setAttribute(Qt.WidgetAttribute.WA_OpaquePaintEvent, False) palette = self.details.palette() self.details.setAcceptDrops(False) - palette.setBrush(QPalette.Base, Qt.transparent) + palette.setBrush(QPalette.ColorRole.Base, Qt.GlobalColor.transparent) self.details.setPalette(palette) self.c = QWidget(self) @@ -187,9 +187,9 @@ class BookInfo(QDialog): self.ps = QShortcut(QKeySequence('Alt+Left'), self) self.ps.activated.connect(self.previous) self.next_button.setToolTip(_('Next [%s]')% - unicode_type(self.ns.key().toString(QKeySequence.NativeText))) + unicode_type(self.ns.key().toString(QKeySequence.SequenceFormat.NativeText))) self.previous_button.setToolTip(_('Previous [%s]')% - unicode_type(self.ps.key().toString(QKeySequence.NativeText))) + unicode_type(self.ps.key().toString(QKeySequence.SequenceFormat.NativeText))) geom = QCoreApplication.instance().desktop().availableGeometry(self) screen_height = geom.height() - 100 @@ -287,7 +287,7 @@ class BookInfo(QDialog): except AttributeError: dpr = self.devicePixelRatio() pixmap = pixmap.scaled(int(dpr * new_width), int(dpr * new_height), - Qt.KeepAspectRatio, Qt.SmoothTransformation) + Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation) pixmap.setDevicePixelRatio(dpr) self.cover.set_pixmap(pixmap) self.update_cover_tooltip() diff --git a/src/calibre/gui2/dialogs/check_library.py b/src/calibre/gui2/dialogs/check_library.py index 070ce7ed13..d5fe06cf3e 100644 --- a/src/calibre/gui2/dialogs/check_library.py +++ b/src/calibre/gui2/dialogs/check_library.py @@ -34,7 +34,7 @@ class DBCheck(QDialog): # {{{ self.l1.setWordWrap(True) self.l.addWidget(self.l1) self.msg = QLabel('') - self.update_msg.connect(self.msg.setText, type=Qt.QueuedConnection) + self.update_msg.connect(self.msg.setText, type=Qt.ConnectionType.QueuedConnection) self.l.addWidget(self.msg) self.msg.setWordWrap(True) self.resize(self.sizeHint() + QSize(100, 50)) @@ -264,33 +264,33 @@ class CheckLibraryDialog(QDialog): tl = Item() tl.setText(0, h) if fixable and list: - tl.setData(1, Qt.UserRole, self.is_fixable) + tl.setData(1, Qt.ItemDataRole.UserRole, self.is_fixable) tl.setText(1, _('(fixable)')) - tl.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable) + tl.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsUserCheckable) tl.setCheckState(1, False) else: - tl.setData(1, Qt.UserRole, self.is_deletable) - tl.setData(2, Qt.UserRole, self.is_deletable) + tl.setData(1, Qt.ItemDataRole.UserRole, self.is_deletable) + tl.setData(2, Qt.ItemDataRole.UserRole, self.is_deletable) tl.setText(1, _('(deletable)')) - tl.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable) + tl.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsUserCheckable) tl.setCheckState(1, False) if attr == 'extra_covers': - tl.setData(2, Qt.UserRole, self.is_deletable) + tl.setData(2, Qt.ItemDataRole.UserRole, self.is_deletable) tl.setText(2, _('(deletable)')) - tl.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable) + tl.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsUserCheckable) tl.setCheckState(2, False) self.top_level_items[attr] = tl for problem in list_: it = Item() if checkable: - it.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable) + it.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsUserCheckable) it.setCheckState(2, False) - it.setData(2, Qt.UserRole, self.is_deletable) + it.setData(2, Qt.ItemDataRole.UserRole, self.is_deletable) else: - it.setFlags(Qt.ItemIsEnabled) + it.setFlags(Qt.ItemFlag.ItemIsEnabled) it.setText(0, problem[0]) - it.setData(0, Qt.UserRole, problem[2]) + it.setData(0, Qt.ItemDataRole.UserRole, problem[2]) it.setText(2, problem[1]) tl.addChild(it) self.all_items.append(it) @@ -331,8 +331,8 @@ class CheckLibraryDialog(QDialog): all_checked = True for i in range(0, node.childCount()): c = node.child(i).checkState(2) - checked = checked or c == Qt.Checked - all_checked = all_checked and c == Qt.Checked + checked = checked or c == Qt.CheckState.Checked + all_checked = all_checked and c == Qt.CheckState.Checked return (checked, all_checked) def any_child_delete_checked(): @@ -344,15 +344,15 @@ class CheckLibraryDialog(QDialog): def any_fix_checked(): for parent in self.top_level_items.values(): - if (parent.data(1, Qt.UserRole) == self.is_fixable and - parent.checkState(1) == Qt.Checked): + if (parent.data(1, Qt.ItemDataRole.UserRole) == self.is_fixable and + parent.checkState(1) == Qt.CheckState.Checked): return True return False if item in self.top_level_items.values(): if item.childCount() > 0: - if item.data(1, Qt.UserRole) == self.is_fixable and column == 1: - if item.data(2, Qt.UserRole) == self.is_deletable: + if item.data(1, Qt.ItemDataRole.UserRole) == self.is_fixable and column == 1: + if item.data(2, Qt.ItemDataRole.UserRole) == self.is_deletable: set_delete_boxes(item, 2, False) else: set_delete_boxes(item, column, item.checkState(column)) @@ -361,40 +361,40 @@ class CheckLibraryDialog(QDialog): item.setCheckState(1, False) self.log.blockSignals(False) else: - item.setCheckState(column, Qt.Unchecked) + item.setCheckState(column, Qt.CheckState.Unchecked) else: for parent in self.top_level_items.values(): - if parent.data(2, Qt.UserRole) == self.is_deletable: + if parent.data(2, Qt.ItemDataRole.UserRole) == self.is_deletable: (child_chkd, all_chkd) = is_child_delete_checked(parent) if all_chkd and child_chkd: - check_state = Qt.Checked + check_state = Qt.CheckState.Checked elif child_chkd: - check_state = Qt.PartiallyChecked + check_state = Qt.CheckState.PartiallyChecked else: - check_state = Qt.Unchecked + check_state = Qt.CheckState.Unchecked self.log.blockSignals(True) - if parent.data(1, Qt.UserRole) == self.is_fixable: + if parent.data(1, Qt.ItemDataRole.UserRole) == self.is_fixable: parent.setCheckState(2, check_state) else: parent.setCheckState(1, check_state) - if child_chkd and parent.data(1, Qt.UserRole) == self.is_fixable: - parent.setCheckState(1, Qt.Unchecked) + if child_chkd and parent.data(1, Qt.ItemDataRole.UserRole) == self.is_fixable: + parent.setCheckState(1, Qt.CheckState.Unchecked) self.log.blockSignals(False) self.delete_button.setEnabled(any_child_delete_checked()) self.fix_button.setEnabled(any_fix_checked()) def mark_for_fix(self): for it in self.top_level_items.values(): - if (it.flags() & Qt.ItemIsUserCheckable and - it.data(1, Qt.UserRole) == self.is_fixable and + if (it.flags() & Qt.ItemFlag.ItemIsUserCheckable and + it.data(1, Qt.ItemDataRole.UserRole) == self.is_fixable and it.childCount() > 0): - it.setCheckState(1, Qt.Checked) + it.setCheckState(1, Qt.CheckState.Checked) def mark_for_delete(self): for it in self.all_items: - if (it.flags() & Qt.ItemIsUserCheckable and - it.data(2, Qt.UserRole) == self.is_deletable): - it.setCheckState(2, Qt.Checked) + if (it.flags() & Qt.ItemFlag.ItemIsUserCheckable and + it.data(2, Qt.ItemDataRole.UserRole) == self.is_deletable): + it.setCheckState(2, Qt.CheckState.Checked) def delete_marked(self): if not confirm('

'+_('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 = [ '

', '

%s

'%book.title, @@ -291,15 +291,15 @@ class ResultsView(QTableView): # {{{ return if not index.isValid(): index = self.model().index(0, 0) - book = self.model().data(index, Qt.UserRole) + book = self.model().data(index, Qt.ItemDataRole.UserRole) self.book_selected.emit(book) def get_result(self): self.select_index(self.currentIndex()) def keyPressEvent(self, ev): - if ev.key() in (Qt.Key_Left, Qt.Key_Right): - ac = self.MoveDown if ev.key() == Qt.Key_Right else self.MoveUp + if ev.key() in (Qt.Key.Key_Left, Qt.Key.Key_Right): + ac = self.MoveDown if ev.key() == Qt.Key.Key_Right else self.MoveUp index = self.moveCursor(ac, ev.modifiers()) if index.isValid() and index != self.currentIndex(): m = self.selectionModel() @@ -352,8 +352,8 @@ class Comments(HTMLDisplay): # {{{ ans = unicode_type(col.name()) return ans - c = color_to_string(QApplication.palette().color(QPalette.Normal, - QPalette.WindowText)) + c = color_to_string(QApplication.palette().color(QPalette.ColorGroup.Normal, + QPalette.ColorRole.WindowText)) templ = '''\ @@ -653,7 +653,7 @@ class CoversModel(QAbstractListModel): # {{{ text = (src + '\n' + sz) scaled = pmap.scaled( int(CoverDelegate.ICON_SIZE[0] * pmap.devicePixelRatio()), int(CoverDelegate.ICON_SIZE[1] * pmap.devicePixelRatio()), - Qt.KeepAspectRatio, Qt.SmoothTransformation) + Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation) scaled.setDevicePixelRatio(pmap.devicePixelRatio()) return (text, (scaled), pmap, waiting) @@ -665,11 +665,11 @@ class CoversModel(QAbstractListModel): # {{{ text, pmap, cover, waiting = self.covers[index.row()] except: return None - if role == Qt.DecorationRole: + if role == Qt.ItemDataRole.DecorationRole: return pmap - if role == Qt.DisplayRole or role == Qt.ToolTipRole: + if role == Qt.ItemDataRole.DisplayRole or role == Qt.ItemDataRole.ToolTipRole: return text - if role == Qt.UserRole: + if role == Qt.ItemDataRole.UserRole: return waiting return None @@ -788,17 +788,17 @@ class CoversView(QListView): # {{{ self.delegate = CoverDelegate(self) self.setItemDelegate(self.delegate) self.delegate.needs_redraw.connect(self.redraw_spinners, - type=Qt.QueuedConnection) + type=Qt.ConnectionType.QueuedConnection) - self.doubleClicked.connect(self.chosen, type=Qt.QueuedConnection) - self.setContextMenuPolicy(Qt.CustomContextMenu) + self.doubleClicked.connect(self.chosen, type=Qt.ConnectionType.QueuedConnection) + self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.customContextMenuRequested.connect(self.show_context_menu) def redraw_spinners(self): m = self.model() for r in range(m.rowCount()): idx = m.index(r) - if bool(m.data(idx, Qt.UserRole)): + if bool(m.data(idx, Qt.ItemDataRole.UserRole)): m.dataChanged.emit(idx, idx) def select(self, num): @@ -826,7 +826,7 @@ class CoversView(QListView): # {{{ def show_context_menu(self, point): idx = self.currentIndex() - if idx and idx.isValid() and not idx.data(Qt.UserRole): + if idx and idx.isValid() and not idx.data(Qt.ItemDataRole.UserRole): m = QMenu(self) m.addAction(QIcon(I('view.png')), _('View this cover at full size'), self.show_cover) m.addAction(QIcon(I('edit-copy.png')), _('Copy this cover to clipboard'), self.copy_cover) @@ -839,7 +839,7 @@ class CoversView(QListView): # {{{ pmap = self.model().cc if pmap is not None: from calibre.gui2.image_popup import ImageView - d = ImageView(self, pmap, unicode_type(idx.data(Qt.DisplayRole) or ''), geom_name='metadata_download_cover_popup_geom') + d = ImageView(self, pmap, unicode_type(idx.data(Qt.ItemDataRole.DisplayRole) or ''), geom_name='metadata_download_cover_popup_geom') d(use_exec=True) def copy_cover(self): @@ -851,7 +851,7 @@ class CoversView(QListView): # {{{ QApplication.clipboard().setPixmap(pmap) 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): self.chosen.emit() ev.accept() return @@ -900,7 +900,7 @@ class CoversWidget(QWidget): # {{{ self.authors, book.identifiers, caches) self.worker.start() QTimer.singleShot(50, self.check) - self.covers_view.setFocus(Qt.OtherFocusReason) + self.covers_view.setFocus(Qt.FocusReason.OtherFocusReason) def check(self): if self.worker.is_alive() and not self.abort.is_set(): @@ -983,7 +983,7 @@ class LogViewer(QDialog): # {{{ self.tb = QTextBrowser(self) l.addWidget(self.tb) - self.bb = QDialogButtonBox(QDialogButtonBox.Close) + self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) l.addWidget(self.bb) self.copy_button = self.bb.addButton(_('Copy to clipboard'), self.bb.ActionRole) @@ -1037,7 +1037,7 @@ class FullFetch(QDialog): # {{{ self.setLayout(l) l.addWidget(self.stack) - self.bb = QDialogButtonBox(QDialogButtonBox.Cancel|QDialogButtonBox.Ok) + self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel|QDialogButtonBox.StandardButton.Ok) self.h = h = QHBoxLayout() l.addLayout(h) self.bb.rejected.connect(self.reject) @@ -1047,7 +1047,7 @@ class FullFetch(QDialog): # {{{ self.ok_button.clicked.connect(self.ok_clicked) self.prev_button = pb = QPushButton(QIcon(I('back.png')), _('&Back'), self) pb.clicked.connect(self.back_clicked) - pb.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) + pb.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) self.log_button = self.bb.addButton(_('&View log'), self.bb.ActionRole) self.log_button.clicked.connect(self.view_log) self.log_button.setIcon(QIcon(I('debug.png'))) @@ -1160,7 +1160,7 @@ class CoverFetch(QDialog): # {{{ self.finished.connect(self.cleanup) - self.bb = QDialogButtonBox(QDialogButtonBox.Cancel|QDialogButtonBox.Ok) + self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel|QDialogButtonBox.StandardButton.Ok) l.addWidget(self.bb) self.log_button = self.bb.addButton(_('&View log'), self.bb.ActionRole) self.log_button.clicked.connect(self.view_log) diff --git a/src/calibre/gui2/open_with.py b/src/calibre/gui2/open_with.py index 91c7dfc785..20ebb94df0 100644 --- a/src/calibre/gui2/open_with.py +++ b/src/calibre/gui2/open_with.py @@ -28,7 +28,7 @@ from calibre.utils.config import JSONConfig from calibre.utils.icu import numeric_sort_key as sort_key from polyglot.builtins import iteritems, range, string_or_bytes, unicode_type -ENTRY_ROLE = Qt.UserRole +ENTRY_ROLE = Qt.ItemDataRole.UserRole def pixmap_to_data(pixmap): @@ -281,7 +281,7 @@ class ChooseProgram(Dialog): # {{{ self.programs = self.find_error = self.selected_entry = None self.select_manually = False Dialog.__init__(self, _('Choose a program'), 'choose-open-with-program-dialog', parent=parent, prefs=prefs) - self.found.connect(self.programs_found, type=Qt.QueuedConnection) + self.found.connect(self.programs_found, type=Qt.ConnectionType.QueuedConnection) self.pi.startAnimation() t = Thread(target=self.find_programs) t.daemon = True @@ -292,11 +292,11 @@ class ChooseProgram(Dialog): # {{{ self.w = w = QWidget(self) self.w.l = l = QVBoxLayout(w) self.pi = pi = ProgressIndicator(self, 256) - l.addStretch(1), l.addWidget(pi, alignment=Qt.AlignHCenter), l.addSpacing(10) + l.addStretch(1), l.addWidget(pi, alignment=Qt.AlignmentFlag.AlignHCenter), l.addSpacing(10) w.la = la = QLabel(_('Gathering data, please wait...')) f = la.font() f.setBold(True), f.setPointSize(28), la.setFont(f) - l.addWidget(la, alignment=Qt.AlignHCenter), l.addStretch(1) + l.addWidget(la, alignment=Qt.AlignmentFlag.AlignHCenter), l.addStretch(1) s.addWidget(w) self.w2 = w = QWidget(self) @@ -380,7 +380,7 @@ def populate_menu(menu, connect_action, file_type): text = elided_text(text, pos='right') sa = registered_shortcuts.get(entry['uuid']) if sa is not None: - text += '\t' + sa.shortcut().toString(QKeySequence.NativeText) + text += '\t' + sa.shortcut().toString(QKeySequence.SequenceFormat.NativeText) ac = menu.addAction(icon, text) connect_action(ac, entry) return menu @@ -444,14 +444,14 @@ class EditPrograms(Dialog): # {{{ if ci is None: return error_dialog(self, _('No selection'), _( 'No application selected'), show=True) - name = ci.data(Qt.DisplayRole) + name = ci.data(Qt.ItemDataRole.DisplayRole) name, ok = QInputDialog.getText(self, _('Enter new name'), _('New name for {}').format(name), text=name) if ok and name: entry = ci.data(ENTRY_ROLE) change_name_in_entry(entry, name) ci.setData(ENTRY_ROLE, entry) self.update_stored_config() - ci.setData(Qt.DisplayRole, name) + ci.setData(Qt.ItemDataRole.DisplayRole, name) def remove(self): ci = self.plist.currentItem() diff --git a/src/calibre/gui2/palette.py b/src/calibre/gui2/palette.py index 140bd53251..c474bf11e5 100644 --- a/src/calibre/gui2/palette.py +++ b/src/calibre/gui2/palette.py @@ -25,11 +25,11 @@ def dark_palette(): p.setColor(p.Button, dark_color) p.setColor(p.ButtonText, dark_text_color) p.setColor(p.Disabled, p.ButtonText, disabled_color) - p.setColor(p.BrightText, Qt.red) + p.setColor(p.BrightText, Qt.GlobalColor.red) p.setColor(p.Link, dark_link_color) p.setColor(p.Highlight, dark_link_color) - p.setColor(p.HighlightedText, Qt.black) + p.setColor(p.HighlightedText, Qt.GlobalColor.black) p.setColor(p.Disabled, p.HighlightedText, disabled_color) return p diff --git a/src/calibre/gui2/preferences/__init__.py b/src/calibre/gui2/preferences/__init__.py index 60d5f13f3a..75b00e09f9 100644 --- a/src/calibre/gui2/preferences/__init__.py +++ b/src/calibre/gui2/preferences/__init__.py @@ -90,7 +90,7 @@ class ConfigWidgetInterface(object): class Setting(object): - CHOICES_SEARCH_FLAGS = Qt.MatchExactly | Qt.MatchCaseSensitive + CHOICES_SEARCH_FLAGS = Qt.MatchFlag.MatchExactly | Qt.MatchFlag.MatchCaseSensitive def __init__(self, name, config_obj, widget, gui_name=None, empty_string_is_None=True, choices=None, restart_required=False): @@ -187,7 +187,7 @@ class Setting(object): if isinstance(self.gui_obj, EditWithComplete): self.gui_obj.setText(val) else: - idx = self.gui_obj.findData((val), role=Qt.UserRole, + idx = self.gui_obj.findData((val), role=Qt.ItemDataRole.UserRole, flags=self.CHOICES_SEARCH_FLAGS) if idx == -1: idx = 0 diff --git a/src/calibre/gui2/preferences/adding.py b/src/calibre/gui2/preferences/adding.py index cf57c8e4ce..1ed2ea4aa5 100644 --- a/src/calibre/gui2/preferences/adding.py +++ b/src/calibre/gui2/preferences/adding.py @@ -59,7 +59,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form): self.author_map_rules_button.clicked.connect(self.change_author_map_rules) self.add_filter_rules_button.clicked.connect(self.change_add_filter_rules) self.tabWidget.setCurrentIndex(0) - self.actions_tab.layout().setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow) + self.actions_tab.layout().setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow) def change_tag_map_rules(self): from calibre.gui2.tag_mapper import RulesDialog @@ -123,9 +123,9 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form): for ext in sorted(exts): viewer.addItem(ext) item = viewer.item(viewer.count()-1) - item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable) - item.setCheckState(Qt.Checked if - ext in fmts else Qt.Unchecked) + item.setFlags(Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsUserCheckable) + item.setCheckState(Qt.CheckState.Checked if + ext in fmts else Qt.CheckState.Unchecked) viewer.blockSignals(False) @property @@ -133,7 +133,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form): fmts = [] viewer = self.opt_blocked_auto_formats for i in range(viewer.count()): - if viewer.item(i).checkState() == Qt.Checked: + if viewer.item(i).checkState() == Qt.CheckState.Checked: fmts.append(unicode_type(viewer.item(i).text())) return fmts # }}} diff --git a/src/calibre/gui2/preferences/behavior.py b/src/calibre/gui2/preferences/behavior.py index d5c4ab8779..f0e0f8818a 100644 --- a/src/calibre/gui2/preferences/behavior.py +++ b/src/calibre/gui2/preferences/behavior.py @@ -32,7 +32,7 @@ def input_order_drop_event(self, ev): class OutputFormatSetting(Setting): - CHOICES_SEARCH_FLAGS = Qt.MatchFixedString + CHOICES_SEARCH_FLAGS = Qt.MatchFlag.MatchFixedString class ConfigWidget(ConfigWidgetBase, Ui_Form): @@ -94,7 +94,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form): def commit(self): input_map = prefs['input_format_order'] - input_cols = [unicode_type(self.opt_input_order.item(i).data(Qt.UserRole) or '') for + input_cols = [unicode_type(self.opt_input_order.item(i).data(Qt.ItemDataRole.UserRole) or '') for i in range(self.opt_input_order.count())] if input_map != input_cols: prefs['input_format_order'] = input_cols @@ -128,9 +128,9 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form): for ext in sorted(exts): viewer.addItem(ext.upper()) item = viewer.item(viewer.count()-1) - item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable) - item.setCheckState(Qt.Checked if - ext.upper() in fmts else Qt.Unchecked) + item.setFlags(Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsUserCheckable) + item.setCheckState(Qt.CheckState.Checked if + ext.upper() in fmts else Qt.CheckState.Unchecked) viewer.blockSignals(False) @property @@ -138,7 +138,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form): fmts = [] viewer = self.opt_internally_viewed_formats for i in range(viewer.count()): - if viewer.item(i).checkState() == Qt.Checked: + if viewer.item(i).checkState() == Qt.CheckState.Checked: fmts.append(unicode_type(viewer.item(i).text())) return fmts # }}} @@ -155,8 +155,8 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form): all_formats.add(fmt.upper()) for format in input_map + list(all_formats.difference(input_map)): item = QListWidgetItem(format, self.opt_input_order) - item.setData(Qt.UserRole, (format)) - item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsSelectable|Qt.ItemIsDragEnabled) + item.setData(Qt.ItemDataRole.UserRole, (format)) + item.setFlags(Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsSelectable|Qt.ItemFlag.ItemIsDragEnabled) def up_input(self, *args): idx = self.opt_input_order.currentRow() diff --git a/src/calibre/gui2/preferences/coloring.py b/src/calibre/gui2/preferences/coloring.py index ad91f916b8..cc0003e18f 100644 --- a/src/calibre/gui2/preferences/coloring.py +++ b/src/calibre/gui2/preferences/coloring.py @@ -321,7 +321,7 @@ class RuleEditor(QDialog): # {{{ l.addWidget(l1, 0, 0, 1, 8) self.f1 = QFrame(self) - self.f1.setFrameShape(QFrame.HLine) + self.f1.setFrameShape(QFrame.Shape.HLine) l.addWidget(self.f1, 1, 0, 1, 8) self.l2 = l2 = QLabel(_('Add the emblem:') if self.rule_kind == 'emblem' else _('Set the')) @@ -364,10 +364,10 @@ class RuleEditor(QDialog): # {{{ if self.rule_kind == 'color': self.color_box = ColorButton(parent=self) self.color_label = QLabel('Sample text Sample text') - self.color_label.setTextFormat(Qt.RichText) + self.color_label.setTextFormat(Qt.TextFormat.RichText) l.addWidget(self.color_box, 2, 5) l.addWidget(self.color_label, 2, 6) - l.addItem(QSpacerItem(10, 10, QSizePolicy.Expanding), 2, 7) + l.addItem(QSpacerItem(10, 10, QSizePolicy.Policy.Expanding), 2, 7) elif self.rule_kind == 'emblem': create_filename_box() self.update_filename_box() @@ -414,7 +414,7 @@ class RuleEditor(QDialog): # {{{ l.addWidget(l6, 6, 0, 1, 8) 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, 7, 0, 1, 8) @@ -428,7 +428,7 @@ class RuleEditor(QDialog): # {{{ self.conditions_widget = QWidget(self) sa.setWidget(self.conditions_widget) self.conditions_widget.setLayout(QVBoxLayout()) - self.conditions_widget.layout().setAlignment(Qt.AlignTop) + self.conditions_widget.layout().setAlignment(Qt.AlignmentFlag.AlignTop) self.conditions = [] if self.rule_kind == 'color': @@ -490,10 +490,10 @@ class RuleEditor(QDialog): # {{{ for i,filename in enumerate(self.icon_file_names): item = QStandardItem(filename) if doing_multiple: - item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) - item.setData(Qt.Unchecked, Qt.CheckStateRole) + item.setFlags(Qt.ItemFlag.ItemIsUserCheckable | Qt.ItemFlag.ItemIsEnabled) + item.setData(Qt.CheckState.Unchecked, Qt.ItemDataRole.CheckStateRole) else: - item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable) + item.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable) icon = QIcon(os.path.join(self.icon_folder, filename)) item.setIcon(icon) model.appendRow(item) @@ -556,7 +556,7 @@ class RuleEditor(QDialog): # {{{ fnames = [] for i in range(1, model.rowCount()): item = model.item(i, 0) - if item.checkState() == Qt.Checked: + if item.checkState() == Qt.CheckState.Checked: fnames.append(lower(unicode_type(item.text()))) fname = ' : '.join(fnames) else: @@ -577,7 +577,7 @@ class RuleEditor(QDialog): # {{{ idx = self.filename_box.findText(icon) if idx >= 0: item = model.item(idx) - item.setCheckState(Qt.Checked) + item.setCheckState(Qt.CheckState.Checked) def update_remove_button(self): m = self.remove_button.menu() @@ -732,13 +732,13 @@ class RulesModel(QAbstractListModel): # {{{ kind, col, rule = self.rules[row] except: return None - if role == Qt.DisplayRole: + if role == Qt.ItemDataRole.DisplayRole: if col == color_row_key: col = all_columns_string else: col = self.fm[col]['name'] return self.rule_to_html(kind, col, rule) - if role == Qt.UserRole: + if role == Qt.ItemDataRole.UserRole: return (kind, col, rule) def add_rule(self, kind, col, rule): @@ -921,12 +921,12 @@ class EditRules(QWidget): # {{{ b.setIcon(QIcon(I('arrow-up.png'))) b.setToolTip(_('Move the selected rule up')) b.clicked.connect(self.move_up) - g.addWidget(b, 0, 1, 1, 1, Qt.AlignTop) + g.addWidget(b, 0, 1, 1, 1, Qt.AlignmentFlag.AlignTop) self.down_button = b = QToolButton(self) b.setIcon(QIcon(I('arrow-down.png'))) b.setToolTip(_('Move the selected rule down')) b.clicked.connect(self.move_down) - g.addWidget(b, 1, 1, 1, 1, Qt.AlignBottom) + g.addWidget(b, 1, 1, 1, 1, Qt.AlignmentFlag.AlignBottom) l.addLayout(g, l.rowCount(), 0, 1, 2) l.setRowStretch(l.rowCount() - 1, 10) @@ -1022,7 +1022,7 @@ class EditRules(QWidget): # {{{ def edit_rule(self, index): try: - kind, col, rule = self.model.data(index, Qt.UserRole) + kind, col, rule = self.model.data(index, Qt.ItemDataRole.UserRole) except: return if isinstance(rule, Rule): diff --git a/src/calibre/gui2/preferences/columns.py b/src/calibre/gui2/preferences/columns.py index 8fdefa6cd5..6ec429a248 100644 --- a/src/calibre/gui2/preferences/columns.py +++ b/src/calibre/gui2/preferences/columns.py @@ -117,7 +117,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form): self.opt_columns.resizeRowsToContents() def setup_row(self, field_metadata, row, col, oldkey=None): - flags = Qt.ItemIsEnabled | Qt.ItemIsSelectable + flags = Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable item = QTableWidgetItem(col) item.setFlags(flags) @@ -154,18 +154,18 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form): self.opt_columns.setItem(row, 3, item) item = QTableWidgetItem(fm['name']) - item.setData(Qt.UserRole, (col)) + item.setData(Qt.ItemDataRole.UserRole, (col)) item.setFlags(flags) self.opt_columns.setItem(row, 0, item) if col.startswith('#'): - item.setData(Qt.DecorationRole, (QIcon(I('column.png')))) + item.setData(Qt.ItemDataRole.DecorationRole, (QIcon(I('column.png')))) if col != 'ondevice': - flags |= Qt.ItemIsUserCheckable + flags |= Qt.ItemFlag.ItemIsUserCheckable item.setFlags(flags) if col != 'ondevice': - item.setCheckState(Qt.Unchecked if col in self.hidden_cols else - Qt.Checked) + item.setCheckState(Qt.CheckState.Unchecked if col in self.hidden_cols else + Qt.CheckState.Checked) def up_column(self): idx = self.opt_columns.currentRow() @@ -194,7 +194,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form): if idx < 0: return error_dialog(self, '', _('You must select a column to delete it'), show=True) - col = unicode_type(self.opt_columns.item(idx, 0).data(Qt.UserRole) or '') + col = unicode_type(self.opt_columns.item(idx, 0).data(Qt.ItemDataRole.UserRole) or '') if col not in self.custcols: return error_dialog(self, '', _('The selected column is not a custom column'), show=True) @@ -223,7 +223,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form): model = self.gui.library_view.model() row = self.opt_columns.currentRow() try: - key = unicode_type(self.opt_columns.item(row, 0).data(Qt.UserRole)) + key = unicode_type(self.opt_columns.item(row, 0).data(Qt.ItemDataRole.UserRole)) except: key = '' CreateCustomColumn(self, row, key, model.orig_headers, ALL_COLUMNS) @@ -236,14 +236,14 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form): def apply_custom_column_changes(self): model = self.gui.library_view.model() db = model.db - config_cols = [unicode_type(self.opt_columns.item(i, 0).data(Qt.UserRole) or '') + config_cols = [unicode_type(self.opt_columns.item(i, 0).data(Qt.ItemDataRole.UserRole) or '') for i in range(self.opt_columns.rowCount())] if not config_cols: config_cols = ['title'] removed_cols = set(model.column_map) - set(config_cols) - hidden_cols = {unicode_type(self.opt_columns.item(i, 0).data(Qt.UserRole) or '') + hidden_cols = {unicode_type(self.opt_columns.item(i, 0).data(Qt.ItemDataRole.UserRole) or '') for i in range(self.opt_columns.rowCount()) - if self.opt_columns.item(i, 0).checkState()==Qt.Unchecked} + if self.opt_columns.item(i, 0).checkState()==Qt.CheckState.Unchecked} hidden_cols = hidden_cols.union(removed_cols) # Hide removed cols hidden_cols = list(hidden_cols.intersection(set(model.column_map))) if 'ondevice' in hidden_cols: diff --git a/src/calibre/gui2/preferences/conversion.py b/src/calibre/gui2/preferences/conversion.py index 1a41bb6086..b487dd77a7 100644 --- a/src/calibre/gui2/preferences/conversion.py +++ b/src/calibre/gui2/preferences/conversion.py @@ -34,7 +34,7 @@ class Model(QStringListModel): self.setStringList([w.TITLE for w in widgets]) def data(self, index, role): - if role == Qt.DecorationRole: + if role == Qt.ItemDataRole.DecorationRole: w = self.widgets[index.row()] if w.ICON: return (QIcon(w.ICON)) @@ -47,7 +47,7 @@ class ListView(QListView): def __init__(self, parent=None): QListView.__init__(self, parent) - self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Expanding) + self.setSizePolicy(QSizePolicy.Policy.MinimumExpanding, QSizePolicy.Policy.Expanding) f = self.font() f.setBold(True) self.setFont(f) diff --git a/src/calibre/gui2/preferences/create_custom_column.py b/src/calibre/gui2/preferences/create_custom_column.py index 06fd195a50..bcc4ec2992 100644 --- a/src/calibre/gui2/preferences/create_custom_column.py +++ b/src/calibre/gui2/preferences/create_custom_column.py @@ -98,7 +98,7 @@ class CreateCustomColumn(QDialog): self.heading_label.setText('' + _('Create a custom column')) # 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.simple_error = partial(error_dialog, self, show=True, @@ -239,7 +239,7 @@ class CreateCustomColumn(QDialog): # }}} def setup_ui(self): # {{{ - self.setWindowModality(Qt.ApplicationModal) + self.setWindowModality(Qt.WindowModality.ApplicationModal) self.setWindowIcon(QIcon(I('column.png'))) self.vl = l = QVBoxLayout(self) self.heading_label = la = QLabel('') @@ -259,7 +259,7 @@ class CreateCustomColumn(QDialog): self.g = g = QGridLayout() l.addLayout(g) l.addStretch(10) - self.button_box = bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, self) + self.button_box = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel, self) bb.accepted.connect(self.accept), bb.rejected.connect(self.reject) l.addWidget(bb) diff --git a/src/calibre/gui2/preferences/device_debug.py b/src/calibre/gui2/preferences/device_debug.py index 7d48941ddf..329836a32b 100644 --- a/src/calibre/gui2/preferences/device_debug.py +++ b/src/calibre/gui2/preferences/device_debug.py @@ -32,8 +32,8 @@ class DebugDevice(QDialog): self.ok.setAutoDefault(False) self.ok.clicked.connect(self.accept) self.bbox = QDialogButtonBox(self) - self.bbox.addButton(self.copy, QDialogButtonBox.ActionRole) - self.bbox.addButton(self.ok, QDialogButtonBox.AcceptRole) + self.bbox.addButton(self.copy, QDialogButtonBox.ButtonRole.ActionRole) + self.bbox.addButton(self.ok, QDialogButtonBox.ButtonRole.AcceptRole) self._layout.addWidget(self.bbox) self.resize(750, 500) self.bbox.setEnabled(False) diff --git a/src/calibre/gui2/preferences/device_user_defined.py b/src/calibre/gui2/preferences/device_user_defined.py index 94ea58a70d..7b2e59c7dc 100644 --- a/src/calibre/gui2/preferences/device_user_defined.py +++ b/src/calibre/gui2/preferences/device_user_defined.py @@ -16,8 +16,8 @@ def step_dialog(parent, title, msg, det_msg=''): d = QMessageBox(parent) d.setWindowTitle(title) d.setText(msg) - d.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) - return d.exec_() & QMessageBox.Cancel + d.setStandardButtons(QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Cancel) + return d.exec_() & QMessageBox.StandardButton.Cancel class UserDefinedDevice(QDialog): @@ -38,8 +38,8 @@ class UserDefinedDevice(QDialog): self.ok.setAutoDefault(False) self.ok.clicked.connect(self.accept) self.bbox = QDialogButtonBox(self) - self.bbox.addButton(self.copy, QDialogButtonBox.ActionRole) - self.bbox.addButton(self.ok, QDialogButtonBox.AcceptRole) + self.bbox.addButton(self.copy, QDialogButtonBox.ButtonRole.ActionRole) + self.bbox.addButton(self.ok, QDialogButtonBox.ButtonRole.AcceptRole) self._layout.addWidget(self.bbox) self.resize(750, 500) self.bbox.setEnabled(False) diff --git a/src/calibre/gui2/preferences/emailp.py b/src/calibre/gui2/preferences/emailp.py index f8f3958745..477723e5f6 100644 --- a/src/calibre/gui2/preferences/emailp.py +++ b/src/calibre/gui2/preferences/emailp.py @@ -71,8 +71,8 @@ class EmailAccounts(QAbstractTableModel): # {{{ return numeric_sort_key(self.tags.get(account_key) or '') self.account_order.sort(key=key, reverse=not self.sorted_on[1]) - def sort(self, column, order=Qt.AscendingOrder): - nsort = (column, order == Qt.AscendingOrder) + def sort(self, column, order=Qt.SortOrder.AscendingOrder): + nsort = (column, order == Qt.SortOrder.AscendingOrder) if nsort != self.sorted_on: self.sorted_on = nsort self.beginResetModel() @@ -88,7 +88,7 @@ class EmailAccounts(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 @@ -99,11 +99,11 @@ class EmailAccounts(QAbstractTableModel): # {{{ account = self.account_order[row] if account not in self.accounts: return None - if role == Qt.UserRole: + if role == Qt.ItemDataRole.UserRole: return (account, self.accounts[account]) - if role == Qt.ToolTipRole: + if role == Qt.ItemDataRole.ToolTipRole: return self.tooltips[col] - if role in [Qt.DisplayRole, Qt.EditRole]: + if role in [Qt.ItemDataRole.DisplayRole, Qt.ItemDataRole.EditRole]: if col == 0: return (account) if col == 1: @@ -114,17 +114,17 @@ class EmailAccounts(QAbstractTableModel): # {{{ return (self.aliases.get(account, '')) if col == 5: return (self.tags.get(account, '')) - if role == Qt.FontRole and self.accounts[account][2]: + if role == Qt.ItemDataRole.FontRole and self.accounts[account][2]: return self.default_font - if role == Qt.CheckStateRole and col == 3: - return (Qt.Checked if self.accounts[account][1] else Qt.Unchecked) + if role == Qt.ItemDataRole.CheckStateRole and col == 3: + return (Qt.CheckState.Checked if self.accounts[account][1] else Qt.CheckState.Unchecked) return None def flags(self, index): if index.column() == 3: - return QAbstractTableModel.flags(self, index)|Qt.ItemIsUserCheckable + return QAbstractTableModel.flags(self, index)|Qt.ItemFlag.ItemIsUserCheckable else: - return QAbstractTableModel.flags(self, index)|Qt.ItemIsEditable + return QAbstractTableModel.flags(self, index)|Qt.ItemFlag.ItemIsEditable def setData(self, index, value, role): if not index.isValid(): @@ -224,7 +224,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form): opts.aliases, opts.tags) connect_lambda(self._email_accounts.dataChanged, self, lambda self: self.changed_signal.emit()) self.email_view.setModel(self._email_accounts) - self.email_view.sortByColumn(0, Qt.AscendingOrder) + self.email_view.sortByColumn(0, Qt.SortOrder.AscendingOrder) self.email_view.setSortingEnabled(True) self.email_add.clicked.connect(self.add_email_account) @@ -248,7 +248,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form): if self.email_view.state() == self.email_view.EditingState: # Ensure that the cell being edited is committed by switching focus # to some other widget, which automatically closes the open editor - self.send_email_widget.setFocus(Qt.OtherFocusReason) + self.send_email_widget.setFocus(Qt.FocusReason.OtherFocusReason) to_set = bool(self._email_accounts.accounts) if not self.send_email_widget.set_email_settings(to_set): raise AbortCommit('abort') diff --git a/src/calibre/gui2/preferences/history.py b/src/calibre/gui2/preferences/history.py index 63bd638e71..44ff00bac7 100644 --- a/src/calibre/gui2/preferences/history.py +++ b/src/calibre/gui2/preferences/history.py @@ -35,7 +35,7 @@ class HistoryBox(QComboBox): history.append(val) self.clear() self.addItems(history) - self.setCurrentIndex(self.findText(val, Qt.MatchFixedString)) + self.setCurrentIndex(self.findText(val, Qt.MatchFlag.MatchFixedString)) def save_history(self, opt_name): history = [unicode_type(self.itemText(i)) for i in range(self.count())] diff --git a/src/calibre/gui2/preferences/ignored_devices.py b/src/calibre/gui2/preferences/ignored_devices.py index 40dd646da7..d799c0f41e 100644 --- a/src/calibre/gui2/preferences/ignored_devices.py +++ b/src/calibre/gui2/preferences/ignored_devices.py @@ -61,8 +61,8 @@ class ConfigWidget(ConfigWidgetBase): self.changed_signal.emit() def toggle_item(self, item): - item.setCheckState(Qt.Checked if item.checkState() == Qt.Unchecked else - Qt.Unchecked) + item.setCheckState(Qt.CheckState.Checked if item.checkState() == Qt.CheckState.Unchecked else + Qt.CheckState.Unchecked) def initialize(self): self.confirms_reset = False @@ -71,18 +71,18 @@ class ConfigWidget(ConfigWidgetBase): for dev in self.gui.device_manager.devices: for d, name in iteritems(dev.get_user_blacklisted_devices()): item = QListWidgetItem('%s [%s]'%(name, d), self.devices) - item.setData(Qt.UserRole, (dev, d)) - item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable|Qt.ItemIsSelectable) - item.setCheckState(Qt.Checked) + item.setData(Qt.ItemDataRole.UserRole, (dev, d)) + item.setFlags(Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsUserCheckable|Qt.ItemFlag.ItemIsSelectable) + item.setCheckState(Qt.CheckState.Checked) self.devices.blockSignals(False) self.device_plugins.blockSignals(True) for dev in self.gui.device_manager.disabled_device_plugins: n = dev.get_gui_name() item = QListWidgetItem(n, self.device_plugins) - item.setData(Qt.UserRole, dev) - item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable|Qt.ItemIsSelectable) - item.setCheckState(Qt.Checked) + item.setData(Qt.ItemDataRole.UserRole, dev) + item.setFlags(Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsUserCheckable|Qt.ItemFlag.ItemIsSelectable) + item.setCheckState(Qt.CheckState.Checked) item.setIcon(QIcon(I('plugins.png'))) self.device_plugins.sortItems() self.device_plugins.blockSignals(False) @@ -95,10 +95,10 @@ class ConfigWidget(ConfigWidgetBase): devs = {} for i in range(0, self.devices.count()): e = self.devices.item(i) - dev, uid = e.data(Qt.UserRole) + dev, uid = e.data(Qt.ItemDataRole.UserRole) if dev not in devs: devs[dev] = [] - if e.checkState() == Qt.Checked: + if e.checkState() == Qt.CheckState.Checked: devs[dev].append(uid) for dev, bl in iteritems(devs): @@ -106,8 +106,8 @@ class ConfigWidget(ConfigWidgetBase): for i in range(self.device_plugins.count()): e = self.device_plugins.item(i) - dev = e.data(Qt.UserRole) - if e.checkState() == Qt.Unchecked: + dev = e.data(Qt.ItemDataRole.UserRole) + if e.checkState() == Qt.CheckState.Unchecked: enable_plugin(dev) if self.confirms_reset: gprefs['ask_to_manage_device'] = [] diff --git a/src/calibre/gui2/preferences/look_feel.py b/src/calibre/gui2/preferences/look_feel.py index 22ac6841b5..89f7142653 100644 --- a/src/calibre/gui2/preferences/look_feel.py +++ b/src/calibre/gui2/preferences/look_feel.py @@ -44,7 +44,7 @@ from polyglot.builtins import iteritems, unicode_type, map class BusyCursor(object): def __enter__(self): - QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) + QApplication.setOverrideCursor(QCursor(Qt.CursorShape.WaitCursor)) def __exit__(self, *args): QApplication.restoreOverrideCursor() @@ -141,7 +141,7 @@ class IdLinksRuleEdit(Dialog): self.template = t = QLineEdit(self) l.addRow(_('&Template:'), t) t.selectAll() - t.setFocus(Qt.OtherFocusReason) + t.setFocus(Qt.FocusReason.OtherFocusReason) l.addWidget(self.bb) def accept(self): @@ -248,7 +248,7 @@ class DisplayedFields(QAbstractListModel): # {{{ field, visible = self.fields[index.row()] except: return None - if role == Qt.DisplayRole: + if role == Qt.ItemDataRole.DisplayRole: name = field try: name = self.db.field_metadata[field]['name'] @@ -257,9 +257,9 @@ class DisplayedFields(QAbstractListModel): # {{{ if not name: name = field return name - if role == Qt.CheckStateRole: - return Qt.Checked if visible else Qt.Unchecked - if role == Qt.DecorationRole and field.startswith('#'): + if role == Qt.ItemDataRole.CheckStateRole: + return Qt.CheckState.Checked if visible else Qt.CheckState.Unchecked + if role == Qt.ItemDataRole.DecorationRole and field.startswith('#'): return QIcon(I('column.png')) return None @@ -267,15 +267,15 @@ class DisplayedFields(QAbstractListModel): # {{{ for i in range(self.rowCount()): idx = self.index(i) if idx.isValid(): - self.setData(idx, show, Qt.CheckStateRole) + self.setData(idx, show, Qt.ItemDataRole.CheckStateRole) def flags(self, index): ans = QAbstractListModel.flags(self, index) - return ans | Qt.ItemIsUserCheckable + return ans | Qt.ItemFlag.ItemIsUserCheckable def setData(self, index, val, role): ret = False - if role == Qt.CheckStateRole: + if role == Qt.ItemDataRole.CheckStateRole: self.fields[index.row()][1] = bool(val) self.changed = True ret = True @@ -350,7 +350,7 @@ class Background(QWidget): # {{{ self.bcol = QColor(*gprefs['cover_grid_color']) self.btex = gprefs['cover_grid_texture'] self.update_brush() - self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) + self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) def update_brush(self): self.brush = QBrush(self.bcol) @@ -545,27 +545,27 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form): self.emblems_tab.layout().addWidget(self.grid_rules) self.tabWidget.setCurrentIndex(0) - keys = [QKeySequence('F11', QKeySequence.PortableText), QKeySequence( - 'Ctrl+Shift+F', QKeySequence.PortableText)] - keys = [unicode_type(x.toString(QKeySequence.NativeText)) for x in keys] + keys = [QKeySequence('F11', QKeySequence.SequenceFormat.PortableText), QKeySequence( + 'Ctrl+Shift+F', QKeySequence.SequenceFormat.PortableText)] + keys = [unicode_type(x.toString(QKeySequence.SequenceFormat.NativeText)) for x in keys] self.fs_help_msg.setText(unicode_type(self.fs_help_msg.text())%( _(' or ').join(keys))) - self.size_calculated.connect(self.update_cg_cache_size, type=Qt.QueuedConnection) + self.size_calculated.connect(self.update_cg_cache_size, type=Qt.ConnectionType.QueuedConnection) self.tabWidget.currentChanged.connect(self.tab_changed) l = self.cg_background_box.layout() self.cg_bg_widget = w = Background(self) l.addWidget(w, 0, 0, 3, 1) self.cover_grid_color_button = b = QPushButton(_('Change &color'), self) - b.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) + b.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) l.addWidget(b, 0, 1) b.clicked.connect(self.change_cover_grid_color) self.cover_grid_texture_button = b = QPushButton(_('Change &background image'), self) - b.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) + b.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) l.addWidget(b, 1, 1) b.clicked.connect(self.change_cover_grid_texture) self.cover_grid_default_appearance_button = b = QPushButton(_('Restore &default appearance'), self) - b.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) + b.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) l.addWidget(b, 2, 1) b.clicked.connect(self.restore_cover_grid_appearance) self.cover_grid_empty_cache.clicked.connect(self.empty_cache) @@ -637,7 +637,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form): font = gprefs['font'] if font is not None: font = list(font) - font.append(gprefs.get('font_stretch', QFont.Unstretched)) + font.append(gprefs.get('font_stretch', QFont.Stretch.Unstretched)) self.current_font = self.initial_font = font self.update_font_display() self.display_model.initialize() @@ -765,7 +765,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form): gprefs['font'] = (self.current_font[:4] if self.current_font else None) gprefs['font_stretch'] = (self.current_font[4] if self.current_font - is not None else QFont.Unstretched) + is not None else QFont.Stretch.Unstretched) QApplication.setFont(self.font_display.font()) rr = True self.display_model.commit() diff --git a/src/calibre/gui2/preferences/main.py b/src/calibre/gui2/preferences/main.py index a07a30461c..e0715b2eba 100644 --- a/src/calibre/gui2/preferences/main.py +++ b/src/calibre/gui2/preferences/main.py @@ -36,7 +36,7 @@ class Message(QWidget): self.layout = QTextLayout() self.layout.setFont(self.font()) self.layout.setCacheEnabled(True) - self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) + self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred) self.last_layout_rect = None def setText(self, text): @@ -82,7 +82,7 @@ class TitleBar(QWidget): self.icon = Icon(self, size=ICON_SIZE) l.addWidget(self.icon) self.title = QLabel('') - self.title.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) + self.title.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter) l.addWidget(self.title) l.addStrut(25) self.msg = la = Message(self) @@ -116,7 +116,7 @@ class Category(QWidget): # {{{ self.bf = QFont() self.bf.setBold(True) self.label.setFont(self.bf) - self.sep.setFrameShape(QFrame.HLine) + self.sep.setFrameShape(QFrame.Shape.HLine) self._layout.addWidget(self.label) self._layout.addWidget(self.sep) @@ -129,7 +129,7 @@ class Category(QWidget): # {{{ self.bar.setIconSize(QSize(2*lh, 2*lh)) self.bar.setMovable(False) self.bar.setFloatable(False) - self.bar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) + self.bar.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextUnderIcon) self._layout.addWidget(self.bar) self.actions = [] for p in plugins: @@ -140,7 +140,7 @@ class Category(QWidget): # {{{ ac.setStatusTip(p.description) self.actions.append(ac) w = self.bar.widgetForAction(ac) - w.setCursor(Qt.PointingHandCursor) + w.setCursor(Qt.CursorShape.PointingHandCursor) if hasattr(w, 'setAutoRaise'): w.setAutoRaise(True) w.setMinimumWidth(100) @@ -230,20 +230,20 @@ class Preferences(QDialog): if islinux: self.move(gui.rect().center() - self.rect().center()) - self.setWindowModality(Qt.ApplicationModal) + self.setWindowModality(Qt.WindowModality.ApplicationModal) self.setWindowTitle(__appname__ + ' - ' + _('Preferences')) self.setWindowIcon(QIcon(I('config.png'))) self.l = l = QVBoxLayout(self) self.stack = QStackedWidget(self) - self.bb = QDialogButtonBox(QDialogButtonBox.Close | QDialogButtonBox.Apply | QDialogButtonBox.Discard | QDialogButtonBox.RestoreDefaults) + self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close | QDialogButtonBox.StandardButton.Apply | QDialogButtonBox.StandardButton.Discard | QDialogButtonBox.StandardButton.RestoreDefaults) self.bb.button(self.bb.Apply).clicked.connect(self.accept) self.bb.button(self.bb.Discard).clicked.connect(self.reject) self.bb.button(self.bb.RestoreDefaults).setIcon(QIcon(I('clear_left.png'))) self.bb.button(self.bb.RestoreDefaults).clicked.connect(self.restore_defaults) self.wizard_button = self.bb.addButton(_('Run Welcome &wizard'), self.bb.ActionRole) self.wizard_button.setIcon(QIcon(I('wizard.png'))) - self.wizard_button.clicked.connect(self.run_wizard, type=Qt.QueuedConnection) + self.wizard_button.clicked.connect(self.run_wizard, type=Qt.ConnectionType.QueuedConnection) self.wizard_button.setAutoDefault(False) self.bb.rejected.connect(self.reject) self.browser = Browser(self) @@ -253,7 +253,7 @@ class Preferences(QDialog): self.stack.addWidget(self.scroll_area) self.scroll_area.setWidgetResizable(True) - self.setContextMenuPolicy(Qt.NoContextMenu) + self.setContextMenuPolicy(Qt.ContextMenuPolicy.NoContextMenu) self.title_bar = TitleBar(self) for ac, tt in [(self.bb.Apply, _('Save changes')), (self.bb.Discard, _('Cancel and return to overview'))]: diff --git a/src/calibre/gui2/preferences/metadata_sources.py b/src/calibre/gui2/preferences/metadata_sources.py index 3408a1a9d8..6e15fa2cfa 100644 --- a/src/calibre/gui2/preferences/metadata_sources.py +++ b/src/calibre/gui2/preferences/metadata_sources.py @@ -48,7 +48,7 @@ class SourcesModel(QAbstractTableModel): # {{{ return 2 def headerData(self, section, orientation, role): - if orientation == Qt.Horizontal and role == Qt.DisplayRole: + if orientation == Qt.Orientation.Horizontal and role == Qt.ItemDataRole.DisplayRole: if section == 0: return _('Source') if section == 1: @@ -62,21 +62,21 @@ class SourcesModel(QAbstractTableModel): # {{{ return None col = index.column() - if role in (Qt.DisplayRole, Qt.EditRole): + if role in (Qt.ItemDataRole.DisplayRole, Qt.ItemDataRole.EditRole): if col == 0: return plugin.name elif col == 1: orig = msprefs['cover_priorities'].get(plugin.name, 1) return self.cover_overrides.get(plugin, orig) - elif role == Qt.CheckStateRole and col == 0: - orig = Qt.Unchecked if is_disabled(plugin) else Qt.Checked + elif role == Qt.ItemDataRole.CheckStateRole and col == 0: + orig = Qt.CheckState.Unchecked if is_disabled(plugin) else Qt.CheckState.Checked return self.enabled_overrides.get(plugin, orig) - elif role == Qt.UserRole: + elif role == Qt.ItemDataRole.UserRole: return plugin - elif (role == Qt.DecorationRole and col == 0 and not + elif (role == Qt.ItemDataRole.DecorationRole and col == 0 and not plugin.is_configured()): return QIcon(I('list_remove.png')) - elif role == Qt.ToolTipRole: + elif role == Qt.ItemDataRole.ToolTipRole: base = plugin.description + '\n\n' if plugin.is_configured(): return base + _('This source is configured and ready to go') @@ -90,8 +90,8 @@ class SourcesModel(QAbstractTableModel): # {{{ return False col = index.column() ret = False - if col == 0 and role == Qt.CheckStateRole: - if val == Qt.Checked and 'Douban' in plugin.name: + if col == 0 and role == Qt.ItemDataRole.CheckStateRole: + if val == Qt.CheckState.Checked and 'Douban' in plugin.name: if not question_dialog(self.gui_parent, _('Are you sure?'), '

'+ _('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.store_name, result.formats)) return None - elif role == Qt.DecorationRole: + elif role == Qt.ItemDataRole.DecorationRole: if col == 0 and result.cover_data: p = QPixmap() p.loadFromData(result.cover_data) @@ -227,7 +227,7 @@ class Matches(QAbstractItemModel): if col == 6: if result.affiliate: return (self.DONATE_ICON) - elif role == Qt.ToolTipRole: + elif role == Qt.ItemDataRole.ToolTipRole: if col == 1: return ('

%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 = '

%s
' % (color, index.data(RENDER_ROLE)) st = QStaticText(text) st.setTextWidth(option.rect.width()) @@ -303,7 +303,7 @@ class Rules(QWidget): r.viewport().setAcceptDrops(True) r.setDropIndicatorShown(True) r.setDragDropMode(r.InternalMove) - r.setDefaultDropAction(Qt.MoveAction) + r.setDefaultDropAction(Qt.DropAction.MoveAction) self.l2 = l = QVBoxLayout() h.addLayout(l) self.up_button = b = QToolButton(self) @@ -329,7 +329,7 @@ class Rules(QWidget): i = self.rule_list.currentItem() if i is not None: d = self.RuleEditDialogClass(self) - d.edit_widget.rule = i.data(Qt.UserRole) + d.edit_widget.rule = i.data(Qt.ItemDataRole.UserRole) if d.exec_() == d.Accepted: rule = d.edit_widget.rule i.setData(DATA_ROLE, rule) diff --git a/src/calibre/gui2/throbber.py b/src/calibre/gui2/throbber.py index 6ab4cedda0..07417e2f18 100644 --- a/src/calibre/gui2/throbber.py +++ b/src/calibre/gui2/throbber.py @@ -28,7 +28,7 @@ class ThrobbingButton(QToolButton): QToolButton.__init__(self, *args) # vertically size policy must be expanding for it to align inside a # toolbar - self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) + self.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Expanding) self._icon_size = -1 QToolButton.setIcon(self, QIcon(I('donate.png'))) self.setText('\xa0') @@ -36,7 +36,7 @@ class ThrobbingButton(QToolButton): self.animation.setDuration(60/72.*1000) self.animation.setLoopCount(4) self.animation.valueChanged.connect(self.value_changed) - self.setCursor(Qt.PointingHandCursor) + self.setCursor(Qt.CursorShape.PointingHandCursor) self.animation.finished.connect(self.animation_finished) def animation_finished(self): @@ -60,7 +60,7 @@ class ThrobbingButton(QToolButton): smaller = int(0.7 * size) self.animation.setStartValue(smaller) self.animation.setEndValue(size) - QMetaObject.invokeMethod(self.animation, 'start', Qt.QueuedConnection) + QMetaObject.invokeMethod(self.animation, 'start', Qt.ConnectionType.QueuedConnection) def stop_animation(self): self.animation.stop() diff --git a/src/calibre/gui2/toc/location.py b/src/calibre/gui2/toc/location.py index fb72c5a4f4..133e62b4c9 100644 --- a/src/calibre/gui2/toc/location.py +++ b/src/calibre/gui2/toc/location.py @@ -33,9 +33,9 @@ class Page(QWebEnginePage): # {{{ self.loadFinished.connect(self.show_frag) s = QWebEngineScript() s.setName('toc.js') - s.setInjectionPoint(QWebEngineScript.DocumentReady) + s.setInjectionPoint(QWebEngineScript.InjectionPoint.DocumentReady) s.setRunsOnSubFrames(True) - s.setWorldId(QWebEngineScript.ApplicationWorld) + s.setWorldId(QWebEngineScript.ScriptWorldId.ApplicationWorld) s.setSourceCode(P('toc.js', allow_user_override=False, data=True).decode('utf-8').replace('COM_ID', self.com_id)) self.scripts().insert(s) @@ -50,7 +50,7 @@ class Page(QWebEnginePage): # {{{ if len(parts) == 2 and parts[0] == self.com_id: self.runJavaScript( 'JSON.stringify(window.calibre_toc_data)', - QWebEngineScript.ApplicationWorld, self.onclick) + QWebEngineScript.ScriptWorldId.ApplicationWorld, self.onclick) def onclick(self, data): try: @@ -67,7 +67,7 @@ class Page(QWebEnginePage): # {{{ document.location = '#' + {0}; '''.format(json.dumps(self.current_frag))) self.current_frag = None - self.runJavaScript('window.pageYOffset/document.body.scrollHeight', QWebEngineScript.ApplicationWorld, self.frag_shown.emit) + self.runJavaScript('window.pageYOffset/document.body.scrollHeight', QWebEngineScript.ScriptWorldId.ApplicationWorld, self.frag_shown.emit) # }}} @@ -124,8 +124,8 @@ class ItemEdit(QWidget): w.setLayout(l) self.view = WebView(self) self.view.elem_clicked.connect(self.elem_clicked) - self.view.frag_shown.connect(self.update_dest_label, type=Qt.QueuedConnection) - self.view.loadFinished.connect(self.load_finished, type=Qt.QueuedConnection) + self.view.frag_shown.connect(self.update_dest_label, type=Qt.ConnectionType.QueuedConnection) + self.view.loadFinished.connect(self.load_finished, type=Qt.ConnectionType.QueuedConnection) l.addWidget(self.view, 0, 0, 1, 3) sp.addWidget(w) @@ -185,7 +185,7 @@ class ItemEdit(QWidget): self.pending_search = None def keyPressEvent(self, ev): - if ev.key() in (Qt.Key_Return, Qt.Key_Enter) and self.search_text.hasFocus(): + if ev.key() in (Qt.Key.Key_Return, Qt.Key.Key_Enter) and self.search_text.hasFocus(): # Prevent pressing enter in the search box from triggering the dialog's accept() method ev.accept() return @@ -193,7 +193,7 @@ class ItemEdit(QWidget): def find(self, forwards=True): text = unicode_type(self.search_text.text()).strip() - flags = QWebEnginePage.FindFlags(0) if forwards else QWebEnginePage.FindBackward + flags = QWebEnginePage.FindFlags(0) if forwards else QWebEnginePage.FindFlag.FindBackward self.find_data = text, flags, forwards self.view.findText(text, flags, self.find_callback) @@ -206,9 +206,9 @@ class ItemEdit(QWidget): _('No match found for: %s')%text, show=True) delta = 1 if forwards else -1 - current = unicode_type(d.currentItem().data(Qt.DisplayRole) or '') + current = unicode_type(d.currentItem().data(Qt.ItemDataRole.DisplayRole) or '') next_index = (d.currentRow() + delta)%d.count() - next = unicode_type(d.item(next_index).data(Qt.DisplayRole) or '') + next = unicode_type(d.item(next_index).data(Qt.ItemDataRole.DisplayRole) or '') msg = '

'+_('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('

%s

'%name) - self.icon_label.setPixmap(item.data(0, Qt.DecorationRole + self.icon_label.setPixmap(item.data(0, Qt.ItemDataRole.DecorationRole ).pixmap(32, 32)) tt = _('This entry points to an existing destination') - toc = item.data(0, Qt.UserRole) + toc = item.data(0, Qt.ItemDataRole.UserRole) if toc.dest_exists is False: tt = _('The location this entry points to does not exist') elif toc.dest_exists is None: @@ -372,7 +372,7 @@ class ItemView(QStackedWidget): # {{{ # }}} -NODE_FLAGS = (Qt.ItemIsDragEnabled|Qt.ItemIsEditable|Qt.ItemIsEnabled|Qt.ItemIsSelectable|Qt.ItemIsDropEnabled) +NODE_FLAGS = (Qt.ItemFlag.ItemIsDragEnabled|Qt.ItemFlag.ItemIsEditable|Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsSelectable|Qt.ItemFlag.ItemIsDropEnabled) class TreeWidget(QTreeWidget): # {{{ @@ -392,13 +392,13 @@ class TreeWidget(QTreeWidget): # {{{ self.setDragDropMode(self.InternalMove) self.setAutoScroll(True) self.setAutoScrollMargin(ICON_SIZE*2) - self.setDefaultDropAction(Qt.MoveAction) + self.setDefaultDropAction(Qt.DropAction.MoveAction) self.setAutoExpandDelay(1000) self.setAnimated(True) self.setMouseTracking(True) self.in_drop_event = False self.root = self.invisibleRootItem() - self.setContextMenuPolicy(Qt.CustomContextMenu) + self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.customContextMenuRequested.connect(self.show_context_menu) def push_history(self): @@ -424,7 +424,7 @@ class TreeWidget(QTreeWidget): # {{{ yield gc def update_status_tip(self, item): - c = item.data(0, Qt.UserRole) + c = item.data(0, Qt.ItemDataRole.UserRole) if c is not None: frag = c.frag or '' if frag: @@ -436,10 +436,10 @@ class TreeWidget(QTreeWidget): # {{{ def serialize_node(node): return { - 'title': node.data(0, Qt.DisplayRole), - 'toc_node': node.data(0, Qt.UserRole), - 'icon': node.data(0, Qt.DecorationRole), - 'tooltip': node.data(0, Qt.ToolTipRole), + 'title': node.data(0, Qt.ItemDataRole.DisplayRole), + 'toc_node': node.data(0, Qt.ItemDataRole.UserRole), + 'icon': node.data(0, Qt.ItemDataRole.DecorationRole), + 'tooltip': node.data(0, Qt.ItemDataRole.ToolTipRole), 'is_selected': node.isSelected(), 'is_expanded': node.isExpanded(), 'children': list(map(serialize_node, (node.child(i) for i in range(node.childCount())))), @@ -452,11 +452,11 @@ class TreeWidget(QTreeWidget): # {{{ def unserialize_node(dict_node, parent): n = QTreeWidgetItem(parent) - n.setData(0, Qt.DisplayRole, dict_node['title']) - n.setData(0, Qt.UserRole, dict_node['toc_node']) + n.setData(0, Qt.ItemDataRole.DisplayRole, dict_node['title']) + n.setData(0, Qt.ItemDataRole.UserRole, dict_node['toc_node']) n.setFlags(NODE_FLAGS) - n.setData(0, Qt.DecorationRole, dict_node['icon']) - n.setData(0, Qt.ToolTipRole, dict_node['tooltip']) + n.setData(0, Qt.ItemDataRole.DecorationRole, dict_node['icon']) + n.setData(0, Qt.ItemDataRole.ToolTipRole, dict_node['tooltip']) self.update_status_tip(n) n.setExpanded(dict_node['is_expanded']) n.setSelected(dict_node['is_selected']) @@ -487,7 +487,7 @@ class TreeWidget(QTreeWidget): # {{{ return ans def highlight_item(self, item): - self.setCurrentItem(item, 0, QItemSelectionModel.ClearAndSelect) + self.setCurrentItem(item, 0, QItemSelectionModel.SelectionFlag.ClearAndSelect) self.scrollToItem(item) def check_multi_selection(self): @@ -597,34 +597,34 @@ class TreeWidget(QTreeWidget): # {{{ self.push_history() from calibre.utils.titlecase import titlecase for item in self.selectedItems(): - t = unicode_type(item.data(0, Qt.DisplayRole) or '') - item.setData(0, Qt.DisplayRole, titlecase(t)) + t = unicode_type(item.data(0, Qt.ItemDataRole.DisplayRole) or '') + item.setData(0, Qt.ItemDataRole.DisplayRole, titlecase(t)) def upper_case(self): self.push_history() for item in self.selectedItems(): - t = unicode_type(item.data(0, Qt.DisplayRole) or '') - item.setData(0, Qt.DisplayRole, icu_upper(t)) + t = unicode_type(item.data(0, Qt.ItemDataRole.DisplayRole) or '') + item.setData(0, Qt.ItemDataRole.DisplayRole, icu_upper(t)) def lower_case(self): self.push_history() for item in self.selectedItems(): - t = unicode_type(item.data(0, Qt.DisplayRole) or '') - item.setData(0, Qt.DisplayRole, icu_lower(t)) + t = unicode_type(item.data(0, Qt.ItemDataRole.DisplayRole) or '') + item.setData(0, Qt.ItemDataRole.DisplayRole, icu_lower(t)) def swap_case(self): self.push_history() from calibre.utils.icu import swapcase for item in self.selectedItems(): - t = unicode_type(item.data(0, Qt.DisplayRole) or '') - item.setData(0, Qt.DisplayRole, swapcase(t)) + t = unicode_type(item.data(0, Qt.ItemDataRole.DisplayRole) or '') + item.setData(0, Qt.ItemDataRole.DisplayRole, swapcase(t)) def capitalize(self): self.push_history() from calibre.utils.icu import capitalize for item in self.selectedItems(): - t = unicode_type(item.data(0, Qt.DisplayRole) or '') - item.setData(0, Qt.DisplayRole, capitalize(t)) + t = unicode_type(item.data(0, Qt.ItemDataRole.DisplayRole) or '') + item.setData(0, Qt.ItemDataRole.DisplayRole, capitalize(t)) def bulk_rename(self): from calibre.gui2.tweak_book.file_list import get_bulk_rename_settings @@ -636,22 +636,22 @@ class TreeWidget(QTreeWidget): # {{{ if fmt is not None and num is not None: self.push_history() for i, item in enumerate(items): - item.setData(0, Qt.DisplayRole, fmt % (num + i)) + item.setData(0, Qt.ItemDataRole.DisplayRole, fmt % (num + i)) def keyPressEvent(self, ev): - if ev.key() == Qt.Key_Left and ev.modifiers() & Qt.CTRL: + if ev.key() == Qt.Key.Key_Left and ev.modifiers() & Qt.Modifier.CTRL: self.move_left() ev.accept() - elif ev.key() == Qt.Key_Right and ev.modifiers() & Qt.CTRL: + elif ev.key() == Qt.Key.Key_Right and ev.modifiers() & Qt.Modifier.CTRL: self.move_right() ev.accept() - elif ev.key() == Qt.Key_Up and (ev.modifiers() & Qt.CTRL or ev.modifiers() & Qt.ALT): + elif ev.key() == Qt.Key.Key_Up and (ev.modifiers() & Qt.Modifier.CTRL or ev.modifiers() & Qt.Modifier.ALT): self.move_up() ev.accept() - elif ev.key() == Qt.Key_Down and (ev.modifiers() & Qt.CTRL or ev.modifiers() & Qt.ALT): + elif ev.key() == Qt.Key.Key_Down and (ev.modifiers() & Qt.Modifier.CTRL or ev.modifiers() & Qt.Modifier.ALT): self.move_down() ev.accept() - elif ev.key() in (Qt.Key_Delete, Qt.Key_Backspace): + elif ev.key() in (Qt.Key.Key_Delete, Qt.Key.Key_Backspace): self.del_items() ev.accept() else: @@ -661,7 +661,7 @@ class TreeWidget(QTreeWidget): # {{{ item = self.currentItem() def key(k): - sc = unicode_type(QKeySequence(k | Qt.CTRL).toString(QKeySequence.NativeText)) + sc = unicode_type(QKeySequence(k | Qt.Modifier.CTRL).toString(QKeySequence.SequenceFormat.NativeText)) return ' [%s]'%sc if item is not None: @@ -670,17 +670,17 @@ class TreeWidget(QTreeWidget): # {{{ m.addAction(QIcon(I('modified.png')), _('Bulk rename all selected items'), self.bulk_rename) m.addAction(QIcon(I('trash.png')), _('Remove all selected items'), self.del_items) m.addSeparator() - ci = unicode_type(item.data(0, Qt.DisplayRole) or '') + ci = unicode_type(item.data(0, Qt.ItemDataRole.DisplayRole) or '') p = item.parent() or self.invisibleRootItem() idx = p.indexOfChild(item) if idx > 0: - m.addAction(QIcon(I('arrow-up.png')), (_('Move "%s" up')%ci)+key(Qt.Key_Up), self.move_up) + m.addAction(QIcon(I('arrow-up.png')), (_('Move "%s" up')%ci)+key(Qt.Key.Key_Up), self.move_up) if idx + 1 < p.childCount(): - m.addAction(QIcon(I('arrow-down.png')), (_('Move "%s" down')%ci)+key(Qt.Key_Down), self.move_down) + m.addAction(QIcon(I('arrow-down.png')), (_('Move "%s" down')%ci)+key(Qt.Key.Key_Down), self.move_down) if item.parent() is not None: - m.addAction(QIcon(I('back.png')), (_('Unindent "%s"')%ci)+key(Qt.Key_Left), self.move_left) + m.addAction(QIcon(I('back.png')), (_('Unindent "%s"')%ci)+key(Qt.Key.Key_Left), self.move_left) if idx > 0: - m.addAction(QIcon(I('forward.png')), (_('Indent "%s"')%ci)+key(Qt.Key_Right), self.move_right) + m.addAction(QIcon(I('forward.png')), (_('Indent "%s"')%ci)+key(Qt.Key.Key_Right), self.move_right) m.addSeparator() case_menu = QMenu(_('Change case'), m) @@ -751,7 +751,7 @@ class TOCView(QWidget): # {{{ l.addWidget(b, col, 1) self.default_msg = _('Double click on an entry to change the text') self.hl = hl = QLabel(self.default_msg) - hl.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) + hl.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Ignored) l.addWidget(hl, col, 2, 1, -1) self.item_view = i = ItemView(self, self.prefs) self.item_view.delete_item.connect(self.delete_current_item) @@ -776,7 +776,7 @@ class TOCView(QWidget): # {{{ return super(TOCView, self).event(e) def item_title(self, item): - return unicode_type(item.data(0, Qt.DisplayRole) or '') + return unicode_type(item.data(0, Qt.ItemDataRole.DisplayRole) or '') def del_items(self): self.tocw.del_items() @@ -831,8 +831,8 @@ class TOCView(QWidget): # {{{ def data_changed(self, top_left, bottom_right): for r in range(top_left.row(), bottom_right.row()+1): idx = self.tocw.model().index(r, 0, top_left.parent()) - new_title = unicode_type(idx.data(Qt.DisplayRole) or '').strip() - toc = idx.data(Qt.UserRole) + new_title = unicode_type(idx.data(Qt.ItemDataRole.DisplayRole) or '').strip() + toc = idx.data(Qt.ItemDataRole.UserRole) if toc is not None: toc.title = new_title or _('(Untitled)') item = self.tocw.itemFromIndex(idx) @@ -849,16 +849,16 @@ class TOCView(QWidget): # {{{ return c def populate_item(self, c, child): - c.setData(0, Qt.DisplayRole, child.title or _('(Untitled)')) - c.setData(0, Qt.UserRole, child) + c.setData(0, Qt.ItemDataRole.DisplayRole, child.title or _('(Untitled)')) + c.setData(0, Qt.ItemDataRole.UserRole, child) c.setFlags(NODE_FLAGS) - c.setData(0, Qt.DecorationRole, self.icon_map[child.dest_exists]) + c.setData(0, Qt.ItemDataRole.DecorationRole, self.icon_map[child.dest_exists]) if child.dest_exists is False: - c.setData(0, Qt.ToolTipRole, _( + c.setData(0, Qt.ItemDataRole.ToolTipRole, _( 'The location this entry point to does not exist:\n%s') %child.dest_error) else: - c.setData(0, Qt.ToolTipRole, None) + c.setData(0, Qt.ItemDataRole.ToolTipRole, None) self.tocw.update_status_tip(c) @@ -880,7 +880,7 @@ class TOCView(QWidget): # {{{ process_item(child, c) root = self.root = self.tocw.invisibleRootItem() - root.setData(0, Qt.UserRole, self.toc) + root.setData(0, Qt.ItemDataRole.UserRole, self.toc) process_item(self.toc, root) self.tocw.model().dataChanged.connect(self.data_changed) self.tocw.currentItemChanged.connect(self.current_item_changed) @@ -898,7 +898,7 @@ class TOCView(QWidget): # {{{ if item is None: # New entry at root level c = self.create_item(self.root, child) - self.tocw.setCurrentItem(c, 0, QItemSelectionModel.ClearAndSelect) + self.tocw.setCurrentItem(c, 0, QItemSelectionModel.SelectionFlag.ClearAndSelect) self.tocw.scrollToItem(c) else: if where is None: @@ -914,7 +914,7 @@ class TOCView(QWidget): # {{{ if where == 'after': idx += 1 c = self.create_item(parent, child, idx=idx) - self.tocw.setCurrentItem(c, 0, QItemSelectionModel.ClearAndSelect) + self.tocw.setCurrentItem(c, 0, QItemSelectionModel.SelectionFlag.ClearAndSelect) self.tocw.scrollToItem(c) def create_toc(self): @@ -923,8 +923,8 @@ class TOCView(QWidget): # {{{ def process_node(parent, toc_parent): for i in range(parent.childCount()): item = parent.child(i) - title = unicode_type(item.data(0, Qt.DisplayRole) or '').strip() - toc = item.data(0, Qt.UserRole) + title = unicode_type(item.data(0, Qt.ItemDataRole.DisplayRole) or '').strip() + toc = item.data(0, Qt.ItemDataRole.UserRole) dest, frag = toc.dest, toc.frag toc = toc_parent.add(title, dest, frag) process_node(item, toc) @@ -1002,12 +1002,12 @@ class TOCEditor(QDialog): # {{{ self.pi = pi = ProgressIndicator() pi.setDisplaySize(QSize(200, 200)) pi.startAnimation() - ll.addWidget(pi, alignment=Qt.AlignHCenter|Qt.AlignCenter) + ll.addWidget(pi, alignment=Qt.AlignmentFlag.AlignHCenter|Qt.AlignmentFlag.AlignCenter) la = self.wait_label = QLabel(_('Loading %s, please wait...')%t) la.setWordWrap(True) f = la.font() f.setPointSize(20), la.setFont(f) - ll.addWidget(la, alignment=Qt.AlignHCenter|Qt.AlignTop) + ll.addWidget(la, alignment=Qt.AlignmentFlag.AlignHCenter|Qt.AlignmentFlag.AlignTop) self.toc_view = TOCView(self, self.prefs) self.toc_view.add_new_item.connect(self.add_new_item) self.toc_view.tocw.history_state_changed.connect(self.update_history_buttons) @@ -1015,7 +1015,7 @@ class TOCEditor(QDialog): # {{{ self.item_edit = ItemEdit(self) s.addWidget(self.item_edit) - bb = self.bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel) + bb = self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel) l.addWidget(bb) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) @@ -1024,8 +1024,8 @@ class TOCEditor(QDialog): # {{{ b.setIcon(QIcon(I('edit-undo.png'))) b.clicked.connect(self.toc_view.undo) - self.explode_done.connect(self.read_toc, type=Qt.QueuedConnection) - self.writing_done.connect(self.really_accept, type=Qt.QueuedConnection) + self.explode_done.connect(self.read_toc, type=Qt.ConnectionType.QueuedConnection) + self.writing_done.connect(self.really_accept, type=Qt.ConnectionType.QueuedConnection) r = QApplication.desktop().availableGeometry(self) self.resize(r.width() - 100, r.height() - 100) diff --git a/src/calibre/gui2/tools.py b/src/calibre/gui2/tools.py index d2a49e1a51..260ab1e6aa 100644 --- a/src/calibre/gui2/tools.py +++ b/src/calibre/gui2/tools.py @@ -45,11 +45,11 @@ def convert_single_ebook(parent, db, book_ids, auto_conversion=False, # {{{ if auto_conversion: d.accept() - result = QDialog.Accepted + result = QDialog.DialogCode.Accepted else: result = d.exec_() - if result == QDialog.Accepted: + if result == QDialog.DialogCode.Accepted: # if not convert_existing(parent, db, [book_id], d.output_format): # continue @@ -143,7 +143,7 @@ def convert_bulk_ebook(parent, queue, db, book_ids, out_format=None, args=[]): d = BulkConfig(parent, db, out_format, has_saved_settings=has_saved_settings, book_ids=book_ids) - if d.exec_() != QDialog.Accepted: + if d.exec_() != QDialog.DialogCode.Accepted: return None output_format = d.output_format diff --git a/src/calibre/gui2/tts/develop.py b/src/calibre/gui2/tts/develop.py index e850e79091..d0827c1e0c 100644 --- a/src/calibre/gui2/tts/develop.py +++ b/src/calibre/gui2/tts/develop.py @@ -51,11 +51,11 @@ class TTSWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.mark_changed.connect(self.on_mark_change) - self.dispatch_on_main_thread_signal.connect(self.dispatch_on_main_thread, type=Qt.QueuedConnection) + self.dispatch_on_main_thread_signal.connect(self.dispatch_on_main_thread, type=Qt.ConnectionType.QueuedConnection) self.tts = Client(self.dispatch_on_main_thread_signal.emit) self.l = l = QVBoxLayout(self) self.la = la = QLabel(self) - la.setTextFormat(Qt.RichText) + la.setTextFormat(Qt.TextFormat.RichText) la.setWordWrap(True) self.text = '''\ In their duty through weakness of will, which is the diff --git a/src/calibre/gui2/tweak_book/boss.py b/src/calibre/gui2/tweak_book/boss.py index 45b27ac000..ff9229819b 100644 --- a/src/calibre/gui2/tweak_book/boss.py +++ b/src/calibre/gui2/tweak_book/boss.py @@ -118,7 +118,7 @@ class Boss(QObject): get_boss.boss = self self.gui = parent completion_worker().result_callback = self.handle_completion_result_signal.emit - self.handle_completion_result_signal.connect(self.handle_completion_result, Qt.QueuedConnection) + self.handle_completion_result_signal.connect(self.handle_completion_result, Qt.ConnectionType.QueuedConnection) self.completion_request_count = 0 self.editor_cache = JSONConfig('editor-cache', base_path=cache_dir()) d = self.editor_cache.defaults @@ -745,7 +745,7 @@ class Boss(QObject): self.apply_container_update_to_gui() if from_filelist: self.gui.file_list.select_names(frozenset(itervalues(name_map)), current_name=name_map.get(from_filelist)) - self.gui.file_list.file_list.setFocus(Qt.PopupFocusReason) + self.gui.file_list.file_list.setFocus(Qt.FocusReason.PopupFocusReason) # }}} @@ -794,12 +794,12 @@ class Boss(QObject): if name in editors: editor = editors[name] editor.go_to_line(lnum) - editor.setFocus(Qt.OtherFocusReason) + editor.setFocus(Qt.FocusReason.OtherFocusReason) self.gui.raise_() d = Diff(revert_button_msg=revert_msg, show_open_in_editor=show_open_in_editor) [x.break_cycles() for x in _diff_dialogs if not x.isVisible()] _diff_dialogs = [x for x in _diff_dialogs if x.isVisible()] + [d] - d.show(), d.raise_(), d.setFocus(Qt.OtherFocusReason), d.setWindowModality(Qt.NonModal) + d.show(), d.raise_(), d.setFocus(Qt.FocusReason.OtherFocusReason), d.setWindowModality(Qt.WindowModality.NonModal) if show_open_in_editor: d.line_activated.connect(line_activated) return d @@ -831,7 +831,7 @@ class Boss(QObject): k.addWidget(cb) cb.setChecked(True) connect_lambda(cb.toggled, d, lambda d, checked: tprefs.set('skip_ask_to_show_current_diff_for_' + name, not checked)) - d.bb = bb = QDialogButtonBox(QDialogButtonBox.Close, d) + d.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close, d) k.addWidget(bb) bb.accepted.connect(d.accept) bb.rejected.connect(d.reject) @@ -994,7 +994,7 @@ class Boss(QObject): def show_text_search(self): self.gui.text_search_dock.show() - self.gui.text_search.find.setFocus(Qt.OtherFocusReason) + self.gui.text_search.find.setFocus(Qt.FocusReason.OtherFocusReason) def search_action_triggered(self, action, overrides=None): ss = self.gui.saved_searches.isVisible() @@ -1013,9 +1013,9 @@ class Boss(QObject): self.gui, self.show_editor, self.edit_file, self.show_current_diff, self.add_savepoint, self.rewind_savepoint, self.set_modified) ed = ret is True and self.gui.central.current_editor if getattr(ed, 'has_line_numbers', False): - ed.editor.setFocus(Qt.OtherFocusReason) + ed.editor.setFocus(Qt.FocusReason.OtherFocusReason) else: - self.gui.saved_searches.setFocus(Qt.OtherFocusReason) + self.gui.saved_searches.setFocus(Qt.FocusReason.OtherFocusReason) def search(self, action, overrides=None): # Run a search/replace @@ -1035,9 +1035,9 @@ class Boss(QObject): self.gui, self.show_editor, self.edit_file, self.show_current_diff, self.add_savepoint, self.rewind_savepoint, self.set_modified) ed = ret is True and self.gui.central.current_editor if getattr(ed, 'has_line_numbers', False): - ed.editor.setFocus(Qt.OtherFocusReason) + ed.editor.setFocus(Qt.FocusReason.OtherFocusReason) else: - self.gui.saved_searches.setFocus(Qt.OtherFocusReason) + self.gui.saved_searches.setFocus(Qt.FocusReason.OtherFocusReason) def find_text(self, state): from calibre.gui2.tweak_book.text_search import run_text_search @@ -1049,7 +1049,7 @@ class Boss(QObject): ret = run_text_search(state, ed, name, searchable_names, self.gui, self.show_editor, self.edit_file) ed = ret is True and self.gui.central.current_editor if getattr(ed, 'has_line_numbers', False): - ed.editor.setFocus(Qt.OtherFocusReason) + ed.editor.setFocus(Qt.FocusReason.OtherFocusReason) def find_word(self, word, locations): # Go to a word from the spell check dialog @@ -1773,7 +1773,7 @@ class Boss(QObject): d.m = QLabel(_('There are unsaved changes, if you quit without saving, you will lose them.')) d.m.setWordWrap(True) d.l.addWidget(d.m, 0, 1) - d.bb = QDialogButtonBox(QDialogButtonBox.Cancel) + d.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel) d.bb.rejected.connect(d.reject) d.bb.accepted.connect(d.accept) d.l.addWidget(d.bb, 1, 0, 1, 2) @@ -1782,10 +1782,10 @@ class Boss(QObject): def endit(d, x): d.do_save = x d.accept() - b = d.bb.addButton(_('&Save and Quit'), QDialogButtonBox.ActionRole) + b = d.bb.addButton(_('&Save and Quit'), QDialogButtonBox.ButtonRole.ActionRole) b.setIcon(QIcon(I('save.png'))) connect_lambda(b.clicked, d, lambda d: endit(d, True)) - b = d.bb.addButton(_('&Quit without saving'), QDialogButtonBox.ActionRole) + b = d.bb.addButton(_('&Quit without saving'), QDialogButtonBox.ButtonRole.ActionRole) connect_lambda(b.clicked, d, lambda d: endit(d, False)) d.resize(d.sizeHint()) if d.exec_() != d.Accepted or d.do_save is None: diff --git a/src/calibre/gui2/tweak_book/char_select.py b/src/calibre/gui2/tweak_book/char_select.py index f9eb410fe0..e2ec301d76 100644 --- a/src/calibre/gui2/tweak_book/char_select.py +++ b/src/calibre/gui2/tweak_book/char_select.py @@ -402,19 +402,19 @@ class CategoryModel(QAbstractItemModel): return ROOT return self.index(pid - 1, 0) - def data(self, index, role=Qt.DisplayRole): + def data(self, index, role=Qt.ItemDataRole.DisplayRole): if not index.isValid(): return None pid = index.internalId() if pid == 0: - if role == Qt.DisplayRole: + if role == Qt.ItemDataRole.DisplayRole: return self.categories[index.row()][0] - if role == Qt.FontRole: + if role == Qt.ItemDataRole.FontRole: return self.bold_font - if role == Qt.DecorationRole and index.row() == 0: + if role == Qt.ItemDataRole.DecorationRole and index.row() == 0: return self.fav_icon else: - if role == Qt.DisplayRole: + if role == Qt.ItemDataRole.DisplayRole: item = self.categories[pid - 1][1][index.row()] return item[0] return None @@ -501,19 +501,19 @@ class CharModel(QAbstractListModel): return len(self.chars) def data(self, index, role): - if role == Qt.UserRole and -1 < index.row() < len(self.chars): + if role == Qt.ItemDataRole.UserRole and -1 < index.row() < len(self.chars): return self.chars[index.row()] return None def flags(self, index): - ans = Qt.ItemIsEnabled + ans = Qt.ItemFlag.ItemIsEnabled if self.allow_dnd: - ans |= Qt.ItemIsSelectable - ans |= Qt.ItemIsDragEnabled if index.isValid() else Qt.ItemIsDropEnabled + ans |= Qt.ItemFlag.ItemIsSelectable + ans |= Qt.ItemFlag.ItemIsDragEnabled if index.isValid() else Qt.ItemFlag.ItemIsDropEnabled return ans def supportedDropActions(self): - return Qt.MoveAction + return Qt.DropAction.MoveAction def mimeTypes(self): return ['application/calibre_charcode_indices'] @@ -525,7 +525,7 @@ class CharModel(QAbstractListModel): return md def dropMimeData(self, md, action, row, column, parent): - if action != Qt.MoveAction or not md.hasFormat('application/calibre_charcode_indices') or row < 0 or column != 0: + if action != Qt.DropAction.MoveAction or not md.hasFormat('application/calibre_charcode_indices') or row < 0 or column != 0: return False indices = list(map(int, bytes(md.data('application/calibre_charcode_indices')).decode('ascii').split(','))) codes = [self.chars[x] for x in indices] @@ -553,7 +553,7 @@ class CharDelegate(QStyledItemDelegate): def paint(self, painter, option, index): QStyledItemDelegate.paint(self, painter, option, index) try: - charcode = int(index.data(Qt.UserRole)) + charcode = int(index.data(Qt.ItemDataRole.UserRole)) except (TypeError, ValueError): return painter.save() @@ -569,12 +569,12 @@ class CharDelegate(QStyledItemDelegate): f = option.font f.setPixelSize(option.rect.height() - 8) painter.setFont(f) - painter.drawText(option.rect, Qt.AlignHCenter | Qt.AlignBottom | Qt.TextSingleLine, codepoint_to_chr(charcode)) + painter.drawText(option.rect, Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignBottom | Qt.TextFlag.TextSingleLine, codepoint_to_chr(charcode)) def paint_non_printing(self, painter, option, charcode): text = self.np_pat.sub(r'\n\1', non_printing[charcode]) - painter.drawText(option.rect, Qt.AlignCenter | Qt.TextWordWrap | Qt.TextWrapAnywhere, text) - painter.setPen(QPen(Qt.DashLine)) + painter.drawText(option.rect, Qt.AlignmentFlag.AlignCenter | Qt.TextFlag.TextWordWrap | Qt.TextFlag.TextWrapAnywhere, text) + painter.setPen(QPen(Qt.PenStyle.DashLine)) painter.drawRect(option.rect.adjusted(1, 1, -1, -1)) @@ -596,7 +596,7 @@ class CharView(QListView): self.setMouseTracking(True) self.setSpacing(2) self.setUniformItemSizes(True) - self.setContextMenuPolicy(Qt.CustomContextMenu) + self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.customContextMenuRequested.connect(self.context_menu) self.showing_favorites = False set_no_activate_on_click(self) @@ -605,7 +605,7 @@ class CharView(QListView): def item_activated(self, index): try: - char_code = int(self.model().data(index, Qt.UserRole)) + char_code = int(self.model().data(index, Qt.ItemDataRole.UserRole)) except (TypeError, ValueError): pass else: @@ -639,14 +639,14 @@ class CharView(QListView): if row != self.last_mouse_idx: self.last_mouse_idx = row try: - char_code = int(self.model().data(index, Qt.UserRole)) + char_code = int(self.model().data(index, Qt.ItemDataRole.UserRole)) except (TypeError, ValueError): pass else: self.show_name.emit(char_code) - self.setCursor(Qt.PointingHandCursor) + self.setCursor(Qt.CursorShape.PointingHandCursor) else: - self.setCursor(Qt.ArrowCursor) + self.setCursor(Qt.CursorShape.ArrowCursor) self.show_name.emit(-1) self.last_mouse_idx = -1 return QListView.mouseMoveEvent(self, ev) @@ -655,7 +655,7 @@ class CharView(QListView): index = self.indexAt(pos) if index.isValid(): try: - char_code = int(self.model().data(index, Qt.UserRole)) + char_code = int(self.model().data(index, Qt.ItemDataRole.UserRole)) except (TypeError, ValueError): pass else: @@ -711,7 +711,7 @@ class CharSelect(Dialog): b.setDefault(True) self.splitter = s = QSplitter(self) - s.setFocusPolicy(Qt.NoFocus) + s.setFocusPolicy(Qt.FocusPolicy.NoFocus) s.setChildrenCollapsible(False) self.search = h = HistoryLineEdit2(self) @@ -722,21 +722,21 @@ class CharSelect(Dialog): h.initialize('charmap_search') h.setPlaceholderText(_('Search by name, nickname or character code')) self.search_button = b = QPushButton(_('&Search')) - b.setFocusPolicy(Qt.NoFocus) + b.setFocusPolicy(Qt.FocusPolicy.NoFocus) h.returnPressed.connect(self.do_search) b.clicked.connect(self.do_search) self.clear_button = cb = QToolButton(self) cb.setIcon(QIcon(I('clear_left.png'))) - cb.setFocusPolicy(Qt.NoFocus) + cb.setFocusPolicy(Qt.FocusPolicy.NoFocus) cb.setText(_('Clear search')) cb.clicked.connect(self.clear_search) l.addWidget(h), l.addWidget(b, 0, 1), l.addWidget(cb, 0, 2) self.category_view = CategoryView(self) - self.category_view.setFocusPolicy(Qt.NoFocus) + self.category_view.setFocusPolicy(Qt.FocusPolicy.NoFocus) l.addWidget(s, 1, 0, 1, 3) self.char_view = CharView(self) - self.char_view.setFocusPolicy(Qt.NoFocus) + self.char_view.setFocusPolicy(Qt.FocusPolicy.NoFocus) self.rearrange_button.toggled[bool].connect(self.set_allow_drag_and_drop) self.category_view.category_selected.connect(self.show_chars) self.char_view.show_name.connect(self.show_char_info) @@ -744,12 +744,12 @@ class CharSelect(Dialog): s.addWidget(self.category_view), s.addWidget(self.char_view) self.char_info = la = QLabel('\xa0') - la.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) + la.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) l.addWidget(la, 2, 0, 1, 3) self.rearrange_msg = la = QLabel(_( 'Drag and drop characters to re-arrange them. Click the "Re-arrange" button again when you are done.')) - la.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) + la.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) la.setVisible(False) l.addWidget(la, 3, 0, 1, 3) self.h = h = QHBoxLayout() @@ -760,7 +760,7 @@ class CharSelect(Dialog): connect_lambda(mm.stateChanged, self, lambda self: tprefs.set('char_select_match_any', self.match_any.isChecked())) h.addWidget(mm), h.addStretch(), h.addWidget(self.bb) l.addLayout(h, 4, 0, 1, 3) - self.char_view.setFocus(Qt.OtherFocusReason) + self.char_view.setFocus(Qt.FocusReason.OtherFocusReason) def do_search(self): text = unicode_type(self.search.text()).strip() @@ -807,7 +807,7 @@ class CharSelect(Dialog): self.raise_() def char_selected(self, c): - if QApplication.keyboardModifiers() & Qt.CTRL: + if QApplication.keyboardModifiers() & Qt.Modifier.CTRL: self.hide() if self.parent() is None or self.parent().focusWidget() is None: QApplication.clipboard().setText(c) diff --git a/src/calibre/gui2/tweak_book/check.py b/src/calibre/gui2/tweak_book/check.py index 795cee8f23..f08dc45358 100644 --- a/src/calibre/gui2/tweak_book/check.py +++ b/src/calibre/gui2/tweak_book/check.py @@ -51,7 +51,7 @@ class Delegate(QStyledItemDelegate): super(Delegate, self).initStyleOption(option, index) if index.row() == self.parent().currentRow(): option.font.setBold(True) - option.backgroundBrush = self.parent().palette().brush(QPalette.AlternateBase) + option.backgroundBrush = self.parent().palette().brush(QPalette.ColorRole.AlternateBase) class Check(QSplitter): @@ -65,7 +65,7 @@ class Check(QSplitter): self.setChildrenCollapsible(False) self.items = i = QListWidget(self) - i.setContextMenuPolicy(Qt.CustomContextMenu) + i.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) i.customContextMenuRequested.connect(self.context_menu) self.items.setSpacing(3) self.items.itemDoubleClicked.connect(self.current_item_activated) @@ -101,7 +101,7 @@ class Check(QSplitter): items = [] for item in (self.items.item(i) for i in range(self.items.count())): msg = unicode_type(item.text()) - msg = prefix_for_level(item.data(Qt.UserRole).level) + msg + msg = prefix_for_level(item.data(Qt.ItemDataRole.UserRole).level) + msg items.append(msg) if items: QApplication.clipboard().setText('\n'.join(items)) @@ -122,11 +122,11 @@ class Check(QSplitter): elif url == 'run:check': self.check_requested.emit() elif url == 'fix:errors': - errors = [self.items.item(i).data(Qt.UserRole) for i in range(self.items.count())] + errors = [self.items.item(i).data(Qt.ItemDataRole.UserRole) for i in range(self.items.count())] self.fix_requested.emit(errors) elif url.startswith('fix:error,'): num = int(url.rpartition(',')[-1]) - errors = [self.items.item(num).data(Qt.UserRole)] + errors = [self.items.item(num).data(Qt.ItemDataRole.UserRole)] self.fix_requested.emit(errors) elif url.startswith('activate:item:'): index = int(url.rpartition(':')[-1]) @@ -145,7 +145,7 @@ class Check(QSplitter): def current_item_activated(self, *args): i = self.items.currentItem() if i is not None: - err = i.data(Qt.UserRole) + err = i.data(Qt.ItemDataRole.UserRole) if err.has_multiple_locations: self.location_activated(0) else: @@ -154,7 +154,7 @@ class Check(QSplitter): def location_activated(self, index): i = self.items.currentItem() if i is not None: - err = i.data(Qt.UserRole) + err = i.data(Qt.ItemDataRole.UserRole) err.current_location_index = index self.item_activated.emit(err) @@ -173,7 +173,7 @@ class Check(QSplitter): return loc if i is not None: - err = i.data(Qt.UserRole) + err = i.data(Qt.ItemDataRole.UserRole) header = {DEBUG:_('Debug'), INFO:_('Information'), WARN:_('Warning'), ERROR:_('Error'), CRITICAL:_('Error')}[err.level] ifix = '' loc = loc_to_string(err.line, err.col) @@ -216,12 +216,12 @@ class Check(QSplitter): for err in sorted(errors, key=lambda e:(100 - e.level, e.name)): i = QListWidgetItem('%s\xa0\xa0\xa0\xa0[%s]' % (err.msg, err.name), self.items) - i.setData(Qt.UserRole, err) + i.setData(Qt.ItemDataRole.UserRole, err) i.setIcon(icon_for_level(err.level)) if errors: self.items.setCurrentRow(0) self.current_item_changed() - self.items.setFocus(Qt.OtherFocusReason) + self.items.setFocus(Qt.FocusReason.OtherFocusReason) else: self.clear_help() @@ -242,7 +242,7 @@ class Check(QSplitter): self.items.clear() 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): self.current_item_activated() return super(Check, self).keyPressEvent(ev) diff --git a/src/calibre/gui2/tweak_book/check_links.py b/src/calibre/gui2/tweak_book/check_links.py index 43c598dca9..0fad39d3be 100644 --- a/src/calibre/gui2/tweak_book/check_links.py +++ b/src/calibre/gui2/tweak_book/check_links.py @@ -42,7 +42,7 @@ class CheckExternalLinks(Dialog): def __init__(self, parent=None): Dialog.__init__(self, _('Check external links'), 'check-external-links-dialog', parent) - self.progress_made.connect(self.on_progress_made, type=Qt.QueuedConnection) + self.progress_made.connect(self.on_progress_made, type=Qt.ConnectionType.QueuedConnection) def show(self): if self.rb.isEnabled(): @@ -59,14 +59,14 @@ class CheckExternalLinks(Dialog): def setup_ui(self): self.pb = pb = QProgressBar(self) pb.setTextVisible(True) - pb.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) + pb.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) pb.setRange(0, 0) self.w = w = QWidget(self) self.w.l = l = QVBoxLayout(w) l.addStretch(), l.addWidget(pb) self.w.la = la = QLabel(_('Checking external links, please wait...')) la.setStyleSheet('QLabel { font-size: 20px; font-weight: bold }') - l.addWidget(la, 0, Qt.AlignCenter), l.addStretch() + l.addWidget(la, 0, Qt.AlignmentFlag.AlignCenter), l.addStretch() self.l = l = QVBoxLayout(self) self.results = QTextBrowser(self) diff --git a/src/calibre/gui2/tweak_book/completion/basic.py b/src/calibre/gui2/tweak_book/completion/basic.py index 766629a1d9..5c55c13764 100644 --- a/src/calibre/gui2/tweak_book/completion/basic.py +++ b/src/calibre/gui2/tweak_book/completion/basic.py @@ -153,7 +153,7 @@ class HandleDataRequest(QObject): def __init__(self): QObject.__init__(self) self.called = Event() - self.call.connect(self.run_func, Qt.QueuedConnection) + self.call.connect(self.run_func, Qt.ConnectionType.QueuedConnection) def run_func(self, func, data): try: diff --git a/src/calibre/gui2/tweak_book/completion/popup.py b/src/calibre/gui2/tweak_book/completion/popup.py index b9cdcacb46..003993b0dd 100644 --- a/src/calibre/gui2/tweak_book/completion/popup.py +++ b/src/calibre/gui2/tweak_book/completion/popup.py @@ -26,11 +26,11 @@ class ChoosePopupWidget(QWidget): def __init__(self, parent, max_height=1000): QWidget.__init__(self, parent) - self.setFocusPolicy(Qt.NoFocus) + self.setFocusPolicy(Qt.FocusPolicy.NoFocus) self.setFocusProxy(parent) self.setVisible(False) self.setMouseTracking(True) - self.setCursor(Qt.PointingHandCursor) + self.setCursor(Qt.CursorShape.PointingHandCursor) self.current_results = self.current_size_hint = None @@ -40,8 +40,8 @@ class ChoosePopupWidget(QWidget): self.max_height = max_height self.text_option = to = QTextOption() - to.setWrapMode(QTextOption.NoWrap) - to.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) + to.setWrapMode(QTextOption.WrapMode.NoWrap) + to.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter) self.rendered_text_cache = {} parent.installEventFilter(self) @@ -71,11 +71,11 @@ class ChoosePopupWidget(QWidget): desc = self.descriptions.get(otext) if desc: text += ' - %s' % prepare_string_for_xml(desc) - color = self.palette().color(QPalette.Text).name() + color = self.palette().color(QPalette.ColorRole.Text).name() text = '%s' % (color, text) st = self.rendered_text_cache[otext] = QStaticText(text) st.setTextOption(self.text_option) - st.setTextFormat(Qt.RichText) + st.setTextFormat(Qt.TextFormat.RichText) st.prepare(font=self.parent().font()) return st @@ -119,7 +119,7 @@ class ChoosePopupWidget(QWidget): painter.save() if i == self.current_index: painter.fillRect(1, y, width, height, pal.color(pal.Highlight)) - color = pal.color(QPalette.HighlightedText).name() + color = pal.color(QPalette.ColorRole.HighlightedText).name() st = QStaticText(st) text = st.text().partition('>')[2] st.setText('%s' % (color, text)) @@ -177,18 +177,18 @@ class ChoosePopupWidget(QWidget): def handle_keypress(self, ev): key = ev.key() - if key == Qt.Key_Escape: + if key == Qt.Key.Key_Escape: self.abort(), ev.accept() return True - if key == Qt.Key_Tab and not ev.modifiers() & Qt.CTRL: - self.choose_next_result(previous=ev.modifiers() & Qt.ShiftModifier) + if key == Qt.Key.Key_Tab and not ev.modifiers() & Qt.Modifier.CTRL: + self.choose_next_result(previous=ev.modifiers() & Qt.KeyboardModifier.ShiftModifier) ev.accept() return True - if key == Qt.Key_Backtab and not ev.modifiers() & Qt.CTRL: - self.choose_next_result(previous=ev.modifiers() & Qt.ShiftModifier) + if key == Qt.Key.Key_Backtab and not ev.modifiers() & Qt.Modifier.CTRL: + self.choose_next_result(previous=ev.modifiers() & Qt.KeyboardModifier.ShiftModifier) return True - if key in (Qt.Key_Up, Qt.Key_Down): - self.choose_next_result(previous=key == Qt.Key_Up) + if key in (Qt.Key.Key_Up, Qt.Key.Key_Down): + self.choose_next_result(previous=key == Qt.Key.Key_Up) return True return False diff --git a/src/calibre/gui2/tweak_book/diff/main.py b/src/calibre/gui2/tweak_book/diff/main.py index 6d57d8187c..144fc7ac50 100644 --- a/src/calibre/gui2/tweak_book/diff/main.py +++ b/src/calibre/gui2/tweak_book/diff/main.py @@ -34,10 +34,10 @@ class BusyWidget(QWidget): # {{{ self.setLayout(l) l.addStretch(10) self.pi = ProgressIndicator(self, 128) - l.addWidget(self.pi, alignment=Qt.AlignHCenter) + l.addWidget(self.pi, alignment=Qt.AlignmentFlag.AlignHCenter) self.dummy = QLabel('

\xa0') l.addSpacing(10) - l.addWidget(self.dummy, alignment=Qt.AlignHCenter) + l.addWidget(self.dummy, alignment=Qt.AlignmentFlag.AlignHCenter) l.addStretch(10) self.text = _('Calculating differences, please wait...') @@ -50,9 +50,9 @@ class BusyWidget(QWidget): # {{{ f.setBold(True) f.setPointSize(20) p.setFont(f) - p.setPen(Qt.SolidLine) + p.setPen(Qt.PenStyle.SolidLine) r = QRect(0, self.dummy.geometry().top() + 10, self.geometry().width(), 150) - p.drawText(r, Qt.AlignHCenter | Qt.AlignTop | Qt.TextSingleLine, self.text) + p.drawText(r, Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop | Qt.TextFlag.TextSingleLine, self.text) p.end() # }}} @@ -214,9 +214,9 @@ class Diff(Dialog): self.show_open_in_editor = show_open_in_editor self.revert_button_msg = revert_button_msg Dialog.__init__(self, _('Differences between books'), 'diff-dialog', parent=parent) - self.setWindowFlags(self.windowFlags() | Qt.WindowMinMaxButtonsHint) + self.setWindowFlags(self.windowFlags() | Qt.WindowType.WindowMinMaxButtonsHint) if show_as_window: - self.setWindowFlags(Qt.Window) + self.setWindowFlags(Qt.WindowType.Window) self.view.line_activated.connect(self.line_activated) def sizeHint(self): @@ -242,14 +242,14 @@ class Diff(Dialog): b.setIcon(QIcon(I('back.png'))) connect_lambda(b.clicked, self, lambda self: self.view.next_change(-1)) b.setToolTip(_('Go to previous change') + ' [p]') - b.setText(_('&Previous change')), b.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) + b.setText(_('&Previous change')), b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) l.addWidget(b, r, 0) self.bn = b = QToolButton(self) b.setIcon(QIcon(I('forward.png'))) connect_lambda(b.clicked, self, lambda self: self.view.next_change(1)) b.setToolTip(_('Go to next change') + ' [n]') - b.setText(_('&Next change')), b.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) + b.setText(_('&Next change')), b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) l.addWidget(b, r, 1) self.search = s = HistoryLineEdit2(self) @@ -261,13 +261,13 @@ class Diff(Dialog): b.setIcon(QIcon(I('arrow-down.png'))) connect_lambda(b.clicked, self, lambda self: self.do_search(False)) b.setToolTip(_('Find next match')) - b.setText(_('Next &match')), b.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) + b.setText(_('Next &match')), b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) l.addWidget(b, r, 3) self.sbp = b = QToolButton(self) b.setIcon(QIcon(I('arrow-up.png'))) connect_lambda(b.clicked, self, lambda self: self.do_search(True)) b.setToolTip(_('Find previous match')) - b.setText(_('P&revious match')), b.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) + b.setText(_('P&revious match')), b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) l.addWidget(b, r, 4) self.lb = b = QRadioButton(_('Left panel'), self) b.setToolTip(_('Perform search in the left panel')) @@ -278,7 +278,7 @@ class Diff(Dialog): b.setChecked(True) self.pb = b = QToolButton(self) b.setIcon(QIcon(I('config.png'))) - b.setText(_('&Options')), b.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) + b.setText(_('&Options')), b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) b.setToolTip(_('Change how the differences are displayed')) b.setPopupMode(b.InstantPopup) m = QMenu(b) @@ -306,7 +306,7 @@ class Diff(Dialog): self.bb.button(self.bb.Close).setDefault(True) self.hl.addWidget(self.bb, r) - self.view.setFocus(Qt.OtherFocusReason) + self.view.setFocus(Qt.FocusReason.OtherFocusReason) def break_cycles(self): self.view = None @@ -352,8 +352,8 @@ class Diff(Dialog): self.stacks.setCurrentIndex(0) self.busy.setVisible(True) self.busy.pi.startAnimation() - QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) - QApplication.processEvents(QEventLoop.ExcludeUserInputEvents | QEventLoop.ExcludeSocketNotifiers) + QApplication.setOverrideCursor(QCursor(Qt.CursorShape.WaitCursor)) + QApplication.processEvents(QEventLoop.ProcessEventsFlag.ExcludeUserInputEvents | QEventLoop.ProcessEventsFlag.ExcludeSocketNotifiers) def __exit__(self, *args): self.busy.pi.stopAnimation() @@ -442,19 +442,19 @@ class Diff(Dialog): def keyPressEvent(self, ev): if not self.view.handle_key(ev): - if ev.key() in (Qt.Key_Enter, Qt.Key_Return): + if ev.key() in (Qt.Key.Key_Enter, Qt.Key.Key_Return): return # The enter key is used by the search box, so prevent it closing the dialog - if ev.key() == Qt.Key_Slash: - return self.search.setFocus(Qt.OtherFocusReason) - if ev.matches(QKeySequence.Copy): + if ev.key() == Qt.Key.Key_Slash: + return self.search.setFocus(Qt.FocusReason.OtherFocusReason) + if ev.matches(QKeySequence.StandardKey.Copy): text = self.view.view.left.selected_text + self.view.view.right.selected_text if text: QApplication.clipboard().setText(text) return - if ev.matches(QKeySequence.FindNext): + if ev.matches(QKeySequence.StandardKey.FindNext): self.sbn.click() return - if ev.matches(QKeySequence.FindPrevious): + if ev.matches(QKeySequence.StandardKey.FindPrevious): self.sbp.click() return return Dialog.keyPressEvent(self, ev) diff --git a/src/calibre/gui2/tweak_book/diff/view.py b/src/calibre/gui2/tweak_book/diff/view.py index cceb92860b..b3479ef509 100644 --- a/src/calibre/gui2/tweak_book/diff/view.py +++ b/src/calibre/gui2/tweak_book/diff/view.py @@ -36,7 +36,7 @@ Change = namedtuple('Change', 'ltop lbot rtop rbot kind') class BusyCursor(object): def __enter__(self): - QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) + QApplication.setOverrideCursor(QCursor(Qt.CursorShape.WaitCursor)) def __exit__(self, *args): QApplication.restoreOverrideCursor() @@ -102,9 +102,9 @@ class TextBrowser(PlainTextEdit): # {{{ self.setFrameStyle(0) self.show_open_in_editor = show_open_in_editor self.side_margin = 0 - self.setContextMenuPolicy(Qt.CustomContextMenu) + self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.customContextMenuRequested.connect(self.show_context_menu) - self.setFocusPolicy(Qt.NoFocus) + self.setFocusPolicy(Qt.FocusPolicy.NoFocus) self.right = right self.setReadOnly(True) self.setLineWrapMode(self.WidgetWidth) @@ -128,7 +128,7 @@ class TextBrowser(PlainTextEdit): # {{{ pal.setColor(pal.Highlight, theme_color(theme, 'Visual', 'bg')) pal.setColor(pal.HighlightedText, theme_color(theme, 'Visual', 'fg')) self.setPalette(pal) - self.viewport().setCursor(Qt.ArrowCursor) + self.viewport().setCursor(Qt.CursorShape.ArrowCursor) self.line_number_area = LineNumbers(self) self.blockCountChanged[int].connect(self.update_line_number_area_width) self.updateRequest.connect(self.update_line_number_area) @@ -139,13 +139,13 @@ class TextBrowser(PlainTextEdit): # {{{ self.line_number_map = LineNumberMap() self.search_header_pos = 0 self.changes, self.headers, self.images = [], [], OrderedDict() - self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff), self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) + self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff), self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) self.diff_backgrounds = { 'replace' : theme_color(theme, 'DiffReplace', 'bg'), 'insert' : theme_color(theme, 'DiffInsert', 'bg'), 'delete' : theme_color(theme, 'DiffDelete', 'bg'), 'replacereplace': theme_color(theme, 'DiffReplaceReplace', 'bg'), - 'boundary': QBrush(theme_color(theme, 'Normal', 'fg'), Qt.Dense7Pattern), + 'boundary': QBrush(theme_color(theme, 'Normal', 'fg'), Qt.BrushStyle.Dense7Pattern), } self.diff_foregrounds = { 'replace' : theme_color(theme, 'DiffReplace', 'fg'), @@ -168,7 +168,7 @@ class TextBrowser(PlainTextEdit): # {{{ a = m.addAction i = unicode_type(self.textCursor().selectedText()).rstrip('\0') if i: - a(QIcon(I('edit-copy.png')), _('Copy to clipboard'), self.copy).setShortcut(QKeySequence.Copy) + a(QIcon(I('edit-copy.png')), _('Copy to clipboard'), self.copy).setShortcut(QKeySequence.StandardKey.Copy) if len(self.changes) > 0: a(QIcon(I('arrow-up.png')), _('Previous change'), partial(self.next_change.emit, -1)) @@ -260,7 +260,7 @@ class TextBrowser(PlainTextEdit): # {{{ del self.headers[:] self.images.clear() self.search_header_pos = 0 - self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) + self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded) def update_line_number_area_width(self, block_count=0): self.side_margin = self.line_number_area_width() @@ -294,13 +294,13 @@ class TextBrowser(PlainTextEdit): # {{{ def paint_line_numbers(self, ev): painter = QPainter(self.line_number_area) - painter.fillRect(ev.rect(), self.line_number_palette.color(QPalette.Base)) + painter.fillRect(ev.rect(), self.line_number_palette.color(QPalette.ColorRole.Base)) block = self.firstVisibleBlock() num = block.blockNumber() top = int(self.blockBoundingGeometry(block).translated(self.contentOffset()).top()) bottom = top + int(self.blockBoundingRect(block).height()) - painter.setPen(self.line_number_palette.color(QPalette.Text)) + painter.setPen(self.line_number_palette.color(QPalette.ColorRole.Text)) change_starts = {x[0] for x in self.changes} while block.isValid() and top <= ev.rect().bottom(): @@ -313,16 +313,16 @@ class TextBrowser(PlainTextEdit): # {{{ f = QFont(self.font()) f.setBold(True) painter.setFont(f) - painter.setPen(self.line_number_palette.color(QPalette.BrightText)) + painter.setPen(self.line_number_palette.color(QPalette.ColorRole.BrightText)) if text == '-': painter.drawLine(r.left() + 2, (top + bottom)//2, r.right() - 2, (top + bottom)//2) else: if self.right: painter.drawText(r.left() + 3, top, r.right(), self.fontMetrics().height(), - Qt.AlignLeft, text) + Qt.AlignmentFlag.AlignLeft, text) else: painter.drawText(r.left() + 2, top, r.right() - 5, self.fontMetrics().height(), - Qt.AlignRight, text) + Qt.AlignmentFlag.AlignRight, text) if is_start: painter.restore() block = block.next() @@ -334,7 +334,7 @@ class TextBrowser(PlainTextEdit): # {{{ w = self.viewport().rect().width() painter = QPainter(self.viewport()) painter.setClipRect(event.rect()) - painter.setRenderHint(QPainter.SmoothPixmapTransform, True) + painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform, True) floor = event.rect().bottom() ceiling = event.rect().top() fv = self.firstVisibleBlock().blockNumber() @@ -353,7 +353,7 @@ class TextBrowser(PlainTextEdit): # {{{ if min(y_top, y_bot) > floor: break painter.setFont(self.heading_font) - br = painter.drawText(3, y_top, w, y_bot - y_top - 5, Qt.TextSingleLine, text) + br = painter.drawText(3, y_top, w, y_bot - y_top - 5, Qt.TextFlag.TextSingleLine, text) painter.setPen(QPen(self.palette().text(), 2)) painter.drawLine(0, br.bottom()+3, w, br.bottom()+3) @@ -412,7 +412,7 @@ class DiffSplitHandle(QSplitterHandle): # {{{ painter.setClipRect(event.rect()) w = self.width() h = self.height() - painter.setRenderHints(QPainter.Antialiasing, True) + painter.setRenderHints(QPainter.RenderHint.Antialiasing, True) C = 16 # Curve factor. @@ -460,7 +460,7 @@ class DiffSplitHandle(QSplitterHandle): # {{{ for kind, path, aa in sorted(lines, key=lambda x:{'replace':0}.get(x[0], 1)): painter.setPen(left.diff_foregrounds[kind]) - painter.setRenderHints(QPainter.Antialiasing, aa) + painter.setRenderHints(QPainter.RenderHint.Antialiasing, aa) painter.drawPath(path) painter.setFont(left.heading_font) @@ -476,11 +476,11 @@ class DiffSplitHandle(QSplitterHandle): # {{{ continue if min(ly_top, ly_bot, ry_top, ry_bot) > h: break - ly = painter.boundingRect(3, ly_top, left.width(), ly_bot - ly_top - 5, Qt.TextSingleLine, text).bottom() + 3 - ry = painter.boundingRect(3, ry_top, right.width(), ry_bot - ry_top - 5, Qt.TextSingleLine, text).bottom() + 3 + ly = painter.boundingRect(3, ly_top, left.width(), ly_bot - ly_top - 5, Qt.TextFlag.TextSingleLine, text).bottom() + 3 + ry = painter.boundingRect(3, ry_top, right.width(), ry_bot - ry_top - 5, Qt.TextFlag.TextSingleLine, text).bottom() + 3 line = create_line(ly, ry) painter.setPen(QPen(left.palette().text(), 2)) - painter.setRenderHints(QPainter.Antialiasing, ly != ry) + painter.setRenderHints(QPainter.RenderHint.Antialiasing, ly != ry) painter.drawPath(line) painter.end() @@ -568,20 +568,20 @@ class DiffSplit(QSplitter): # {{{ dpr = self.devicePixelRatioF() except AttributeError: dpr = self.devicePixelRatio() - i = QImage(200, 150, QImage.Format_ARGB32) + i = QImage(200, 150, QImage.Format.Format_ARGB32) i.setDevicePixelRatio(dpr) - i.fill(Qt.white) + i.fill(Qt.GlobalColor.white) p = QPainter(i) r = i.rect().adjusted(10, 10, -10, -10) - n = QPen(Qt.DashLine) - n.setColor(Qt.black) + n = QPen(Qt.PenStyle.DashLine) + n.setColor(Qt.GlobalColor.black) p.setPen(n) p.drawRect(r) - p.setPen(Qt.black) + p.setPen(Qt.GlobalColor.black) f = self.font() f.setPixelSize(20) p.setFont(f) - p.drawText(r.adjusted(10, 0, -10, 0), Qt.AlignCenter | Qt.TextWordWrap, _('Image could not be rendered')) + p.drawText(r.adjusted(10, 0, -10, 0), Qt.AlignmentFlag.AlignCenter | Qt.TextFlag.TextWordWrap, _('Image could not be rendered')) p.end() self._failed_img = QPixmap.fromImage(i) return self._failed_img @@ -602,7 +602,7 @@ class DiffSplit(QSplitter): # {{{ change = [] # Let any initial resizing of the window finish in case this is the # first diff, to avoid the expensive resize calculation later - QApplication.processEvents(QEventLoop.ExcludeUserInputEvents | QEventLoop.ExcludeSocketNotifiers) + QApplication.processEvents(QEventLoop.ProcessEventsFlag.ExcludeUserInputEvents | QEventLoop.ProcessEventsFlag.ExcludeSocketNotifiers) for v, img, size in ((self.left, left_img, len(left_data)), (self.right, right_img, len(right_data))): c = v.textCursor() c.movePosition(c.End) @@ -621,7 +621,7 @@ class DiffSplit(QSplitter): # {{{ change.append('replace' if left_data and right_data else 'delete' if left_data else 'insert') self.left.changes.append((change[0], change[1], change[-1])) self.right.changes.append((change[2], change[3], change[-1])) - QApplication.processEvents(QEventLoop.ExcludeUserInputEvents | QEventLoop.ExcludeSocketNotifiers) + QApplication.processEvents(QEventLoop.ProcessEventsFlag.ExcludeUserInputEvents | QEventLoop.ProcessEventsFlag.ExcludeSocketNotifiers) def resized(self): ' Resize images to fit in new view size and adjust all line number references accordingly ' @@ -699,7 +699,7 @@ class DiffSplit(QSplitter): # {{{ if context is None: for tag, alo, ahi, blo, bhi in cruncher.get_opcodes(): getattr(self, tag)(alo, ahi, blo, bhi) - QApplication.processEvents(QEventLoop.ExcludeUserInputEvents | QEventLoop.ExcludeSocketNotifiers) + QApplication.processEvents(QEventLoop.ProcessEventsFlag.ExcludeUserInputEvents | QEventLoop.ProcessEventsFlag.ExcludeSocketNotifiers) else: def insert_boundary(): self.changes.append(Change( @@ -714,7 +714,7 @@ class DiffSplit(QSplitter): # {{{ if j == 0 and (i > 0 or min(alo, blo) > 0): insert_boundary() getattr(self, tag)(alo, ahi, blo, bhi) - QApplication.processEvents(QEventLoop.ExcludeUserInputEvents | QEventLoop.ExcludeSocketNotifiers) + QApplication.processEvents(QEventLoop.ProcessEventsFlag.ExcludeUserInputEvents | QEventLoop.ProcessEventsFlag.ExcludeSocketNotifiers) cl.insertBlock(), cr.insertBlock() if ahi < len(left_lines) - 1 or bhi < len(right_lines) - 1: insert_boundary() @@ -1075,19 +1075,19 @@ class DiffView(QWidget): # {{{ def handle_key(self, ev): amount, d = None, 1 key = ev.key() - if key in (Qt.Key_Up, Qt.Key_Down, Qt.Key_J, Qt.Key_K): + if key in (Qt.Key.Key_Up, Qt.Key.Key_Down, Qt.Key.Key_J, Qt.Key.Key_K): amount = self.scrollbar.singleStep() - if key in (Qt.Key_Up, Qt.Key_K): + if key in (Qt.Key.Key_Up, Qt.Key.Key_K): d = -1 - elif key in (Qt.Key_PageUp, Qt.Key_PageDown): + elif key in (Qt.Key.Key_PageUp, Qt.Key.Key_PageDown): amount = self.scrollbar.pageStep() - if key in (Qt.Key_PageUp,): + if key in (Qt.Key.Key_PageUp,): d = -1 - elif key in (Qt.Key_Home, Qt.Key_End): - self.scrollbar.setValue(0 if key == Qt.Key_Home else self.scrollbar.maximum()) + elif key in (Qt.Key.Key_Home, Qt.Key.Key_End): + self.scrollbar.setValue(0 if key == Qt.Key.Key_Home else self.scrollbar.maximum()) return True - elif key in (Qt.Key_N, Qt.Key_P): - self.next_change(1 if key == Qt.Key_N else -1) + elif key in (Qt.Key.Key_N, Qt.Key.Key_P): + self.next_change(1 if key == Qt.Key.Key_N else -1) return True if amount is not None: diff --git a/src/calibre/gui2/tweak_book/download.py b/src/calibre/gui2/tweak_book/download.py index 90794c0b5c..1688abb7dd 100644 --- a/src/calibre/gui2/tweak_book/download.py +++ b/src/calibre/gui2/tweak_book/download.py @@ -34,15 +34,15 @@ class ChooseResources(QWidget): def select_none(self): for item in self: - item.setCheckState(Qt.Unchecked) + item.setCheckState(Qt.CheckState.Unchecked) def select_all(self): for item in self: - item.setCheckState(Qt.Checked) + item.setCheckState(Qt.CheckState.Checked) @property def resources(self): - return {i.data(Qt.UserRole):self.original_resources[i.data(Qt.UserRole)] for i in self if i.checkState() == Qt.Checked} + return {i.data(Qt.ItemDataRole.UserRole):self.original_resources[i.data(Qt.ItemDataRole.UserRole)] for i in self if i.checkState() == Qt.CheckState.Checked} @resources.setter def resources(self, resources): @@ -57,9 +57,9 @@ class ChooseResources(QWidget): text = _('Data URL #{}').format(dc) text += ' ({})'.format(ngettext('one instance', '{} instances', num).format(num)) i = QListWidgetItem(text, self.items) - i.setData(Qt.UserRole, url) - i.setCheckState(Qt.Checked) - i.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) + i.setData(Qt.ItemDataRole.UserRole, url) + i.setCheckState(Qt.CheckState.Checked) + i.setFlags(Qt.ItemFlag.ItemIsUserCheckable | Qt.ItemFlag.ItemIsEnabled) class DownloadStatus(QScrollArea): @@ -109,7 +109,7 @@ class DownloadResources(Dialog): self.get_done.connect(self._get_done) self.download_done.connect(self._download_done) self.replace_done.connect(self._replace_done) - self.progress.connect(self.download_status.progress, type=Qt.QueuedConnection) + self.progress.connect(self.download_status.progress, type=Qt.ConnectionType.QueuedConnection) def setup_ui(self): self.setWindowIcon(QIcon(I('download-metadata.png'))) diff --git a/src/calibre/gui2/tweak_book/editor/canvas.py b/src/calibre/gui2/tweak_book/editor/canvas.py index c033e9e41e..da19e5cba2 100644 --- a/src/calibre/gui2/tweak_book/editor/canvas.py +++ b/src/calibre/gui2/tweak_book/editor/canvas.py @@ -117,7 +117,7 @@ class Rotate(Command): img = canvas.current_image m = QTransform() m.rotate(90) - return img.transformed(m, Qt.SmoothTransformation) + return img.transformed(m, Qt.TransformationMode.SmoothTransformation) class Scale(Command): @@ -130,7 +130,7 @@ class Scale(Command): def __call__(self, canvas): img = canvas.current_image - return img.scaled(self.width, self.height, transformMode=Qt.SmoothTransformation) + return img.scaled(self.width, self.height, transformMode=Qt.TransformationMode.SmoothTransformation) class Sharpen(Command): @@ -212,7 +212,7 @@ def imageop(func): return error_dialog(self, _('No image'), _('No image loaded'), show=True) if not self.is_valid: return error_dialog(self, _('Invalid image'), _('The current image is not valid'), show=True) - QApplication.setOverrideCursor(Qt.BusyCursor) + QApplication.setOverrideCursor(Qt.CursorShape.BusyCursor) try: return func(self, *args, **kwargs) finally: @@ -224,7 +224,7 @@ class Canvas(QWidget): BACKGROUND = QColor(60, 60, 60) SHADE_COLOR = QColor(0, 0, 0, 180) - SELECT_PEN = QPen(QColor(Qt.white)) + SELECT_PEN = QPen(QColor(Qt.GlobalColor.white)) selection_state_changed = pyqtSignal(object) undo_redo_state_changed = pyqtSignal(object, object) @@ -246,7 +246,7 @@ class Canvas(QWidget): event.acceptProposedAction() def dropEvent(self, event): - event.setDropAction(Qt.CopyAction) + event.setDropAction(Qt.DropAction.CopyAction) md = event.mimeData() x, y = dnd_get_image(md) @@ -276,7 +276,7 @@ class Canvas(QWidget): QWidget.__init__(self, parent) self.setAcceptDrops(True) self.setMouseTracking(True) - self.setFocusPolicy(Qt.ClickFocus) + self.setFocusPolicy(Qt.FocusPolicy.ClickFocus) self.selection_state = SelectionState() self.undo_stack = u = QUndoStack() u.setUndoLimit(10) @@ -454,11 +454,11 @@ class Canvas(QWidget): def get_cursor(self): dc = self.selection_state.drag_corner if dc is None: - ans = Qt.OpenHandCursor if self.selection_state.last_drag_pos is None else Qt.ClosedHandCursor + ans = Qt.CursorShape.OpenHandCursor if self.selection_state.last_drag_pos is None else Qt.CursorShape.ClosedHandCursor elif None in dc: - ans = Qt.SizeVerCursor if dc[0] is None else Qt.SizeHorCursor + ans = Qt.CursorShape.SizeVerCursor if dc[0] is None else Qt.CursorShape.SizeHorCursor else: - ans = Qt.SizeBDiagCursor if dc in {('left', 'bottom'), ('right', 'top')} else Qt.SizeFDiagCursor + ans = Qt.CursorShape.SizeBDiagCursor if dc in {('left', 'bottom'), ('right', 'top')} else Qt.CursorShape.SizeFDiagCursor return ans def move_edge(self, edge, dp): @@ -499,7 +499,7 @@ class Canvas(QWidget): self.move_edge(edge, dp) def mousePressEvent(self, ev): - if ev.button() == Qt.LeftButton and self.target.contains(ev.pos()): + if ev.button() == Qt.MouseButton.LeftButton and self.target.contains(ev.pos()): pos = ev.pos() self.selection_state.last_press_point = pos if self.selection_state.current_mode is None: @@ -522,11 +522,11 @@ class Canvas(QWidget): self.selection_state.in_selection = False self.selection_state.drag_corner = None pos = ev.pos() - cursor = Qt.ArrowCursor + cursor = Qt.CursorShape.ArrowCursor try: if not self.target.contains(pos): return - if ev.buttons() & Qt.LeftButton: + if ev.buttons() & Qt.MouseButton.LeftButton: if self.selection_state.last_press_point is not None and self.selection_state.current_mode is not None: if self.selection_state.current_mode == 'select': self.selection_state.rect = QRectF(self.selection_state.last_press_point, pos).normalized() @@ -554,7 +554,7 @@ class Canvas(QWidget): self.setCursor(cursor) def mouseReleaseEvent(self, ev): - if ev.button() == Qt.LeftButton: + if ev.button() == Qt.MouseButton.LeftButton: self.selection_state.dragging = self.selection_state.last_drag_pos = None if self.selection_state.current_mode == 'select': r = self.selection_state.rect @@ -569,14 +569,14 @@ class Canvas(QWidget): def keyPressEvent(self, ev): k = ev.key() - if k in (Qt.Key_Left, Qt.Key_Right, Qt.Key_Up, Qt.Key_Down) and self.selection_state.rect is not None and self.has_selection: + if k in (Qt.Key.Key_Left, Qt.Key.Key_Right, Qt.Key.Key_Up, Qt.Key.Key_Down) and self.selection_state.rect is not None and self.has_selection: ev.accept() - delta = 10 if ev.modifiers() & Qt.ShiftModifier else 1 + delta = 10 if ev.modifiers() & Qt.KeyboardModifier.ShiftModifier else 1 x = y = 0 - if k in (Qt.Key_Left, Qt.Key_Right): - x = delta * (-1 if k == Qt.Key_Left else 1) + if k in (Qt.Key.Key_Left, Qt.Key.Key_Right): + x = delta * (-1 if k == Qt.Key.Key_Left else 1) else: - y = delta * (-1 if k == Qt.Key_Up else 1) + y = delta * (-1 if k == Qt.Key.Key_Up else 1) self.move_selection_rect(x, y) self.update() else: @@ -594,8 +594,8 @@ class Canvas(QWidget): font.setPointSize(3 * font.pointSize()) font.setBold(True) painter.setFont(font) - painter.setPen(QColor(Qt.black)) - painter.drawText(self.rect(), Qt.AlignCenter, _('Not a valid image')) + painter.setPen(QColor(Qt.GlobalColor.black)) + painter.drawText(self.rect(), Qt.AlignmentFlag.AlignCenter, _('Not a valid image')) def load_pixmap(self): canvas_size = self.rect().width(), self.rect().height() @@ -615,7 +615,7 @@ class Canvas(QWidget): except AttributeError: dpr = self.devicePixelRatio() if scaled: - i = self.current_image.scaled(int(dpr * width), int(dpr * height), transformMode=Qt.SmoothTransformation) + i = self.current_image.scaled(int(dpr * width), int(dpr * height), transformMode=Qt.TransformationMode.SmoothTransformation) self.current_scaled_pixmap = QPixmap.fromImage(i) self.current_scaled_pixmap.setDevicePixelRatio(dpr) @@ -637,7 +637,7 @@ class Canvas(QWidget): def draw_selection_rect(self, painter): cr, sr = self.target, self.selection_state.rect painter.setPen(self.SELECT_PEN) - painter.setRenderHint(QPainter.Antialiasing, False) + painter.setRenderHint(QPainter.RenderHint.Antialiasing, False) if self.selection_state.current_mode == 'selected': # Shade out areas outside the selection rect for r in ( @@ -652,19 +652,19 @@ class Canvas(QWidget): if self.selection_state.in_selection and dr is not None: # Draw the resize rectangle painter.save() - painter.setCompositionMode(QPainter.RasterOp_SourceAndNotDestination) + painter.setCompositionMode(QPainter.CompositionMode.RasterOp_SourceAndNotDestination) painter.setClipRect(sr.adjusted(1, 1, -1, -1)) painter.drawRect(dr) painter.restore() # Draw the selection rectangle - painter.setCompositionMode(QPainter.RasterOp_SourceAndNotDestination) + painter.setCompositionMode(QPainter.CompositionMode.RasterOp_SourceAndNotDestination) painter.drawRect(sr) def paintEvent(self, event): QWidget.paintEvent(self, event) p = QPainter(self) - p.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform) + p.setRenderHints(QPainter.RenderHint.Antialiasing | QPainter.RenderHint.SmoothPixmapTransform) try: self.draw_background(p) if self.original_image_data is None: diff --git a/src/calibre/gui2/tweak_book/editor/image.py b/src/calibre/gui2/tweak_book/editor/image.py index e5e388e337..d98c51aebe 100644 --- a/src/calibre/gui2/tweak_book/editor/image.py +++ b/src/calibre/gui2/tweak_book/editor/image.py @@ -47,7 +47,7 @@ class ResizeDialog(QDialog): # {{{ l.addRow(ar) self.resize(self.sizeHint()) - 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) @@ -92,7 +92,7 @@ class Editor(QMainWindow): def __init__(self, syntax, parent=None): QMainWindow.__init__(self, parent) if parent is None: - self.setWindowFlags(Qt.Widget) + self.setWindowFlags(Qt.WindowType.Widget) self.is_synced_to_container = False self.syntax = syntax @@ -186,7 +186,7 @@ class Editor(QMainWindow): self.restoreState(state) def set_focus(self): - self.canvas.setFocus(Qt.OtherFocusReason) + self.canvas.setFocus(Qt.FocusReason.OtherFocusReason) def undo(self): self.canvas.undo_action.trigger() @@ -267,7 +267,7 @@ class Editor(QMainWindow): self.action_resize = ac = b.addAction(QIcon(I('resize.png')), _('Resize image'), self.resize_image) b.addSeparator() self.action_filters = ac = b.addAction(QIcon(I('filter.png')), _('Image filters')) - b.widgetForAction(ac).setPopupMode(QToolButton.InstantPopup) + b.widgetForAction(ac).setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup) self.filters_menu = m = QMenu(self) ac.setMenu(m) m.addAction(_('Auto-trim image'), self.canvas.autotrim_image) diff --git a/src/calibre/gui2/tweak_book/editor/insert_resource.py b/src/calibre/gui2/tweak_book/editor/insert_resource.py index d1fc35fd3e..60933ea3ad 100644 --- a/src/calibre/gui2/tweak_book/editor/insert_resource.py +++ b/src/calibre/gui2/tweak_book/editor/insert_resource.py @@ -111,7 +111,7 @@ class ImageDelegate(QStyledItemDelegate): def paint(self, painter, option, index): QStyledItemDelegate.paint(self, painter, option, empty_index) # draw the hover and selection highlights - name = unicode_type(index.data(Qt.DisplayRole) or '') + name = unicode_type(index.data(Qt.ItemDataRole.DisplayRole) or '') cover = self.cover_cache.get(name, None) if cover is None: cover = self.cover_cache[name] = QPixmap() @@ -129,7 +129,7 @@ class ImageDelegate(QStyledItemDelegate): if not cover.isNull(): scaled, width, height = fit_image(cover.width(), cover.height(), self.cover_size.width(), self.cover_size.height()) if scaled: - cover = self.cover_cache[name] = cover.scaled(int(dpr*width), int(dpr*height), transformMode=Qt.SmoothTransformation) + cover = self.cover_cache[name] = cover.scaled(int(dpr*width), int(dpr*height), transformMode=Qt.TransformationMode.SmoothTransformation) painter.save() try: @@ -144,10 +144,10 @@ class ImageDelegate(QStyledItemDelegate): painter.drawPixmap(rect, cover) rect = trect rect.setTop(rect.bottom() - self.title_height + 5) - painter.setRenderHint(QPainter.TextAntialiasing, True) + painter.setRenderHint(QPainter.RenderHint.TextAntialiasing, True) metrics = painter.fontMetrics() - painter.drawText(rect, Qt.AlignCenter|Qt.TextSingleLine, - metrics.elidedText(name, Qt.ElideLeft, rect.width())) + painter.drawText(rect, Qt.AlignmentFlag.AlignCenter|Qt.TextFlag.TextSingleLine, + metrics.elidedText(name, Qt.TextElideMode.ElideLeft, rect.width())) finally: painter.restore() @@ -184,7 +184,7 @@ class Images(QAbstractListModel): name = self.image_names[index.row()] except IndexError: return None - if role in (Qt.DisplayRole, Qt.ToolTipRole): + if role in (Qt.ItemDataRole.DisplayRole, Qt.ItemDataRole.ToolTipRole): return name return None @@ -208,7 +208,7 @@ class InsertImage(Dialog): self.setLayout(l) self.la1 = la = QLabel(_('&Existing images in the book')) - la.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) + la.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) l.addWidget(la, 0, 0, 1, 2) if self.for_browsing: la.setVisible(False) @@ -250,7 +250,7 @@ class InsertImage(Dialog): b.clicked.connect(self.refresh) b.setIcon(QIcon(I('view-refresh.png'))) b.setToolTip(_('Refresh the displayed images')) - self.setAttribute(Qt.WA_DeleteOnClose, False) + self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, False) else: b = self.import_button = self.bb.addButton(_('&Import image'), self.bb.ActionRole) b.clicked.connect(self.import_image) @@ -333,7 +333,7 @@ class InsertImage(Dialog): self.accept() def pressed(self, index): - if QApplication.mouseButtons() & Qt.LeftButton: + if QApplication.mouseButtons() & Qt.MouseButton.LeftButton: self.activated(index) def activated(self, index): @@ -391,7 +391,7 @@ class ChooseFolder(Dialog): # {{{ f.setHeaderHidden(True) f.itemDoubleClicked.connect(self.accept) l.addWidget(f) - f.setContextMenuPolicy(Qt.CustomContextMenu) + f.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) f.customContextMenuRequested.connect(self.show_context_menu) self.root = QTreeWidgetItem(f, ('/',)) @@ -452,7 +452,7 @@ class NewBook(Dialog): # {{{ self.title = t = QLineEdit(self) l.addRow(_('&Title:'), t) - t.setFocus(Qt.OtherFocusReason) + t.setFocus(Qt.FocusReason.OtherFocusReason) self.authors = a = QLineEdit(self) l.addRow(_('&Authors:'), a) diff --git a/src/calibre/gui2/tweak_book/editor/smarts/css.py b/src/calibre/gui2/tweak_book/editor/smarts/css.py index bc1a19be74..6b8099ff67 100644 --- a/src/calibre/gui2/tweak_book/editor/smarts/css.py +++ b/src/calibre/gui2/tweak_book/editor/smarts/css.py @@ -46,7 +46,7 @@ class Smarts(NullSmarts): def handle_key_press(self, ev, editor): key = ev.key() - if key in (Qt.Key_Enter, Qt.Key_Return) and no_modifiers(ev, Qt.ControlModifier, Qt.AltModifier): + if key in (Qt.Key.Key_Enter, Qt.Key.Key_Return) and no_modifiers(ev, Qt.KeyboardModifier.ControlModifier, Qt.KeyboardModifier.AltModifier): ls = get_leading_whitespace_on_block(editor) cursor, text = get_text_before_cursor(editor) if text.rstrip().endswith('{'): @@ -54,7 +54,7 @@ class Smarts(NullSmarts): editor.textCursor().insertText('\n' + ls) return True - if key == Qt.Key_BraceRight: + if key == Qt.Key.Key_BraceRight: ls = get_leading_whitespace_on_block(editor) pls = get_leading_whitespace_on_block(editor, previous=True) cursor, text = get_text_before_cursor(editor) @@ -64,13 +64,13 @@ class Smarts(NullSmarts): editor.setTextCursor(cursor) return True - if key == Qt.Key_Home and smart_home(editor, ev): + if key == Qt.Key.Key_Home and smart_home(editor, ev): return True - if key == Qt.Key_Tab and smart_tab(editor, ev): + if key == Qt.Key.Key_Tab and smart_tab(editor, ev): return True - if key == Qt.Key_Backspace and smart_backspace(editor, ev): + if key == Qt.Key.Key_Backspace and smart_backspace(editor, ev): return True return False diff --git a/src/calibre/gui2/tweak_book/editor/smarts/html.py b/src/calibre/gui2/tweak_book/editor/smarts/html.py index f31b9b0d6a..fad4c1bad1 100644 --- a/src/calibre/gui2/tweak_book/editor/smarts/html.py +++ b/src/calibre/gui2/tweak_book/editor/smarts/html.py @@ -621,12 +621,12 @@ class Smarts(NullSmarts): if tprefs['replace_entities_as_typed'] and ( ';' in ev_text or - (key == Qt.Key_Semicolon and no_modifiers(ev, Qt.ControlModifier, Qt.AltModifier)) + (key == Qt.Key.Key_Semicolon and no_modifiers(ev, Qt.KeyboardModifier.ControlModifier, Qt.KeyboardModifier.AltModifier)) ): self.replace_possible_entity(editor) return True - if key in (Qt.Key_Enter, Qt.Key_Return) and no_modifiers(ev, Qt.ControlModifier, Qt.AltModifier): + if key in (Qt.Key.Key_Enter, Qt.Key.Key_Return) and no_modifiers(ev, Qt.KeyboardModifier.ControlModifier, Qt.KeyboardModifier.AltModifier): ls = get_leading_whitespace_on_block(editor) if ls == ' ': ls = '' # Do not consider a single leading space as indentation @@ -645,7 +645,7 @@ class Smarts(NullSmarts): editor.textCursor().insertText('\n' + ls) return True - if key == Qt.Key_Slash: + if key == Qt.Key.Key_Slash: cursor, text = get_text_before_cursor(editor) if not text.rstrip().endswith('<'): return False @@ -661,21 +661,21 @@ class Smarts(NullSmarts): if self.auto_close_tag(editor): return True - if key == Qt.Key_Home and smart_home(editor, ev): + if key == Qt.Key.Key_Home and smart_home(editor, ev): return True - if key == Qt.Key_Tab and smart_tab(editor, ev): + if key == Qt.Key.Key_Tab and smart_tab(editor, ev): return True - if key == Qt.Key_Backspace and smart_backspace(editor, ev): + if key == Qt.Key.Key_Backspace and smart_backspace(editor, ev): return True - if key in (Qt.Key_BraceLeft, Qt.Key_BraceRight): + if key in (Qt.Key.Key_BraceLeft, Qt.Key.Key_BraceRight): mods = ev.modifiers() - if int(mods & Qt.ControlModifier): - if self.jump_to_enclosing_tag(editor, key == Qt.Key_BraceLeft): + if int(mods & Qt.KeyboardModifier.ControlModifier): + if self.jump_to_enclosing_tag(editor, key == Qt.Key.Key_BraceLeft): return True - if key == Qt.Key_T and int(ev.modifiers() & (Qt.ControlModifier | Qt.AltModifier)): + if key == Qt.Key.Key_T and int(ev.modifiers() & (Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.AltModifier)): return self.select_tag_contents(editor) return False diff --git a/src/calibre/gui2/tweak_book/editor/smarts/python.py b/src/calibre/gui2/tweak_book/editor/smarts/python.py index 2c46a4c677..62c7288fd8 100644 --- a/src/calibre/gui2/tweak_book/editor/smarts/python.py +++ b/src/calibre/gui2/tweak_book/editor/smarts/python.py @@ -36,13 +36,13 @@ class Smarts(NullSmarts): def handle_key_press(self, ev, editor): key = ev.key() - if key == Qt.Key_Tab and smart_tab(editor, ev): + if key == Qt.Key.Key_Tab and smart_tab(editor, ev): return True - elif key == Qt.Key_Backspace and smart_backspace(editor, ev): + elif key == Qt.Key.Key_Backspace and smart_backspace(editor, ev): return True - elif key in (Qt.Key_Enter, Qt.Key_Return): + elif key in (Qt.Key.Key_Enter, Qt.Key.Key_Return): ls = get_leading_whitespace_on_block(editor) cursor = editor.textCursor() line = cursor.block().text() @@ -54,7 +54,7 @@ class Smarts(NullSmarts): editor.setTextCursor(cursor) return True - elif key == Qt.Key_Colon: + elif key == Qt.Key.Key_Colon: cursor, text = get_text_before_cursor(editor) if self.dedent_pat.search(text) is not None: ls = get_leading_whitespace_on_block(editor) @@ -66,7 +66,7 @@ class Smarts(NullSmarts): editor.setTextCursor(cursor) return True - if key == Qt.Key_Home and smart_home(editor, ev): + if key == Qt.Key.Key_Home and smart_home(editor, ev): return True diff --git a/src/calibre/gui2/tweak_book/editor/smarts/utils.py b/src/calibre/gui2/tweak_book/editor/smarts/utils.py index 633995c989..101e0941e2 100644 --- a/src/calibre/gui2/tweak_book/editor/smarts/utils.py +++ b/src/calibre/gui2/tweak_book/editor/smarts/utils.py @@ -57,10 +57,10 @@ def test_modifiers(ev, *args): def smart_home(editor, ev): - if no_modifiers(ev, Qt.ControlModifier) and not is_cursor_on_wrapped_line(editor): + if no_modifiers(ev, Qt.KeyboardModifier.ControlModifier) and not is_cursor_on_wrapped_line(editor): cursor, text = get_text_before_cursor(editor) cursor = editor.textCursor() - mode = cursor.KeepAnchor if test_modifiers(ev, Qt.ShiftModifier) else cursor.MoveAnchor + mode = cursor.KeepAnchor if test_modifiers(ev, Qt.KeyboardModifier.ShiftModifier) else cursor.MoveAnchor cursor.movePosition(cursor.StartOfBlock, mode) if text.strip() and text.lstrip() != text: # Move to the start of text diff --git a/src/calibre/gui2/tweak_book/editor/snippets.py b/src/calibre/gui2/tweak_book/editor/snippets.py index 3d6b3c6e7b..ccdc4864e6 100644 --- a/src/calibre/gui2/tweak_book/editor/snippets.py +++ b/src/calibre/gui2/tweak_book/editor/snippets.py @@ -26,8 +26,8 @@ from calibre.utils.localization import localize_user_manual_link from polyglot.builtins import codepoint_to_chr, iteritems, itervalues, unicode_type, range string_length = lambda x: strlen(unicode_type(x)) # Needed on narrow python builds, as subclasses of unicode dont work -KEY = Qt.Key_J -MODIFIER = Qt.META if ismacos else Qt.CTRL +KEY = Qt.Key.Key_J +MODIFIER = Qt.Modifier.META if ismacos else Qt.Modifier.CTRL SnipKey = namedtuple('SnipKey', 'trigger syntaxes') @@ -463,7 +463,7 @@ class EditSnippet(QWidget): l.addWidget(args[0], r, 0, 1, 2) else: la = QLabel(args[0]) - l.addWidget(la, r, 0, Qt.AlignRight), l.addWidget(args[1], r, 1) + l.addWidget(la, r, 0, Qt.AlignmentFlag.AlignRight), l.addWidget(args[1], r, 1) la.setBuddy(args[1]) self.heading = la = QLabel('

\xa0') @@ -503,14 +503,14 @@ class EditSnippet(QWidget): add_row(_('T&est:'), d) i = QListWidgetItem(_('All'), t) - i.setData(Qt.UserRole, '*') - i.setCheckState(Qt.Checked) - i.setFlags(i.flags() | Qt.ItemIsUserCheckable) + i.setData(Qt.ItemDataRole.UserRole, '*') + i.setCheckState(Qt.CheckState.Checked) + i.setFlags(i.flags() | Qt.ItemFlag.ItemIsUserCheckable) for ftype in sorted(all_text_syntaxes): i = QListWidgetItem(ftype, t) - i.setData(Qt.UserRole, ftype) - i.setCheckState(Qt.Checked) - i.setFlags(i.flags() | Qt.ItemIsUserCheckable) + i.setData(Qt.ItemDataRole.UserRole, ftype) + i.setCheckState(Qt.CheckState.Checked) + i.setFlags(i.flags() | Qt.ItemFlag.ItemIsUserCheckable) self.creating_snippet = False @@ -529,19 +529,19 @@ class EditSnippet(QWidget): ftypes = snip.get('syntaxes', ()) for i in range(self.types.count()): i = self.types.item(i) - ftype = i.data(Qt.UserRole) - i.setCheckState(Qt.Checked if ftype in ftypes else Qt.Unchecked) + ftype = i.data(Qt.ItemDataRole.UserRole) + i.setCheckState(Qt.CheckState.Checked if ftype in ftypes else Qt.CheckState.Unchecked) if self.creating_snippet and not ftypes: - self.types.item(0).setCheckState(Qt.Checked) - (self.name if self.creating_snippet else self.template).setFocus(Qt.OtherFocusReason) + self.types.item(0).setCheckState(Qt.CheckState.Checked) + (self.name if self.creating_snippet else self.template).setFocus(Qt.FocusReason.OtherFocusReason) @property def snip(self): ftypes = [] for i in range(self.types.count()): i = self.types.item(i) - if i.checkState() == Qt.Checked: - ftypes.append(i.data(Qt.UserRole)) + if i.checkState() == Qt.CheckState.Checked: + ftypes.append(i.data(Qt.ItemDataRole.UserRole)) return {'description':self.name.text().strip(), 'trigger':self.trig.text(), 'template':self.template.toPlainText(), 'syntaxes':ftypes} @snip.setter @@ -595,22 +595,22 @@ class UserSnippets(Dialog): c.l2 = l = QVBoxLayout() h.addLayout(l) self.add_button = b = QToolButton(self) - b.setIcon(QIcon(I('plus.png'))), b.setText(_('&Add snippet')), b.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) + b.setIcon(QIcon(I('plus.png'))), b.setText(_('&Add snippet')), b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextUnderIcon) b.clicked.connect(self.add_snippet) l.addWidget(b) self.edit_button = b = QToolButton(self) - b.setIcon(QIcon(I('modified.png'))), b.setText(_('&Edit snippet')), b.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) + b.setIcon(QIcon(I('modified.png'))), b.setText(_('&Edit snippet')), b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextUnderIcon) b.clicked.connect(self.edit_snippet) l.addWidget(b) self.add_button = b = QToolButton(self) - b.setIcon(QIcon(I('minus.png'))), b.setText(_('&Remove snippet')), b.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) + b.setIcon(QIcon(I('minus.png'))), b.setText(_('&Remove snippet')), b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextUnderIcon) b.clicked.connect(self.remove_snippet) l.addWidget(b) self.add_button = b = QToolButton(self) - b.setIcon(QIcon(I('config.png'))), b.setText(_('Change &built-in')), b.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) + b.setIcon(QIcon(I('config.png'))), b.setText(_('Change &built-in')), b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextUnderIcon) b.clicked.connect(self.change_builtin) l.addWidget(b) @@ -627,7 +627,7 @@ class UserSnippets(Dialog): def snip_to_item(self, snip): i = QListWidgetItem(self.snip_to_text(snip), self.snip_list) - i.setData(Qt.UserRole, copy.deepcopy(snip)) + i.setData(Qt.ItemDataRole.UserRole, copy.deepcopy(snip)) return i def reject(self): @@ -647,13 +647,13 @@ class UserSnippets(Dialog): item = self.snip_list.currentItem() snip = self.edit_snip.snip item.setText(self.snip_to_text(snip)) - item.setData(Qt.UserRole, snip) + item.setData(Qt.ItemDataRole.UserRole, snip) self.snip_list.setCurrentItem(item) self.snip_list.scrollToItem(item) else: error_dialog(self, _('Invalid snippet'), err, show=True) return - user_snippets['snippets'] = [self.snip_list.item(i).data(Qt.UserRole) for i in range(self.snip_list.count())] + user_snippets['snippets'] = [self.snip_list.item(i).data(Qt.ItemDataRole.UserRole) for i in range(self.snip_list.count())] snippets(refresh=True) return Dialog.accept(self) @@ -665,7 +665,7 @@ class UserSnippets(Dialog): if item is None: return error_dialog(self, _('Cannot edit snippet'), _('No snippet selected'), show=True) self.stack.setCurrentIndex(1) - self.edit_snip.snip = item.data(Qt.UserRole) + self.edit_snip.snip = item.data(Qt.ItemDataRole.UserRole) def add_snippet(self, *args): self.stack.setCurrentIndex(1) @@ -680,7 +680,7 @@ class UserSnippets(Dialog): q = self.search_bar.text().strip() if not q: return - matches = self.snip_list.findItems(q, Qt.MatchContains | Qt.MatchWrap) + matches = self.snip_list.findItems(q, Qt.MatchFlag.MatchContains | Qt.MatchFlag.MatchWrap) if len(matches) < 1: return error_dialog(self, _('No snippets found'), _( 'No snippets found for query: %s') % q, show=True) @@ -699,17 +699,17 @@ class UserSnippets(Dialog): snip = copy.deepcopy(snip) snip['trigger'], snip['syntaxes'] = trigger, syntaxes i = QListWidgetItem(self.snip_to_text(snip), lw) - i.setData(Qt.UserRole, snip) + i.setData(Qt.ItemDataRole.UserRole, snip) d.l = l = QVBoxLayout(d) l.addWidget(QLabel(_('Choose the built-in snippet to modify:'))) l.addWidget(lw) lw.itemDoubleClicked.connect(d.accept) - d.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) + d.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) l.addWidget(bb) bb.accepted.connect(d.accept), bb.rejected.connect(d.reject) if d.exec_() == d.Accepted and lw.currentItem() is not None: self.stack.setCurrentIndex(1) - self.edit_snip.apply_snip(lw.currentItem().data(Qt.UserRole), creating_snippet=True) + self.edit_snip.apply_snip(lw.currentItem().data(Qt.ItemDataRole.UserRole), creating_snippet=True) # }}} diff --git a/src/calibre/gui2/tweak_book/editor/syntax/html.py b/src/calibre/gui2/tweak_book/editor/syntax/html.py index 9c7585025c..866a22635e 100644 --- a/src/calibre/gui2/tweak_book/editor/syntax/html.py +++ b/src/calibre/gui2/tweak_book/editor/syntax/html.py @@ -218,7 +218,7 @@ def process_text(state, text, nbsp_format, spell_format, user_data): if state.is_bold or state.is_italic: fmt = syntax_text_char_format() if state.is_bold: - fmt.setFontWeight(QFont.Bold) + fmt.setFontWeight(QFont.Weight.Bold) if state.is_italic: fmt.setFontItalic(True) last = 0 @@ -478,7 +478,7 @@ def create_formats(highlighter, add_css=True): f = formats[name] = syntax_text_char_format(formats['error']) f.setToolTip(msg) f = formats['title'] = syntax_text_char_format() - f.setFontWeight(QFont.Bold) + f.setFontWeight(QFont.Weight.Bold) if add_css: formats['css_sub_formats'] = create_css_formats(highlighter) formats['spell'].setProperty(SPELL_PROPERTY, True) diff --git a/src/calibre/gui2/tweak_book/editor/text.py b/src/calibre/gui2/tweak_book/editor/text.py index c30b55fd3c..71f5b3c016 100644 --- a/src/calibre/gui2/tweak_book/editor/text.py +++ b/src/calibre/gui2/tweak_book/editor/text.py @@ -222,7 +222,7 @@ class TextEdit(PlainTextEdit): def apply_settings(self, prefs=None, dictionaries_changed=False): # {{{ prefs = prefs or tprefs self.setAcceptDrops(prefs.get('editor_accepts_drops', True)) - self.setLineWrapMode(QPlainTextEdit.WidgetWidth if prefs['editor_line_wrap'] else QPlainTextEdit.NoWrap) + self.setLineWrapMode(QPlainTextEdit.LineWrapMode.WidgetWidth if prefs['editor_line_wrap'] else QPlainTextEdit.LineWrapMode.NoWrap) theme = get_theme(prefs['editor_theme']) self.apply_theme(theme) w = self.fontMetrics() @@ -621,7 +621,7 @@ class TextEdit(PlainTextEdit): def highlight_cursor_line(self): sel = QTextEdit.ExtraSelection() sel.format.setBackground(self.palette().alternateBase()) - sel.format.setProperty(QTextFormat.FullWidthSelection, True) + sel.format.setProperty(QTextFormat.Property.FullWidthSelection, True) sel.cursor = self.textCursor() sel.cursor.clearSelection() self.current_cursor_line = sel @@ -664,26 +664,26 @@ class TextEdit(PlainTextEdit): def paint_line_numbers(self, ev): painter = QPainter(self.line_number_area) - painter.fillRect(ev.rect(), self.line_number_palette.color(QPalette.Base)) + painter.fillRect(ev.rect(), self.line_number_palette.color(QPalette.ColorRole.Base)) block = self.firstVisibleBlock() num = block.blockNumber() top = int(self.blockBoundingGeometry(block).translated(self.contentOffset()).top()) bottom = top + int(self.blockBoundingRect(block).height()) current = self.textCursor().block().blockNumber() - painter.setPen(self.line_number_palette.color(QPalette.Text)) + painter.setPen(self.line_number_palette.color(QPalette.ColorRole.Text)) while block.isValid() and top <= ev.rect().bottom(): if block.isVisible() and bottom >= ev.rect().top(): if current == num: painter.save() - painter.setPen(self.line_number_palette.color(QPalette.BrightText)) + painter.setPen(self.line_number_palette.color(QPalette.ColorRole.BrightText)) f = QFont(self.font()) f.setBold(True) painter.setFont(f) self.last_current_lnum = (top, bottom - top) painter.drawText(0, top, self.line_number_area.width() - 5, self.fontMetrics().height(), - Qt.AlignRight, unicode_type(num + 1)) + Qt.AlignmentFlag.AlignRight, unicode_type(num + 1)) if current == num: painter.restore() block = block.next() @@ -697,12 +697,12 @@ class TextEdit(PlainTextEdit): # problem as well, since they use the overridden createMimeDataFromSelection() method # instead of the one from Qt (which makes copy() work), and allows proper customization # of the shortcuts - if ev in (QKeySequence.Copy, QKeySequence.Cut, QKeySequence.Paste, QKeySequence.Undo, QKeySequence.Redo): + if ev in (QKeySequence.StandardKey.Copy, QKeySequence.StandardKey.Cut, QKeySequence.StandardKey.Paste, QKeySequence.StandardKey.Undo, QKeySequence.StandardKey.Redo): ev.ignore() return True # This is used to convert typed hex codes into unicode # characters - if ev.key() == Qt.Key_X and ev.modifiers() == Qt.AltModifier: + if ev.key() == Qt.Key.Key_X and ev.modifiers() == Qt.KeyboardModifier.AltModifier: ev.accept() return True return PlainTextEdit.override_shortcut(self, ev) @@ -767,7 +767,7 @@ class TextEdit(PlainTextEdit): # For some reason using eventFilter for this does not work, so we # implement it here self.completion_popup.abort() - if ev.modifiers() & Qt.CTRL: + if ev.modifiers() & Qt.Modifier.CTRL: url = self.link_for_position(ev.pos()) if url is not None: ev.accept() @@ -803,7 +803,7 @@ class TextEdit(PlainTextEdit): return self.smarts.set_text_alignment(self, formatting.partition('_')[-1]) color = 'currentColor' if formatting in {'color', 'background-color'}: - color = QColorDialog.getColor(QColor(Qt.black if formatting == 'color' else Qt.white), self, _('Choose color'), QColorDialog.ShowAlphaChannel) + color = QColorDialog.getColor(QColor(Qt.GlobalColor.black if formatting == 'color' else Qt.GlobalColor.white), self, _('Choose color'), QColorDialog.ColorDialogOption.ShowAlphaChannel) if not color.isValid(): return r, g, b, a = color.getRgb() @@ -881,11 +881,11 @@ version="1.1" width="100%%" height="100%%" viewBox="0 0 {w} {h}" preserveAspectR self.smarts.remove_tag(self) def keyPressEvent(self, ev): - if ev.key() == Qt.Key_X and ev.modifiers() == Qt.AltModifier: + if ev.key() == Qt.Key.Key_X and ev.modifiers() == Qt.KeyboardModifier.AltModifier: if self.replace_possible_unicode_sequence(): ev.accept() return - if ev.key() == Qt.Key_Insert: + if ev.key() == Qt.Key.Key_Insert: self.setOverwriteMode(self.overwriteMode() ^ True) ev.accept() return @@ -903,9 +903,9 @@ version="1.1" width="100%%" height="100%%" viewBox="0 0 {w} {h}" preserveAspectR return code = ev.key() if 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, Qt.Key_Up, Qt.Key_Down): + 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, Qt.Key.Key_Up, Qt.Key.Key_Down): # We ignore up/down arrow so as to not break scrolling through the # text with the arrow keys return diff --git a/src/calibre/gui2/tweak_book/editor/themes.py b/src/calibre/gui2/tweak_book/editor/themes.py index 37da479b1a..8c2db4392d 100644 --- a/src/calibre/gui2/tweak_book/editor/themes.py +++ b/src/calibre/gui2/tweak_book/editor/themes.py @@ -27,7 +27,7 @@ _default_theme = None def default_theme(): global _default_theme if _default_theme is None: - isdark = QApplication.instance().palette().color(QPalette.WindowText).lightness() > 128 + isdark = QApplication.instance().palette().color(QPalette.ColorRole.WindowText).lightness() > 128 _default_theme = 'wombat-dark' if isdark else 'pyte-light' return _default_theme @@ -279,7 +279,7 @@ def get_theme(name): def highlight_to_char_format(h): ans = syntax_text_char_format() if h.bold: - ans.setFontWeight(QFont.Bold) + ans.setFontWeight(QFont.Weight.Bold) if h.italic: ans.setFontItalic(True) if h.fg is not None: @@ -375,7 +375,7 @@ class ColorButton(QPushButton): self.current_color = read_color(color).color() self.ic.fill(self.current_color) else: - self.ic.fill(Qt.transparent) + self.ic.fill(Qt.GlobalColor.transparent) self.current_color = color self.update_tooltip() self.setIcon(QIcon(self.ic)) @@ -384,13 +384,13 @@ class ColorButton(QPushButton): def clear(self): self.current_color = None self.update_tooltip() - self.ic.fill(Qt.transparent) + self.ic.fill(Qt.GlobalColor.transparent) self.setIcon(QIcon(self.ic)) self.data[self.name] = self.value self.changed.emit() def choose_color(self): - col = QColorDialog.getColor(self.current_color or Qt.black, self, _('Choose color')) + col = QColorDialog.getColor(self.current_color or Qt.GlobalColor.black, self, _('Choose color')) if col.isValid(): self.current_color = col self.update_tooltip() @@ -425,7 +425,7 @@ class Bool(QCheckBox): @property def value(self): - return self.checkState() == Qt.Checked + return self.checkState() == Qt.CheckState.Checked class Property(QWidget): diff --git a/src/calibre/gui2/tweak_book/editor/widget.py b/src/calibre/gui2/tweak_book/editor/widget.py index b0dadebec0..b7b06f07b9 100644 --- a/src/calibre/gui2/tweak_book/editor/widget.py +++ b/src/calibre/gui2/tweak_book/editor/widget.py @@ -37,8 +37,8 @@ def create_icon(text, palette=None, sz=None, divider=2, fill='white'): sz = sz or int(math.ceil(tprefs['toolbar_icon_size'] * QApplication.instance().devicePixelRatio())) if palette is None: palette = QApplication.palette() - img = QImage(sz, sz, QImage.Format_ARGB32) - img.fill(Qt.transparent) + img = QImage(sz, sz, QImage.Format.Format_ARGB32) + img.fill(Qt.GlobalColor.transparent) p = QPainter(img) p.setRenderHints(p.TextAntialiasing | p.Antialiasing) if fill is not None: @@ -46,7 +46,7 @@ def create_icon(text, palette=None, sz=None, divider=2, fill='white'): f = p.font() f.setFamily('Liberation Sans'), f.setPixelSize(int(sz // divider)), f.setBold(True) p.setFont(f), p.setPen(QColor('#2271d5')) - p.drawText(img.rect().adjusted(2, 2, -2, -2), Qt.AlignCenter, text) + p.drawText(img.rect().adjusted(2, 2, -2, -2), Qt.AlignmentFlag.AlignCenter, text) p.end() return QIcon(QPixmap.fromImage(img)) @@ -143,11 +143,11 @@ class Editor(QMainWindow): def __init__(self, syntax, parent=None): QMainWindow.__init__(self, parent) if parent is None: - self.setWindowFlags(Qt.Widget) + self.setWindowFlags(Qt.WindowType.Widget) self.is_synced_to_container = False self.syntax = syntax self.editor = TextEdit(self) - self.editor.setContextMenuPolicy(Qt.CustomContextMenu) + self.editor.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.editor.customContextMenuRequested.connect(self.show_context_menu) self.setCentralWidget(self.editor) self.create_toolbars() @@ -230,7 +230,7 @@ class Editor(QMainWindow): self.editor.apply_settings(prefs=None, dictionaries_changed=dictionaries_changed) def set_focus(self): - self.editor.setFocus(Qt.OtherFocusReason) + self.editor.setFocus(Qt.FocusReason.OtherFocusReason) def action_triggered(self, action): action, args = action[0], action[1:] @@ -396,9 +396,9 @@ class Editor(QMainWindow): if hasattr(w, 'setPopupMode'): # For some unknown reason this button is occassionally a # QPushButton instead of a QToolButton - w.setPopupMode(QToolButton.MenuButtonPopup) + w.setPopupMode(QToolButton.ToolButtonPopupMode.MenuButtonPopup) w.setMenu(self.insert_tag_menu) - w.setContextMenuPolicy(Qt.CustomContextMenu) + w.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) w.customContextMenuRequested.connect(w.showMenu) self._build_insert_tag_button_menu() elif name == 'change-paragraph': @@ -408,7 +408,7 @@ class Editor(QMainWindow): if hasattr(ch, 'setPopupMode'): # For some unknown reason this button is occassionally a # QPushButton instead of a QToolButton - ch.setPopupMode(QToolButton.InstantPopup) + ch.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup) for name in tuple('h%d' % d for d in range(1, 7)) + ('p',): m.addAction(actions['rename-block-tag-%s' % name]) diff --git a/src/calibre/gui2/tweak_book/file_list.py b/src/calibre/gui2/tweak_book/file_list.py index 4f4de66b69..5bfd630ee3 100644 --- a/src/calibre/gui2/tweak_book/file_list.py +++ b/src/calibre/gui2/tweak_book/file_list.py @@ -50,7 +50,7 @@ except ImportError: FILE_COPY_MIME = 'application/calibre-edit-book-files' TOP_ICON_SIZE = 24 -NAME_ROLE = Qt.UserRole +NAME_ROLE = Qt.ItemDataRole.UserRole CATEGORY_ROLE = NAME_ROLE + 1 LINEAR_ROLE = CATEGORY_ROLE + 1 MIME_ROLE = LINEAR_ROLE + 1 @@ -106,7 +106,7 @@ def get_bulk_rename_settings(parent, number, msg=None, sanitize=sanitize_file_na d.spine_order.setToolTip(textwrap.fill(_( 'Rename the selected files according to the order they appear in the book, instead of the order they were selected in.'))) l.addRow(d.spine_order) - d.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) + d.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) bb.accepted.connect(d.accept), bb.rejected.connect(d.reject) l.addRow(bb) ans = {'prefix': None, 'start': None} @@ -165,7 +165,7 @@ class ItemDelegate(QStyledItemDelegate): # {{{ def paint(self, painter, option, index): top_level = not index.parent().isValid() - hover = option.state & QStyle.State_MouseOver + hover = option.state & QStyle.StateFlag.State_MouseOver if hover: if top_level: suffix = '%s(%d)' % (NBSP, index.model().rowCount(index)) @@ -174,7 +174,7 @@ class ItemDelegate(QStyledItemDelegate): # {{{ suffix = NBSP + human_readable(current_container().filesize(unicode_type(index.data(NAME_ROLE) or ''))) except EnvironmentError: suffix = NBSP + human_readable(0) - br = painter.boundingRect(option.rect, Qt.AlignRight|Qt.AlignVCenter, suffix) + br = painter.boundingRect(option.rect, Qt.AlignmentFlag.AlignRight|Qt.AlignmentFlag.AlignVCenter, suffix) if top_level and index.row() > 0: option.rect.adjust(0, 5, 0, 0) painter.drawLine(option.rect.topLeft(), option.rect.topRight()) @@ -184,7 +184,7 @@ class ItemDelegate(QStyledItemDelegate): # {{{ QStyledItemDelegate.paint(self, painter, option, index) if hover: option.rect.adjust(0, 0, br.width(), 0) - painter.drawText(option.rect, Qt.AlignRight|Qt.AlignVCenter, suffix) + painter.drawText(option.rect, Qt.AlignmentFlag.AlignRight|Qt.AlignmentFlag.AlignVCenter, suffix) # }}} @@ -246,7 +246,7 @@ class FileList(QTreeWidget, OpenWithHandler): self.current_edited_name = None self.delegate = ItemDelegate(self) self.delegate.rename_requested.connect(self.rename_requested) - self.setTextElideMode(Qt.ElideMiddle) + self.setTextElideMode(Qt.TextElideMode.ElideMiddle) self.setItemDelegate(self.delegate) self.setIconSize(QSize(16, 16)) self.header().close() @@ -258,11 +258,11 @@ class FileList(QTreeWidget, OpenWithHandler): self.setDragDropMode(self.InternalMove) self.setAutoScroll(True) self.setAutoScrollMargin(TOP_ICON_SIZE*2) - self.setDefaultDropAction(Qt.MoveAction) + self.setDefaultDropAction(Qt.DropAction.MoveAction) self.setAutoExpandDelay(1000) self.setAnimated(True) self.setMouseTracking(True) - self.setContextMenuPolicy(Qt.CustomContextMenu) + self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.customContextMenuRequested.connect(self.show_context_menu) self.root = self.invisibleRootItem() self.emblem_cache = {} @@ -346,7 +346,7 @@ class FileList(QTreeWidget, OpenWithHandler): if self.current_edited_name is not None: ci = self.item_from_name(self.current_edited_name) if ci is not None: - ci.setData(0, Qt.FontRole, None) + ci.setData(0, Qt.ItemDataRole.FontRole, None) self.current_edited_name = name self.mark_item_as_current(current) @@ -354,13 +354,13 @@ class FileList(QTreeWidget, OpenWithHandler): font = QFont(self.font()) font.setItalic(True) font.setBold(True) - item.setData(0, Qt.FontRole, font) + item.setData(0, Qt.ItemDataRole.FontRole, font) def clear_currently_edited_name(self): if self.current_edited_name: ci = self.item_from_name(self.current_edited_name) if ci is not None: - ci.setData(0, Qt.FontRole, None) + ci.setData(0, Qt.ItemDataRole.FontRole, None) self.current_edited_name = None def build(self, container, preserve_state=True): @@ -370,19 +370,19 @@ class FileList(QTreeWidget, OpenWithHandler): state = self.get_state() self.clear() self.root = self.invisibleRootItem() - self.root.setFlags(Qt.ItemIsDragEnabled) + self.root.setFlags(Qt.ItemFlag.ItemIsDragEnabled) self.categories = {} for category, text, __ in CATEGORIES: self.categories[category] = i = QTreeWidgetItem(self.root, 0) i.setText(0, text) - i.setData(0, Qt.DecorationRole, self.top_level_pixmap_cache[category]) + i.setData(0, Qt.ItemDataRole.DecorationRole, self.top_level_pixmap_cache[category]) f = i.font(0) f.setBold(True) i.setFont(0, f) i.setData(0, NAME_ROLE, category) - flags = Qt.ItemIsEnabled + flags = Qt.ItemFlag.ItemIsEnabled if category == 'text': - flags |= Qt.ItemIsDropEnabled + flags |= Qt.ItemFlag.ItemIsDropEnabled i.setFlags(flags) processed, seen = {}, {} @@ -448,13 +448,13 @@ class FileList(QTreeWidget, OpenWithHandler): else: canvas = QPixmap((num * w) + ((num-1)*2), h) canvas.setDevicePixelRatio(pixmaps[0].devicePixelRatio()) - canvas.fill(Qt.transparent) + canvas.fill(Qt.GlobalColor.transparent) painter = QPainter(canvas) for i, pm in enumerate(pixmaps): painter.drawPixmap(int(i * (w + 2)/canvas.devicePixelRatio()), 0, pm) painter.end() icon = self.rendered_emblem_cache[emblems] = canvas - item.setData(0, Qt.DecorationRole, icon) + item.setData(0, Qt.ItemDataRole.DecorationRole, icon) cannot_be_renamed = container.names_that_must_not_be_changed ncx_mime = guess_type('a.ncx') @@ -465,11 +465,11 @@ class FileList(QTreeWidget, OpenWithHandler): icat = get_category(name, imt) category = 'text' if linear is not None else ({'text':'misc'}.get(icat, icat)) item = QTreeWidgetItem(self.categories['text' if linear is not None else category], 1) - flags = Qt.ItemIsEnabled | Qt.ItemIsSelectable + flags = Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable if category == 'text': - flags |= Qt.ItemIsDragEnabled + flags |= Qt.ItemFlag.ItemIsDragEnabled if name not in cannot_be_renamed: - flags |= Qt.ItemIsEditable + flags |= Qt.ItemFlag.ItemIsEditable item.setFlags(flags) item.setStatusTip(0, _('Full path: ') + name) item.setData(0, NAME_ROLE, name) @@ -512,7 +512,7 @@ class FileList(QTreeWidget, OpenWithHandler): render_emblems(item, emblems) if tooltips: - item.setData(0, Qt.ToolTipRole, '\n'.join(tooltips)) + item.setData(0, Qt.ItemDataRole.ToolTipRole, '\n'.join(tooltips)) return item for name, linear in container.spine_names: @@ -526,7 +526,7 @@ class FileList(QTreeWidget, OpenWithHandler): for name, c in iteritems(self.categories): c.setExpanded(True) if name != 'text': - c.sortChildren(1, Qt.AscendingOrder) + c.sortChildren(1, Qt.SortOrder.AscendingOrder) if preserve_state: self.set_state(state) @@ -666,7 +666,7 @@ class FileList(QTreeWidget, OpenWithHandler): self.mark_requested.emit(name, 'titlepage:%r' % move_to_start) def keyPressEvent(self, ev): - if ev.key() in (Qt.Key_Delete, Qt.Key_Backspace): + if ev.key() in (Qt.Key.Key_Delete, Qt.Key.Key_Backspace): ev.accept() self.request_delete() else: @@ -930,21 +930,21 @@ class FileList(QTreeWidget, OpenWithHandler): s.setDropIndicatorShown(True) s.setDragDropMode(self.InternalMove) s.setAutoScroll(True) - s.setDefaultDropAction(Qt.MoveAction) + s.setDefaultDropAction(Qt.DropAction.MoveAction) for name in sheets: i = QListWidgetItem(name, s) - flags = Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsDragEnabled | Qt.ItemIsSelectable + flags = Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsUserCheckable | Qt.ItemFlag.ItemIsDragEnabled | Qt.ItemFlag.ItemIsSelectable i.setFlags(flags) - i.setCheckState(Qt.Checked) + i.setCheckState(Qt.CheckState.Checked) d.r = r = QCheckBox(_('Remove existing links to stylesheets')) r.setChecked(tprefs['remove_existing_links_when_linking_sheets']) l.addWidget(r) - d.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) + d.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) bb.accepted.connect(d.accept), bb.rejected.connect(d.reject) l.addWidget(bb) if d.exec_() == d.Accepted: tprefs['remove_existing_links_when_linking_sheets'] = r.isChecked() - sheets = [unicode_type(s.item(il).text()) for il in range(s.count()) if s.item(il).checkState() == Qt.Checked] + sheets = [unicode_type(s.item(il).text()) for il in range(s.count()) if s.item(il).checkState() == Qt.CheckState.Checked] if sheets: self.link_stylesheets_requested.emit(names, sheets, r.isChecked()) @@ -970,7 +970,7 @@ class NewFileDialog(QDialog): # {{{ self.err_label = la = QLabel('') la.setWordWrap(True) l.addWidget(la) - 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) @@ -1053,7 +1053,7 @@ class MergeDialog(QDialog): # {{{ l.addWidget(la) self.sa = sa = QScrollArea(self) l.addWidget(sa) - 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) diff --git a/src/calibre/gui2/tweak_book/function_replace.py b/src/calibre/gui2/tweak_book/function_replace.py index 9e3aace7fb..a3b07cf9c1 100644 --- a/src/calibre/gui2/tweak_book/function_replace.py +++ b/src/calibre/gui2/tweak_book/function_replace.py @@ -108,7 +108,7 @@ class DebugOutput(Dialog): def __init__(self, parent=None): Dialog.__init__(self, 'Debug output', 'sr-function-debug-output') - self.setAttribute(Qt.WA_DeleteOnClose, False) + self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, False) def setup_ui(self): self.l = l = QVBoxLayout(self) diff --git a/src/calibre/gui2/tweak_book/job.py b/src/calibre/gui2/tweak_book/job.py index 884a06ff48..51d563ca9c 100644 --- a/src/calibre/gui2/tweak_book/job.py +++ b/src/calibre/gui2/tweak_book/job.py @@ -50,14 +50,14 @@ class BlockingJob(QWidget): self.setLayout(l) l.addStretch(10) self.pi = ProgressIndicator(self, 128) - l.addWidget(self.pi, alignment=Qt.AlignHCenter) + l.addWidget(self.pi, alignment=Qt.AlignmentFlag.AlignHCenter) self.dummy = QLabel('

\xa0') l.addSpacing(10) - l.addWidget(self.dummy, alignment=Qt.AlignHCenter) + l.addWidget(self.dummy, alignment=Qt.AlignmentFlag.AlignHCenter) l.addStretch(10) self.setVisible(False) self.text = '' - self.setFocusPolicy(Qt.NoFocus) + self.setFocusPolicy(Qt.FocusPolicy.NoFocus) def start(self): self.setGeometry(0, 0, self.parent().width(), self.parent().height()) @@ -65,9 +65,9 @@ class BlockingJob(QWidget): # Prevent any actions from being triggerred by key presses self.parent().setEnabled(False) self.raise_() - self.setFocus(Qt.OtherFocusReason) + self.setFocus(Qt.FocusReason.OtherFocusReason) self.pi.startAnimation() - QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) + QApplication.setOverrideCursor(QCursor(Qt.CursorShape.WaitCursor)) def stop(self): QApplication.restoreOverrideCursor() @@ -77,7 +77,7 @@ class BlockingJob(QWidget): # The following line is needed on OS X, because of this bug: # https://bugreports.qt-project.org/browse/QTBUG-34371 it causes # keyboard events to no longer work - self.parent().setFocus(Qt.OtherFocusReason) + self.parent().setFocus(Qt.FocusReason.OtherFocusReason) def job_done(self, callback, job): del job.callback @@ -97,9 +97,9 @@ class BlockingJob(QWidget): f.setBold(True) f.setPointSize(20) p.setFont(f) - p.setPen(Qt.SolidLine) + p.setPen(Qt.PenStyle.SolidLine) r = QRect(0, self.dummy.geometry().top() + 10, self.geometry().width(), 150) - p.drawText(r, Qt.AlignHCenter | Qt.AlignTop | Qt.TextSingleLine, self.text) + p.drawText(r, Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop | Qt.TextFlag.TextSingleLine, self.text) p.end() def set_msg(self, text): diff --git a/src/calibre/gui2/tweak_book/live_css.py b/src/calibre/gui2/tweak_book/live_css.py index 4c35761b29..a440aae711 100644 --- a/src/calibre/gui2/tweak_book/live_css.py +++ b/src/calibre/gui2/tweak_book/live_css.py @@ -28,8 +28,8 @@ class Heading(QWidget): # {{{ def __init__(self, text, expanded=True, parent=None): QWidget.__init__(self, parent) - self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum) - self.setCursor(Qt.PointingHandCursor) + self.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Minimum) + self.setCursor(Qt.CursorShape.PointingHandCursor) self.text = text self.expanded = expanded self.hovering = False @@ -48,7 +48,7 @@ class Heading(QWidget): # {{{ self.setFont(f) def mousePressEvent(self, ev): - if ev.button() == Qt.LeftButton: + if ev.button() == Qt.MouseButton.LeftButton: ev.accept() self.expanded ^= True self.toggled.emit(self) @@ -68,12 +68,12 @@ class Heading(QWidget): # {{{ def paintEvent(self, ev): p = QPainter(self) p.setClipRect(ev.rect()) - bg = self.palette().color(QPalette.AlternateBase) + bg = self.palette().color(QPalette.ColorRole.AlternateBase) if self.hovering: bg = bg.lighter(115) p.fillRect(self.rect(), bg) try: - p.drawText(self.rect(), Qt.AlignLeft|Qt.AlignVCenter|Qt.TextSingleLine, self.rendered_text) + p.drawText(self.rect(), Qt.AlignmentFlag.AlignLeft|Qt.AlignmentFlag.AlignVCenter|Qt.TextFlag.TextSingleLine, self.rendered_text) finally: p.end() @@ -97,9 +97,9 @@ class Cell(object): # {{{ __slots__ = ('rect', 'text', 'right_align', 'color_role', 'override_color', 'swatch', 'is_overriden') SIDE_MARGIN = 5 - FLAGS = Qt.AlignVCenter | Qt.TextSingleLine | Qt.TextIncludeTrailingSpaces + FLAGS = Qt.AlignmentFlag.AlignVCenter | Qt.TextFlag.TextSingleLine | Qt.TextFlag.TextIncludeTrailingSpaces - def __init__(self, text, rect, right_align=False, color_role=QPalette.WindowText, swatch=None, is_overriden=False): + def __init__(self, text, rect, right_align=False, color_role=QPalette.ColorRole.WindowText, swatch=None, is_overriden=False): self.rect, self.text = rect, text self.right_align = right_align self.is_overriden = is_overriden @@ -110,7 +110,7 @@ class Cell(object): # {{{ self.swatch = QColor(swatch[0], swatch[1], swatch[2], int(255 * swatch[3])) def draw(self, painter, width, palette): - flags = self.FLAGS | (Qt.AlignRight if self.right_align else Qt.AlignLeft) + flags = self.FLAGS | (Qt.AlignmentFlag.AlignRight if self.right_align else Qt.AlignmentFlag.AlignLeft) rect = QRect(self.rect) if self.right_align: rect.setRight(width - self.SIDE_MARGIN) @@ -121,7 +121,7 @@ class Cell(object): # {{{ painter.fillRect(r, self.swatch) br.setRight(r.right()) if self.is_overriden: - painter.setPen(palette.color(QPalette.WindowText)) + painter.setPen(palette.color(QPalette.ColorRole.WindowText)) painter.drawLine(br.left(), br.top() + br.height() // 2, br.right(), br.top() + br.height() // 2) # }}} @@ -133,7 +133,7 @@ class Declaration(QWidget): def __init__(self, html_name, data, is_first=False, parent=None): QWidget.__init__(self, parent) - self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum) + self.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Minimum) self.data = data self.is_first = is_first self.html_name = html_name @@ -159,7 +159,7 @@ class Declaration(QWidget): br2 = bounding_rect(sel) self.hyperlink_rect = QRect(side_margin, ypos, br1.width(), br1.height()) self.rows.append([ - Cell(name, self.hyperlink_rect, color_role=QPalette.Link), + Cell(name, self.hyperlink_rect, color_role=QPalette.ColorRole.Link), Cell(sel, QRect(br1.right() + side_margin, ypos, br2.width(), br2.height()), right_align=True) ]) ypos += max(br1.height(), br2.height()) + 2 * line_spacing @@ -171,7 +171,7 @@ class Declaration(QWidget): vtext = prop.value + '\xa0' + ('!' if prop.important else '') + prop.important br2 = bounding_rect(vtext) self.rows.append([ - Cell(text, QRect(side_margin, ypos, br1.width(), br1.height()), color_role=QPalette.LinkVisited, is_overriden=prop.is_overriden), + Cell(text, QRect(side_margin, ypos, br1.width(), br1.height()), color_role=QPalette.ColorRole.LinkVisited, is_overriden=prop.is_overriden), Cell(vtext, QRect(br1.right() + side_margin, ypos, br2.width(), br2.height()), swatch=prop.color, is_overriden=prop.is_overriden) ]) self.lines_for_copy.append(text + vtext) @@ -190,7 +190,7 @@ class Declaration(QWidget): p = QPainter(self) p.setClipRect(ev.rect()) palette = self.palette() - p.setPen(palette.color(QPalette.WindowText)) + p.setPen(palette.color(QPalette.ColorRole.WindowText)) if not self.is_first: p.drawLine(0, 0, self.width(), 0) try: @@ -210,20 +210,20 @@ class Declaration(QWidget): pos = ev.pos() hovering = self.hyperlink_rect.contains(pos) self.update_hover(hovering) - cursor = Qt.ArrowCursor + cursor = Qt.CursorShape.ArrowCursor for r, row in enumerate(self.rows): for cell in row: if cell.rect.contains(pos): - cursor = Qt.PointingHandCursor if cell.rect is self.hyperlink_rect else Qt.IBeamCursor + cursor = Qt.CursorShape.PointingHandCursor if cell.rect is self.hyperlink_rect else Qt.CursorShape.IBeamCursor if r == 0: break - if cursor != Qt.ArrowCursor: + if cursor != Qt.CursorShape.ArrowCursor: break self.setCursor(cursor) return QWidget.mouseMoveEvent(self, ev) def mousePressEvent(self, ev): - if hasattr(self, 'hyperlink_rect') and ev.button() == Qt.LeftButton: + if hasattr(self, 'hyperlink_rect') and ev.button() == Qt.MouseButton.LeftButton: pos = ev.pos() if self.hyperlink_rect.contains(pos): self.emit_hyperlink_activated() @@ -245,14 +245,14 @@ class Declaration(QWidget): def leaveEvent(self, ev): self.update_hover(False) - self.setCursor(Qt.ArrowCursor) + self.setCursor(Qt.CursorShape.ArrowCursor) return QWidget.leaveEvent(self, ev) def update_hover(self, hovering): cell = self.rows[0][0] if (hovering and cell.override_color is None) or ( not hovering and cell.override_color is not None): - cell.override_color = QColor(Qt.red) if hovering else None + cell.override_color = QColor(Qt.GlobalColor.red) if hovering else None self.update() def contextMenuEvent(self, ev): @@ -266,7 +266,7 @@ class Box(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.l = l = QVBoxLayout(self) - l.setAlignment(Qt.AlignTop) + l.setAlignment(Qt.AlignmentFlag.AlignTop) self.setLayout(l) self.widgets = [] @@ -404,11 +404,11 @@ class LiveCSS(QWidget): 'Move the cursor inside a HTML tag to see what styles' ' apply to that tag.')) la.setWordWrap(True) - la.setAlignment(Qt.AlignTop | Qt.AlignLeft) + la.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft) s.addWidget(la) self.box = box = Box(self) - box.hyperlink_activated.connect(self.goto_declaration, type=Qt.QueuedConnection) + box.hyperlink_activated.connect(self.goto_declaration, type=Qt.ConnectionType.QueuedConnection) self.scroll = sc = QScrollArea(self) sc.setWidget(box) sc.setWidgetResizable(True) diff --git a/src/calibre/gui2/tweak_book/main.py b/src/calibre/gui2/tweak_book/main.py index a88d74e11d..ec8a17ea17 100644 --- a/src/calibre/gui2/tweak_book/main.py +++ b/src/calibre/gui2/tweak_book/main.py @@ -56,7 +56,7 @@ def _run(args, notify=None): reset_base_dir() scheme = QWebEngineUrlScheme(FAKE_PROTOCOL.encode('ascii')) scheme.setSyntax(QWebEngineUrlScheme.Syntax.Host) - scheme.setFlags(QWebEngineUrlScheme.SecureScheme) + scheme.setFlags(QWebEngineUrlScheme.Flag.SecureScheme) QWebEngineUrlScheme.registerScheme(scheme) # The following two lines are needed to prevent circular imports causing diff --git a/src/calibre/gui2/tweak_book/manage_fonts.py b/src/calibre/gui2/tweak_book/manage_fonts.py index 83306f0e46..fe5f28b2df 100644 --- a/src/calibre/gui2/tweak_book/manage_fonts.py +++ b/src/calibre/gui2/tweak_book/manage_fonts.py @@ -106,8 +106,8 @@ class AllFonts(QAbstractTableModel): def columnCount(self, parent=None): return 2 - def headerData(self, section, orientation, role=Qt.DisplayRole): - if orientation == Qt.Horizontal and role == Qt.DisplayRole: + def headerData(self, section, orientation, role=Qt.ItemDataRole.DisplayRole): + if orientation == Qt.Orientation.Horizontal and role == Qt.ItemDataRole.DisplayRole: return _('Font family') if section == 1 else _('Embedded') return QAbstractTableModel.headerData(self, section, orientation, role) @@ -124,8 +124,8 @@ class AllFonts(QAbstractTableModel): if self.sorted_on[0] != 'name': self.items.sort(key=self.font_data.get, reverse=reverse) - def data(self, index, role=Qt.DisplayRole): - if role == Qt.DisplayRole: + def data(self, index, role=Qt.ItemDataRole.DisplayRole): + if role == Qt.ItemDataRole.DisplayRole: row, col = index.row(), index.column() try: name = self.items[row] @@ -133,17 +133,17 @@ class AllFonts(QAbstractTableModel): except (IndexError, KeyError): return return name if col == 1 else embedded - if role == Qt.TextAlignmentRole: + if role == Qt.ItemDataRole.TextAlignmentRole: col = index.column() if col == 0: - return Qt.AlignHCenter | Qt.AlignVCenter - if role in (Qt.UserRole, Qt.UserRole + 1): + return Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter + if role in (Qt.ItemDataRole.UserRole, Qt.ItemDataRole.UserRole + 1): row = index.row() try: name = self.items[row] except (IndexError, KeyError): return - if role == Qt.UserRole: + if role == Qt.ItemDataRole.UserRole: try: return font_scanner.fonts_for_family(name) except NoFonts: @@ -151,8 +151,8 @@ class AllFonts(QAbstractTableModel): else: return name - def sort(self, col, order=Qt.AscendingOrder): - sorted_on = (('name' if col == 1 else 'embedded'), order == Qt.AscendingOrder) + def sort(self, col, order=Qt.SortOrder.AscendingOrder): + sorted_on = (('name' if col == 1 else 'embedded'), order == Qt.SortOrder.AscendingOrder) if sorted_on != self.sorted_on: self.sorted_on = sorted_on self.beginResetModel() @@ -230,7 +230,7 @@ class ManageFonts(Dialog): Dialog.__init__(self, _('Manage Fonts'), 'manage-fonts', parent=parent) def setup_ui(self): - self.setAttribute(Qt.WA_DeleteOnClose, False) + self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, False) self.l = l = QVBoxLayout(self) self.setLayout(l) @@ -255,7 +255,7 @@ class ManageFonts(Dialog): fv.setAlternatingRowColors(True) fv.setSelectionMode(fv.ExtendedSelection) fv.setSelectionBehavior(fv.SelectRows) - fv.horizontalHeader().setSortIndicator(1, Qt.AscendingOrder) + fv.horizontalHeader().setSortIndicator(1, Qt.SortOrder.AscendingOrder) self.container = c = QWidget() l = c.l = QVBoxLayout(c) c.setLayout(l) @@ -291,11 +291,11 @@ class ManageFonts(Dialog): la.setWordWrap(True) l.addWidget(la) - l.setAlignment(Qt.AlignTop | Qt.AlignHCenter) + l.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignHCenter) def show_embedding_data(self, index): - faces = index.data(Qt.UserRole) - family = index.data(Qt.UserRole + 1) + faces = index.data(Qt.ItemDataRole.UserRole) + family = index.data(Qt.ItemDataRole.UserRole + 1) if not faces: return error_dialog(self, _('Not found'), _( 'The font %s was not found on your computer. If you have the font files,' diff --git a/src/calibre/gui2/tweak_book/plugin.py b/src/calibre/gui2/tweak_book/plugin.py index b07d195d57..c1b555abf4 100644 --- a/src/calibre/gui2/tweak_book/plugin.py +++ b/src/calibre/gui2/tweak_book/plugin.py @@ -152,8 +152,8 @@ def create_plugin_action(plugin, tool, for_toolbar, actions=None, toolbar_action if toolbar_actions is not None: toolbar_actions[sid] = ac plugin_toolbar_actions.append(ac) - ac.popup_mode = {'instant':QToolButton.InstantPopup, 'button':QToolButton.MenuButtonPopup}.get( - tool.toolbar_button_popup_mode, QToolButton.DelayedPopup) + ac.popup_mode = {'instant':QToolButton.ToolButtonPopupMode.InstantPopup, 'button':QToolButton.ToolButtonPopupMode.MenuButtonPopup}.get( + tool.toolbar_button_popup_mode, QToolButton.ToolButtonPopupMode.DelayedPopup) else: if plugin_menu_actions is not None: plugin_menu_actions.append(ac) diff --git a/src/calibre/gui2/tweak_book/polish.py b/src/calibre/gui2/tweak_book/polish.py index fd148c698f..8eee5df25b 100644 --- a/src/calibre/gui2/tweak_book/polish.py +++ b/src/calibre/gui2/tweak_book/polish.py @@ -62,7 +62,7 @@ def customize_remove_unused_css(name, parent, ans): ' Note that in rare cases merging can result in a change to the effective styling' ' of the book, so use with care.')) - d.bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) + d.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) d.l.addWidget(d.bb) d.bb.rejected.connect(d.reject) d.bb.accepted.connect(d.accept) @@ -109,7 +109,7 @@ def show_report(changed, title, report, parent, show_current_diff): d.e = QTextBrowser(d) d.l.addWidget(d.e) d.e.setHtml(report) - d.bb = QDialogButtonBox(QDialogButtonBox.Close) + d.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) d.show_changes = False if changed: b = d.b = d.bb.addButton(_('See what &changed'), d.bb.AcceptRole) @@ -144,17 +144,17 @@ class ImageItemDelegate(QStyledItemDelegate): return QSize(300, 100) def paint(self, painter, option, index): - name = index.data(Qt.DisplayRole) - sz = human_readable(index.data(Qt.UserRole)) - pmap = index.data(Qt.UserRole+1) + name = index.data(Qt.ItemDataRole.DisplayRole) + sz = human_readable(index.data(Qt.ItemDataRole.UserRole)) + pmap = index.data(Qt.ItemDataRole.UserRole+1) irect = option.rect.adjusted(0, 5, 0, -5) irect.setRight(irect.left() + 70) if pmap is None: pmap = QPixmap(current_container().get_file_path_for_processing(name)) scaled, nwidth, nheight = fit_image(pmap.width(), pmap.height(), irect.width(), irect.height()) if scaled: - pmap = pmap.scaled(nwidth, nheight, transformMode=Qt.SmoothTransformation) - index.model().setData(index, pmap, Qt.UserRole+1) + pmap = pmap.scaled(nwidth, nheight, transformMode=Qt.TransformationMode.SmoothTransformation) + index.model().setData(index, pmap, Qt.ItemDataRole.UserRole+1) x, y = (irect.width() - pmap.width())//2, (irect.height() - pmap.height())//2 r = irect.adjusted(x, y, -x, -y) QStyledItemDelegate.paint(self, painter, option, empty_index) @@ -162,9 +162,9 @@ class ImageItemDelegate(QStyledItemDelegate): trect = irect.adjusted(irect.width() + 10, 0, 0, 0) trect.setRight(option.rect.right()) painter.save() - if option.state & QStyle.State_Selected: + if option.state & QStyle.StateFlag.State_Selected: painter.setPen(QPen(option.palette.color(option.palette.HighlightedText))) - painter.drawText(trect, Qt.AlignVCenter | Qt.AlignLeft, name + '\n' + sz) + painter.drawText(trect, Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft, name + '\n' + sz) painter.restore() @@ -184,7 +184,7 @@ class CompressImages(Dialog): c = current_container() for name in sorted(get_compressible_images(c), key=numeric_sort_key): x = QListWidgetItem(name, i) - x.setData(Qt.UserRole, c.filesize(name)) + x.setData(Qt.ItemDataRole.UserRole, c.filesize(name)) i.setSelectionMode(i.ExtendedSelection) i.setMinimumHeight(350), i.setMinimumWidth(350) i.selectAll(), i.setSpacing(5) @@ -239,8 +239,8 @@ class CompressImagesProgress(Dialog): self.keep_going = True self.result = (None, '') Dialog.__init__(self, _('Compressing images...'), 'compress-images-progress', parent=parent) - self.gui_loop.connect(self.update_progress, type=Qt.QueuedConnection) - self.cidone.connect(self.accept, type=Qt.QueuedConnection) + self.gui_loop.connect(self.update_progress, type=Qt.ConnectionType.QueuedConnection) + self.cidone.connect(self.accept, type=Qt.ConnectionType.QueuedConnection) t = Thread(name='RunCompressImages', target=self.run_compress) t.daemon = True t.start() @@ -261,17 +261,17 @@ class CompressImagesProgress(Dialog): def setup_ui(self): self.setWindowIcon(QIcon(I('compress-image.png'))) - self.setCursor(Qt.BusyCursor) + self.setCursor(Qt.CursorShape.BusyCursor) self.setMinimumWidth(350) self.l = l = QVBoxLayout(self) self.la = la = QLabel(_('Compressing images, please wait...')) - la.setStyleSheet('QLabel { font-weight: bold }'), la.setAlignment(Qt.AlignCenter), la.setTextFormat(Qt.PlainText) + la.setStyleSheet('QLabel { font-weight: bold }'), la.setAlignment(Qt.AlignmentFlag.AlignCenter), la.setTextFormat(Qt.TextFormat.PlainText) l.addWidget(la) self.progress = p = QProgressBar(self) p.setMinimum(0), p.setMaximum(0) l.addWidget(p) self.msg = la = QLabel('\xa0') - la.setAlignment(Qt.AlignCenter), la.setTextFormat(Qt.PlainText) + la.setAlignment(Qt.AlignmentFlag.AlignCenter), la.setTextFormat(Qt.TextFormat.PlainText) l.addWidget(la) self.bb.setStandardButtons(self.bb.Cancel) diff --git a/src/calibre/gui2/tweak_book/preferences.py b/src/calibre/gui2/tweak_book/preferences.py index 48a3ea9818..07cba73ed2 100644 --- a/src/calibre/gui2/tweak_book/preferences.py +++ b/src/calibre/gui2/tweak_book/preferences.py @@ -83,9 +83,9 @@ class BasicSettings(QWidget): # {{{ def setter(w, val): val = {None:none_val}.get(val, val) - idx = w.findData(val, flags=Qt.MatchFixedString|Qt.MatchCaseSensitive) + idx = w.findData(val, flags=Qt.MatchFlag.MatchFixedString|Qt.MatchFlag.MatchCaseSensitive) if idx == -1: - idx = w.findData(fallback_val, flags=Qt.MatchFixedString|Qt.MatchCaseSensitive) + idx = w.findData(fallback_val, flags=Qt.MatchFlag.MatchFixedString|Qt.MatchFlag.MatchCaseSensitive) w.setCurrentIndex(idx) return self(name, widget=widget, getter=getter, setter=setter, prefs=prefs) @@ -99,7 +99,7 @@ class BasicSettings(QWidget): # {{{ widget.viewport().setAcceptDrops(True) widget.setDropIndicatorShown(True) widget.indexesMoved.connect(self.emit_changed) - widget.setDefaultDropAction(Qt.MoveAction) + widget.setDefaultDropAction(Qt.DropAction.MoveAction) widget.setMovement(widget.Snap) widget.setSpacing(5) widget.defaults = prefs.defaults[name] @@ -116,7 +116,7 @@ class BasicSettings(QWidget): # {{{ for x in items: i = QListWidgetItem(w) i.setText(x) - i.setFlags(i.flags() | Qt.ItemIsDragEnabled) + i.setFlags(i.flags() | Qt.ItemFlag.ItemIsDragEnabled) return self(name, widget=widget, getter=getter, setter=setter, prefs=prefs) @@ -233,12 +233,12 @@ class EditorSettings(BasicSettings): # {{{ l.addRow(lw) self.dictionaries = d = QPushButton(_('Manage &spelling dictionaries'), self) - d.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) + d.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) d.clicked.connect(self.manage_dictionaries) l.addRow(d) self.snippets = s = QPushButton(_('Manage sni&ppets'), self) - s.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) + s.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) s.clicked.connect(self.manage_snippets) l.addRow(s) @@ -461,7 +461,7 @@ class ToolbarSettings(QWidget): ): b.addItem(text, name) self.la = la = QLabel(_('&Toolbar to customize:')) - la.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) + la.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) la.setBuddy(b) gl.addWidget(la), gl.addWidget(b, 0, 1) self.sl = l = QGridLayout() @@ -470,8 +470,8 @@ class ToolbarSettings(QWidget): self.gb1 = gb1 = QGroupBox(_('A&vailable actions'), self) self.gb2 = gb2 = QGroupBox(_('&Current actions'), self) gb1.setFlat(True), gb2.setFlat(True) - gb1.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) - gb2.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) + gb1.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) + gb2.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) l.addWidget(gb1, 0, 0, -1, 1), l.addWidget(gb2, 0, 2, -1, 1) self.available, self.current = ToolbarList(self), ToolbarList(self) self.ub = b = QToolButton(self) @@ -492,7 +492,7 @@ class ToolbarSettings(QWidget): self.rb = b = QToolButton(self) b.setToolTip(_('Remove selected actions from the toolbar')), b.setIcon(QIcon(I('back.png'))) l.addWidget(b, 3, 1), b.clicked.connect(self.remove_action) - self.si = QSpacerItem(20, 10, hPolicy=QSizePolicy.Preferred, vPolicy=QSizePolicy.Expanding) + self.si = QSpacerItem(20, 10, hPolicy=QSizePolicy.Policy.Preferred, vPolicy=QSizePolicy.Policy.Expanding) l.setRowStretch(0, 10), l.setRowStretch(2, 10), l.setRowStretch(4, 10) l.addItem(self.si, 4, 1) @@ -544,7 +544,7 @@ class ToolbarSettings(QWidget): if not ic or ic.isNull(): ic = blank ans = QListWidgetItem(ic, unicode_type(ac.text()).replace('&', ''), parent) - ans.setData(Qt.UserRole, key) + ans.setData(Qt.ItemDataRole.UserRole, key) ans.setToolTip(ac.toolTip()) return ans @@ -552,7 +552,7 @@ class ToolbarSettings(QWidget): if key not in applied: to_item(key, ac, self.available) if name == 'global_book_toolbar' and 'donate' not in applied: - QListWidgetItem(QIcon(I('donate.png')), _('Donate'), self.available).setData(Qt.UserRole, 'donate') + QListWidgetItem(QIcon(I('donate.png')), _('Donate'), self.available).setData(Qt.ItemDataRole.UserRole, 'donate') QListWidgetItem(blank, '--- %s ---' % _('Separator'), self.available) for key in items: @@ -560,7 +560,7 @@ class ToolbarSettings(QWidget): QListWidgetItem(blank, '--- %s ---' % _('Separator'), self.current) else: if key == 'donate': - QListWidgetItem(QIcon(I('donate.png')), _('Donate'), self.current).setData(Qt.UserRole, 'donate') + QListWidgetItem(QIcon(I('donate.png')), _('Donate'), self.current).setData(Qt.ItemDataRole.UserRole, 'donate') else: try: ac = all_items[key] @@ -599,7 +599,7 @@ class ToolbarSettings(QWidget): s = self.current_settings[self.current_name] except KeyError: return - names = [unicode_type(i.data(Qt.UserRole) or '') for i in self.available.selectedItems()] + names = [unicode_type(i.data(Qt.ItemDataRole.UserRole) or '') for i in self.available.selectedItems()] if not names: return for n in names: @@ -741,7 +741,7 @@ class Preferences(QDialog): cl.setWordWrap(True) l.addWidget(cl, 0, 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.rdb = b = bb.addButton(_('Restore all &defaults'), bb.ResetRole) @@ -790,7 +790,7 @@ class Preferences(QDialog): cl.item(i).setSizeHint(QSize(w, h)) cl.setMaximumWidth(cl.sizeHintForColumn(0) + 35) - cl.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) + cl.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) cl.setMinimumWidth(min(cl.maximumWidth(), cl.sizeHint().width())) @property diff --git a/src/calibre/gui2/tweak_book/preview.py b/src/calibre/gui2/tweak_book/preview.py index abcce059ca..456f8eadd7 100644 --- a/src/calibre/gui2/tweak_book/preview.py +++ b/src/calibre/gui2/tweak_book/preview.py @@ -280,7 +280,7 @@ def create_profile(): document.addEventListener("DOMContentLoaded", apply_css); })(); '''.replace('CSS', json.dumps(dark_mode_css), 1), - injection_point=QWebEngineScript.DocumentCreation) + injection_point=QWebEngineScript.InjectionPoint.DocumentCreation) ) url_handler = UrlSchemeHandler(ans) ans.installUrlSchemeHandler(QByteArray(FAKE_PROTOCOL.encode('ascii')), url_handler) @@ -329,9 +329,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 go_to_sourceline_address(self, sourceline_address): if self.bridge.ready: @@ -420,7 +420,7 @@ class WebView(RestartingWebEngineView, OpenWithHandler): def refresh(self): self.update_settings() - self.pageAction(QWebEnginePage.ReloadAndBypassCache).trigger() + self.pageAction(QWebEnginePage.WebAction.ReloadAndBypassCache).trigger() def set_url(self, qurl): self.update_settings() @@ -443,7 +443,7 @@ class WebView(RestartingWebEngineView, OpenWithHandler): def inspect(self): self.inspector.parent().show() self.inspector.parent().raise_() - self.pageAction(QWebEnginePage.InspectElement).trigger() + self.pageAction(QWebEnginePage.WebAction.InspectElement).trigger() def contextMenuEvent(self, ev): menu = QMenu(self) @@ -452,7 +452,7 @@ class WebView(RestartingWebEngineView, OpenWithHandler): url = unicode_type(url.toString(NO_URL_FORMATTING)).strip() text = data.selectedText() if text: - ca = self.pageAction(QWebEnginePage.Copy) + ca = self.pageAction(QWebEnginePage.WebAction.Copy) if ca.isEnabled(): menu.addAction(ca) menu.addAction(actions['reload-preview']) @@ -515,9 +515,9 @@ class Preview(QWidget): self.stack.addWidget(self.view) self.cover = c = QLabel(_('Loading preview, please wait...')) c.setWordWrap(True) - c.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) + c.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) c.setStyleSheet('QLabel { background-color: palette(window); }') - c.setAlignment(Qt.AlignCenter) + c.setAlignment(Qt.AlignmentFlag.AlignCenter) self.stack.addWidget(self.cover) self.stack.setCurrentIndex(self.stack.indexOf(self.cover)) self.bar = QToolBar(self) @@ -573,7 +573,7 @@ class Preview(QWidget): def find(self, direction): text = unicode_type(self.search.text()) self.view._page.findText(text, ( - QWebEnginePage.FindBackward if direction == 'prev' else QWebEnginePage.FindFlags(0))) + QWebEnginePage.FindFlag.FindBackward if direction == 'prev' else QWebEnginePage.FindFlags(0))) def find_next(self): self.find('next') diff --git a/src/calibre/gui2/tweak_book/reports.py b/src/calibre/gui2/tweak_book/reports.py index 924d4ecc61..39b8ccb079 100644 --- a/src/calibre/gui2/tweak_book/reports.py +++ b/src/calibre/gui2/tweak_book/reports.py @@ -62,7 +62,7 @@ def save_state(name, val): data[name] = val -SORT_ROLE = Qt.UserRole + 1 +SORT_ROLE = Qt.ItemDataRole.UserRole + 1 class ProxyModel(QSortFilterProxyModel): @@ -85,8 +85,8 @@ class ProxyModel(QSortFilterProxyModel): return True return False - def headerData(self, section, orientation, role=Qt.DisplayRole): - if orientation == Qt.Vertical and role == Qt.DisplayRole: + def headerData(self, section, orientation, role=Qt.ItemDataRole.DisplayRole): + if orientation == Qt.Orientation.Vertical and role == Qt.ItemDataRole.DisplayRole: return section + 1 return QSortFilterProxyModel.headerData(self, section, orientation, role) @@ -106,8 +106,8 @@ class FileCollection(QAbstractTableModel): def rowCount(self, parent=None): return len(self.files) - def headerData(self, section, orientation, role=Qt.DisplayRole): - if role == Qt.DisplayRole and orientation == Qt.Horizontal: + def headerData(self, section, orientation, role=Qt.ItemDataRole.DisplayRole): + if role == Qt.ItemDataRole.DisplayRole and orientation == Qt.Orientation.Horizontal: try: return self.COLUMN_HEADERS[section] except IndexError: @@ -137,7 +137,7 @@ class FilesView(QTableView): p.setSourceModel(model) self.setModel(p) self.doubleClicked.connect(self._double_clicked) - self.setContextMenuPolicy(Qt.CustomContextMenu) + self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.customContextMenuRequested.connect(self.show_context_menu) def currentChanged(self, current, previous): @@ -162,7 +162,7 @@ class FilesView(QTableView): self.double_clicked.emit(index) def keyPressEvent(self, ev): - if self.DELETE_POSSIBLE and ev.key() == Qt.Key_Delete: + if self.DELETE_POSSIBLE and ev.key() == Qt.Key.Key_Delete: self.delete_selected() ev.accept() return @@ -203,14 +203,14 @@ class FilesView(QTableView): w.writerow(self.proxy.sourceModel().COLUMN_HEADERS) cols = self.proxy.columnCount() for r in range(self.proxy.rowCount()): - items = [self.proxy.index(r, c).data(Qt.DisplayRole) for c in range(cols)] + items = [self.proxy.index(r, c).data(Qt.ItemDataRole.DisplayRole) for c in range(cols)] w.writerow(items) return buf.getvalue() def save_table(self, name): save_state(name, bytearray(self.horizontalHeader().saveState())) - def restore_table(self, name, sort_column=0, sort_order=Qt.AscendingOrder): + def restore_table(self, name, sort_column=0, sort_order=Qt.SortOrder.AscendingOrder): h = self.horizontalHeader() try: h.restoreState(read_state(name)) @@ -251,13 +251,13 @@ class FilesModel(FileCollection): for entry in self.files) self.endResetModel() - def data(self, index, role=Qt.DisplayRole): + def data(self, index, role=Qt.ItemDataRole.DisplayRole): if role == SORT_ROLE: try: return self.sort_keys[index.row()][index.column()] except IndexError: pass - elif role == Qt.DisplayRole: + elif role == Qt.ItemDataRole.DisplayRole: col = index.column() try: entry = self.files[index.row()] @@ -298,7 +298,7 @@ class FilesWidget(QWidget): self.summary = s = QLabel(self) l.addWidget(s) s.setText('\xa0') - self.files.restore_table('all-files-table', 1, Qt.AscendingOrder) + self.files.restore_table('all-files-table', 1, Qt.SortOrder.AscendingOrder) def __call__(self, data): self.model(data) @@ -372,7 +372,7 @@ class ImagesDelegate(QStyledItemDelegate): def sizeHint(self, option, index): ans = QStyledItemDelegate.sizeHint(self, option, index) - entry = index.data(Qt.UserRole) + entry = index.data(Qt.ItemDataRole.UserRole) if entry is None: return ans th = self.parent().thumbnail_height @@ -382,7 +382,7 @@ class ImagesDelegate(QStyledItemDelegate): def paint(self, painter, option, index): QStyledItemDelegate.paint(self, painter, option, ROOT) - entry = index.data(Qt.UserRole) + entry = index.data(Qt.ItemDataRole.UserRole) if entry is None: return painter.save() @@ -403,9 +403,9 @@ class ImagesDelegate(QStyledItemDelegate): painter.drawPixmap(x, option.rect.top() + self.MARGIN, pmap) bottom = m + int(pmap.height() / pmap.devicePixelRatio()) + option.rect.top() rect = QRect(option.rect.left(), bottom, option.rect.width(), option.rect.bottom() - bottom) - if option.state & QStyle.State_Selected: - painter.setPen(self.parent().palette().color(QPalette.HighlightedText)) - painter.drawText(rect, Qt.AlignHCenter | Qt.AlignVCenter, entry.basename) + if option.state & QStyle.StateFlag.State_Selected: + painter.setPen(self.parent().palette().color(QPalette.ColorRole.HighlightedText)) + painter.drawText(rect, Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter, entry.basename) painter.restore() def pixmap(self, thumbnail_height, entry, dpr): @@ -414,7 +414,7 @@ class ImagesDelegate(QStyledItemDelegate): pmap.setDevicePixelRatio(dpr) scaled, width, height = fit_image(entry.width, entry.height, thumbnail_height, thumbnail_height) if scaled: - pmap = pmap.scaled(int(dpr * width), int(dpr * height), transformMode=Qt.SmoothTransformation) + pmap = pmap.scaled(int(dpr * width), int(dpr * height), transformMode=Qt.TransformationMode.SmoothTransformation) pmap.setDevicePixelRatio(dpr) return pmap @@ -434,13 +434,13 @@ class ImagesModel(FileCollection): for entry in self.files) self.endResetModel() - def data(self, index, role=Qt.DisplayRole): + def data(self, index, role=Qt.ItemDataRole.DisplayRole): if role == SORT_ROLE: try: return self.sort_keys[index.row()][index.column()] except IndexError: pass - elif role == Qt.DisplayRole: + elif role == Qt.ItemDataRole.DisplayRole: col = index.column() try: entry = self.files[index.row()] @@ -455,7 +455,7 @@ class ImagesModel(FileCollection): return unicode_type(len(entry.usage)) if col == 3: return '%d x %d' % (entry.width, entry.height) - elif role == Qt.UserRole: + elif role == Qt.ItemDataRole.UserRole: try: return self.files[index.row()] except IndexError: @@ -499,7 +499,7 @@ class ImagesWidget(QWidget): QTimer.singleShot(0, self.files.resizeRowsToContents) def double_clicked(self, index): - entry = index.data(Qt.UserRole) + entry = index.data(Qt.ItemDataRole.UserRole) if entry is not None: jump((id(self), entry.id), entry.usage) @@ -532,13 +532,13 @@ class LinksModel(FileCollection): for link in self.links) self.endResetModel() - def data(self, index, role=Qt.DisplayRole): + def data(self, index, role=Qt.ItemDataRole.DisplayRole): if role == SORT_ROLE: try: return self.sort_keys[index.row()][index.column()] except IndexError: pass - elif role == Qt.DisplayRole: + elif role == Qt.ItemDataRole.DisplayRole: col = index.column() try: link = self.links[index.row()] @@ -556,7 +556,7 @@ class LinksModel(FileCollection): return link.anchor.id if col == 5: return link.anchor.text - elif role == Qt.ToolTipRole: + elif role == Qt.ItemDataRole.ToolTipRole: col = index.column() try: link = self.links[index.row()] @@ -571,7 +571,7 @@ class LinksModel(FileCollection): if col == 5: if link.anchor.text: return textwrap.fill(link.anchor.text) - elif role == Qt.UserRole: + elif role == Qt.ItemDataRole.UserRole: try: return self.links[index.row()] except IndexError: @@ -592,7 +592,7 @@ class LinksWidget(QWidget): self.filter_edit = e = QLineEdit(self) l.addWidget(e) - self.splitter = s = QSplitter(Qt.Vertical, self) + self.splitter = s = QSplitter(Qt.Orientation.Vertical, self) l.addWidget(s) e.setPlaceholderText(_('Filter')) e.setClearButtonEnabled(True) @@ -605,7 +605,7 @@ class LinksWidget(QWidget): s.addWidget(f) self.links.restore_table('links-table', sort_column=1) self.view = None - self.setContextMenuPolicy(Qt.NoContextMenu) + self.setContextMenuPolicy(Qt.ContextMenuPolicy.NoContextMenu) self.ignore_current_change = False self.current_url = None f.current_changed.connect(self.current_changed) @@ -620,7 +620,7 @@ class LinksWidget(QWidget): if self.view is None: self.view = WebView(self) secure_webengine(self.view) - self.view.setContextMenuPolicy(Qt.NoContextMenu) + self.view.setContextMenuPolicy(Qt.ContextMenuPolicy.NoContextMenu) self.splitter.addWidget(self.view) self.splitter.setCollapsible(1, True) self.ignore_current_change = True @@ -632,7 +632,7 @@ class LinksWidget(QWidget): self.ignore_current_change = False def current_changed(self, current, previous): - link = current.data(Qt.UserRole) + link = current.data(Qt.ItemDataRole.UserRole) if link is None: return url = None @@ -656,7 +656,7 @@ class LinksWidget(QWidget): self.view.setUrl(url) def double_clicked(self, index): - link = index.data(Qt.UserRole) + link = index.data(Qt.ItemDataRole.UserRole) if link is None: return if index.column() < 3: @@ -699,13 +699,13 @@ class WordsModel(FileCollection): self.sort_keys = tuple((psk(entry.word), locale_sort_key(entry.locale), len(entry.usage)) for entry in self.files) self.endResetModel() - def data(self, index, role=Qt.DisplayRole): + def data(self, index, role=Qt.ItemDataRole.DisplayRole): if role == SORT_ROLE: try: return self.sort_keys[index.row()][index.column()] except IndexError: pass - elif role == Qt.DisplayRole: + elif role == Qt.ItemDataRole.DisplayRole: col = index.column() try: entry = self.files[index.row()] @@ -720,7 +720,7 @@ class WordsModel(FileCollection): return ans if col == 2: return unicode_type(len(entry.usage)) - elif role == Qt.UserRole: + elif role == Qt.ItemDataRole.UserRole: try: return self.files[index.row()] except IndexError: @@ -760,7 +760,7 @@ class WordsWidget(QWidget): self.model.rowCount(), self.model.total_size, self.model.total_words)) def double_clicked(self, index): - entry = index.data(Qt.UserRole) + entry = index.data(Qt.ItemDataRole.UserRole) if entry is not None: from calibre.gui2.tweak_book.boss import get_boss boss = get_boss() @@ -786,7 +786,7 @@ class CharsModel(FileCollection): self.sort_keys = tuple((psk(entry.char), None, entry.codepoint, entry.count) for entry in self.files) self.endResetModel() - def data(self, index, role=Qt.DisplayRole): + def data(self, index, role=Qt.ItemDataRole.DisplayRole): if role == SORT_ROLE: if index.column() == 1: return self.data(index) @@ -794,7 +794,7 @@ class CharsModel(FileCollection): return self.sort_keys[index.row()][index.column()] except IndexError: pass - elif role == Qt.DisplayRole: + elif role == Qt.ItemDataRole.DisplayRole: col = index.column() try: entry = self.files[index.row()] @@ -808,7 +808,7 @@ class CharsModel(FileCollection): return ('U+%04X' if entry.codepoint < 0x10000 else 'U+%06X') % entry.codepoint if col == 3: return unicode_type(entry.count) - elif role == Qt.UserRole: + elif role == Qt.ItemDataRole.UserRole: try: return self.files[index.row()] except IndexError: @@ -849,7 +849,7 @@ class CharsWidget(QWidget): self.filter_edit.clear() def double_clicked(self, index): - entry = index.data(Qt.UserRole) + entry = index.data(Qt.ItemDataRole.UserRole) if entry is not None: self.find_next_location(entry) @@ -898,7 +898,7 @@ class CSSRulesModel(QAbstractItemModel): self.num_size = 1 self.num_unused = 0 self.build_maps() - self.main_font = f = QFontDatabase.systemFont(QFontDatabase.FixedFont) + self.main_font = f = QFontDatabase.systemFont(QFontDatabase.SystemFont.FixedFont) f.setBold(True), f.setPointSize(parent.font().pointSize() + 2) self.italic_font = f = QFont(parent.font()) f.setItalic(True) @@ -954,7 +954,7 @@ class CSSRulesModel(QAbstractItemModel): def columnCount(self, parent=ROOT): return 1 - def data(self, index, role=Qt.DisplayRole): + def data(self, index, role=Qt.ItemDataRole.DisplayRole): if role == SORT_ROLE: entry = self.index_to_entry(index) if isinstance(entry, CSSEntry): @@ -963,7 +963,7 @@ class CSSRulesModel(QAbstractItemModel): return len(entry.locations) if self.sort_on_count else entry.sort_key if isinstance(entry, MatchLocation): return entry.sourceline - elif role == Qt.DisplayRole: + elif role == Qt.ItemDataRole.DisplayRole: entry = self.index_to_entry(index) if isinstance(entry, CSSEntry): return '[%{}d] %s'.format(self.num_size) % (entry.count, entry.rule.selector) @@ -971,9 +971,9 @@ class CSSRulesModel(QAbstractItemModel): return _('{0} [{1} elements]').format(entry.file_name, len(entry.locations)) elif isinstance(entry, MatchLocation): return '%s @ %s' % (entry.tag, entry.sourceline) - elif role == Qt.UserRole: + elif role == Qt.ItemDataRole.UserRole: return self.index_to_entry(index) - elif role == Qt.FontRole: + elif role == Qt.ItemDataRole.FontRole: entry = self.index_to_entry(index) if isinstance(entry, CSSEntry): return self.main_font @@ -1067,11 +1067,11 @@ class CSSWidget(QWidget): @property def sort_order(self): - return [Qt.AscendingOrder, Qt.DescendingOrder][self._sort_order.currentIndex()] + return [Qt.SortOrder.AscendingOrder, Qt.SortOrder.DescendingOrder][self._sort_order.currentIndex()] @sort_order.setter def sort_order(self, val): - self._sort_order.setCurrentIndex({Qt.AscendingOrder:0}.get(val, 1)) + self._sort_order.setCurrentIndex({Qt.SortOrder.AscendingOrder:0}.get(val, 1)) def update_summary(self): self.summary.setText(_('{0} rules, {1} unused').format(self.model.rowCount(), self.model.num_unused)) @@ -1084,7 +1084,7 @@ class CSSWidget(QWidget): def save(self): self.save_state('sort-on-counts', self.counts_button.isChecked()) - self.save_state('sort-ascending', self.sort_order == Qt.AscendingOrder) + self.save_state('sort-ascending', self.sort_order == Qt.SortOrder.AscendingOrder) def resort(self, *args): self.model.sort_on_count = self.counts_button.isChecked() @@ -1096,7 +1096,7 @@ class CSSWidget(QWidget): w = csv_writer(buf) w.writerow([_('Style Rule'), _('Number of matches')]) for r in range(self.proxy.rowCount()): - entry = self.proxy.mapToSource(self.proxy.index(r, 0)).data(Qt.UserRole) + entry = self.proxy.mapToSource(self.proxy.index(r, 0)).data(Qt.ItemDataRole.UserRole) w.writerow([entry.rule.selector, entry.count]) return buf.getvalue() @@ -1174,7 +1174,7 @@ class ClassesModel(CSSRulesModel): return entry.matched_rules return entry - def data(self, index, role=Qt.DisplayRole): + def data(self, index, role=Qt.ItemDataRole.DisplayRole): if role == SORT_ROLE: entry = self.index_to_entry(index) if isinstance(entry, ClassEntry): @@ -1185,7 +1185,7 @@ class ClassesModel(CSSRulesModel): return entry.line_number if isinstance(entry, CSSRule): return entry.location.file_name - elif role == Qt.DisplayRole: + elif role == Qt.ItemDataRole.DisplayRole: entry = self.index_to_entry(index) if isinstance(entry, ClassEntry): return '[%{}d] %s'.format(self.num_size) % (entry.num_of_matches, entry.cls) @@ -1195,9 +1195,9 @@ class ClassesModel(CSSRulesModel): return '%s @ %s' % (entry.tag, entry.line_number) elif isinstance(entry, CSSRule): return '%s @ %s:%s' % (entry.selector, entry.location.file_name, entry.location.line) - elif role == Qt.UserRole: + elif role == Qt.ItemDataRole.UserRole: return self.index_to_entry(index) - elif role == Qt.FontRole: + elif role == Qt.ItemDataRole.FontRole: entry = self.index_to_entry(index) if isinstance(entry, ClassEntry): return self.main_font @@ -1242,7 +1242,7 @@ class ClassesWidget(CSSWidget): w = csv_writer(buf) w.writerow([_('Class'), _('Number of matches')]) for r in range(self.proxy.rowCount()): - entry = self.proxy.mapToSource(self.proxy.index(r, 0)).data(Qt.UserRole) + entry = self.proxy.mapToSource(self.proxy.index(r, 0)).data(Qt.ItemDataRole.UserRole) w.writerow([entry.cls, entry.num_of_matches]) return buf.getvalue() @@ -1340,7 +1340,7 @@ class ReportsWidget(QWidget): st = time.time() self.stack.widget(i)(data) if DEBUG: - category = self.reports.item(i).data(Qt.DisplayRole) + category = self.reports.item(i).data(Qt.ItemDataRole.DisplayRole) print('Widget time for %12s: %.2fs seconds' % (category, time.time() - st)) def save(self): @@ -1351,7 +1351,7 @@ class ReportsWidget(QWidget): def to_csv(self): w = self.stack.currentWidget() - category = self.reports.currentItem().data(Qt.DisplayRole) + category = self.reports.currentItem().data(Qt.ItemDataRole.DisplayRole) if not hasattr(w, 'to_csv'): return error_dialog(self, _('Not supported'), _( 'Export of %s data is not supported') % category, show=True) @@ -1372,8 +1372,8 @@ class Reports(Dialog): def __init__(self, parent=None): Dialog.__init__(self, _('Reports'), 'reports-dialog', parent=parent) - self.data_gathered.connect(self.display_data, type=Qt.QueuedConnection) - self.setAttribute(Qt.WA_DeleteOnClose, False) + self.data_gathered.connect(self.display_data, type=Qt.ConnectionType.QueuedConnection) + self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, False) self.setWindowIcon(QIcon(I('reports.png'))) def setup_ui(self): @@ -1389,10 +1389,10 @@ class Reports(Dialog): s.addWidget(pw), s.addWidget(r) pw.l = l = QVBoxLayout(pw) self.pi = pi = ProgressIndicator(self, 256) - l.addStretch(1), l.addWidget(pi, alignment=Qt.AlignHCenter), l.addSpacing(10) + l.addStretch(1), l.addWidget(pi, alignment=Qt.AlignmentFlag.AlignHCenter), l.addSpacing(10) pw.la = la = QLabel(_('Gathering data, please wait...')) la.setStyleSheet('QLabel { font-size: 30pt; font-weight: bold }') - l.addWidget(la, alignment=Qt.AlignHCenter), l.addStretch(1) + l.addWidget(la, alignment=Qt.AlignmentFlag.AlignHCenter), l.addStretch(1) self.bb.setStandardButtons(self.bb.Close) self.refresh_button = b = self.bb.addButton(_('&Refresh'), self.bb.ActionRole) @@ -1416,7 +1416,7 @@ class Reports(Dialog): def refresh(self): self.wait_stack.setCurrentIndex(0) - self.setCursor(Qt.BusyCursor) + self.setCursor(Qt.CursorShape.BusyCursor) self.pi.startAnimation() self.refresh_starting.emit() t = Thread(name='GatherReportData', target=self.gather_data) diff --git a/src/calibre/gui2/tweak_book/save.py b/src/calibre/gui2/tweak_book/save.py index 01c7718302..2de36fa06c 100644 --- a/src/calibre/gui2/tweak_book/save.py +++ b/src/calibre/gui2/tweak_book/save.py @@ -137,8 +137,8 @@ class SaveManager(QObject): t.daemon = True t.start() self.status_widget = w = SaveWidget(parent) - self.start_save.connect(w.start, type=Qt.QueuedConnection) - self.save_done.connect(w.stop, type=Qt.QueuedConnection) + self.start_save.connect(w.start, type=Qt.ConnectionType.QueuedConnection) + self.save_done.connect(w.stop, type=Qt.ConnectionType.QueuedConnection) def schedule(self, tdir, container): self.count += 1 diff --git a/src/calibre/gui2/tweak_book/search.py b/src/calibre/gui2/tweak_book/search.py index c8136e5fa7..55dc5014cf 100644 --- a/src/calibre/gui2/tweak_book/search.py +++ b/src/calibre/gui2/tweak_book/search.py @@ -254,7 +254,7 @@ class SearchWidget(QWidget): l.setContentsMargins(0, 0, right, 0) self.fl = fl = QLabel(_('&Find:')) - fl.setAlignment(Qt.AlignRight | Qt.AlignCenter) + fl.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignCenter) self.find_text = ft = HistoryBox(self, _('Clear search &history')) ft.save_search.connect(self.save_search) ft.show_saved_searches.connect(self.show_saved_searches) @@ -266,7 +266,7 @@ class SearchWidget(QWidget): l.setColumnStretch(1, 10) self.rl = rl = QLabel(_('&Replace:')) - rl.setAlignment(Qt.AlignRight | Qt.AlignCenter) + rl.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignCenter) self.replace_text = rt = HistoryBox(self, _('Clear replace &history')) rt.save_search.connect(self.save_search) rt.show_saved_searches.connect(self.show_saved_searches) @@ -279,7 +279,7 @@ class SearchWidget(QWidget): l.addLayout(rs2, 1, 1) self.rl2 = rl2 = QLabel(_('F&unction:')) - rl2.setAlignment(Qt.AlignRight | Qt.AlignCenter) + rl2.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignCenter) self.functions = fb = FunctionBox(self, show_saved_search_actions=True) fb.show_saved_searches.connect(self.show_saved_searches) fb.save_search.connect(self.save_search) @@ -289,7 +289,7 @@ class SearchWidget(QWidget): rs2.addWidget(w) self.fhl = fhl = QHBoxLayout(w) fhl.setContentsMargins(0, 0, 0, 0) - fhl.addWidget(fb, stretch=10, alignment=Qt.AlignVCenter) + fhl.addWidget(fb, stretch=10, alignment=Qt.AlignmentFlag.AlignVCenter) self.ae_func = b = QPushButton(_('Create/&edit'), self) b.clicked.connect(self.edit_function) b.setToolTip(_('Create a new function, or edit an existing function')) @@ -313,7 +313,7 @@ class SearchWidget(QWidget): self.ml = ml = QLabel(_('&Mode:')) self.ol = ol = FlowLayout() - ml.setAlignment(Qt.AlignRight | Qt.AlignVCenter) + ml.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter) l.addWidget(ml, 2, 0) l.addLayout(ol, 2, 1, 1, 3) self.mode_box = mb = ModeBox(self) @@ -474,7 +474,7 @@ class SearchPanel(QWidget): # {{{ l.setContentsMargins(0, 0, 0, 0) self.t = t = QToolBar(self) l.addWidget(t) - t.setOrientation(Qt.Vertical) + t.setOrientation(Qt.Orientation.Vertical) t.setIconSize(QSize(12, 12)) t.setMovable(False) t.setFloatable(False) @@ -496,7 +496,7 @@ class SearchPanel(QWidget): # {{{ def show_panel(self): self.setVisible(True) - self.widget.find_text.setFocus(Qt.OtherFocusReason) + self.widget.find_text.setFocus(Qt.FocusReason.OtherFocusReason) le = self.widget.find_text.lineEdit() le.setSelection(0, le.maxLength()) @@ -518,7 +518,7 @@ class SearchPanel(QWidget): # {{{ self.where_before_marked = None def keyPressEvent(self, ev): - if ev.key() == Qt.Key_Escape: + if ev.key() == Qt.Key.Key_Escape: self.hide_panel() ev.accept() else: @@ -533,7 +533,7 @@ class SearchDescription(QScrollArea): self.label = QLabel(' \n \n ') self.setWidget(self.label) self.setWidgetResizable(True) - self.label.setTextFormat(Qt.PlainText) + self.label.setTextFormat(Qt.TextFormat.PlainText) self.label.setWordWrap(True) self.set_text = self.label.setText @@ -549,14 +549,14 @@ class SearchesModel(QAbstractListModel): return len(self.filtered_searches) def supportedDropActions(self): - return Qt.MoveAction + return Qt.DropAction.MoveAction def flags(self, index): ans = QAbstractListModel.flags(self, index) if index.isValid(): - ans |= Qt.ItemIsDragEnabled + ans |= Qt.ItemFlag.ItemIsDragEnabled else: - ans |= Qt.ItemIsDropEnabled + ans |= Qt.ItemFlag.ItemIsDropEnabled return ans def mimeTypes(self): @@ -574,7 +574,7 @@ class SearchesModel(QAbstractListModel): return ans def dropMimeData(self, data, action, row, column, parent): - if parent.isValid() or action != Qt.MoveAction or not data.hasFormat('x-calibre/searches-rows') or not self.filtered_searches: + if parent.isValid() or action != Qt.DropAction.MoveAction or not data.hasFormat('x-calibre/searches-rows') or not self.filtered_searches: return False rows = sorted(map(int, bytes(bytearray(data.data('x-calibre/searches-rows'))).decode('ascii').split(','))) moved_searches = [self.searches[self.filtered_searches[r]] for r in rows] @@ -606,14 +606,14 @@ class SearchesModel(QAbstractListModel): def data(self, index, role): try: - if role == Qt.DisplayRole: + if role == Qt.ItemDataRole.DisplayRole: search = self.searches[self.filtered_searches[index.row()]] return search['name'] - if role == Qt.ToolTipRole: + if role == Qt.ItemDataRole.ToolTipRole: search = self.searches[self.filtered_searches[index.row()]] tt = '\n'.join((search['find'], search['replace'])) return tt - if role == Qt.UserRole: + if role == Qt.ItemDataRole.UserRole: search = self.searches[self.filtered_searches[index.row()]] return (self.filtered_searches[index.row()], search) except IndexError: @@ -732,7 +732,7 @@ class EditSearch(QFrame): # {{{ self.h2 = h = QHBoxLayout() l.addLayout(h) self.mode_box = m = ModeBox(self) - m.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) + m.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) self.la4 = la = QLabel(_('&Mode:')) la.setBuddy(m) h.addWidget(la), h.addWidget(m), h.addStretch(2) @@ -794,7 +794,7 @@ class EditSearch(QFrame): # {{{ self.done.emit(True) def keyPressEvent(self, ev): - if ev.key() == Qt.Key_Escape: + if ev.key() == Qt.Key.Key_Escape: self.abort_editing() ev.accept() return @@ -929,7 +929,7 @@ class SavedSearches(QWidget): b.setToolTip(tooltip or '') if action: b.setObjectName(action) - b.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) + b.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Fixed) return b mulmsg = '\n\n' + _('The entries are tried in order until the first one matches.') @@ -947,14 +947,14 @@ class SavedSearches(QWidget): connect_lambda(b.clicked, self, lambda self: self.run_search(self.sender().objectName())) self.d1 = d = QFrame(self) - d.setFrameStyle(QFrame.HLine) + d.setFrameStyle(QFrame.Shape.HLine) v.addWidget(d) self.h3 = h = QHBoxLayout() self.upb = b = QToolButton(self) self.move_up_action = a = QAction(self) a.setShortcut(QKeySequence('Alt+Up')) - b.setIcon(QIcon(I('arrow-up.png'))), b.setToolTip(_('Move selected entries up') + ' [%s]' % a.shortcut().toString(QKeySequence.NativeText)) + b.setIcon(QIcon(I('arrow-up.png'))), b.setToolTip(_('Move selected entries up') + ' [%s]' % a.shortcut().toString(QKeySequence.SequenceFormat.NativeText)) connect_lambda(a.triggered, self, lambda self: self.move_entry(-1)) self.searches.addAction(a) connect_lambda(b.clicked, self, lambda self: self.move_entry(-1)) @@ -962,7 +962,7 @@ class SavedSearches(QWidget): self.dnb = b = QToolButton(self) self.move_down_action = a = QAction(self) a.setShortcut(QKeySequence('Alt+Down')) - b.setIcon(QIcon(I('arrow-down.png'))), b.setToolTip(_('Move selected entries down') + ' [%s]' % a.shortcut().toString(QKeySequence.NativeText)) + b.setIcon(QIcon(I('arrow-down.png'))), b.setToolTip(_('Move selected entries down') + ' [%s]' % a.shortcut().toString(QKeySequence.SequenceFormat.NativeText)) connect_lambda(a.triggered, self, lambda self: self.move_entry(1)) self.searches.addAction(a) connect_lambda(b.clicked, self, lambda self: self.move_entry(1)) @@ -982,7 +982,7 @@ class SavedSearches(QWidget): v.addWidget(b) self.d2 = d = QFrame(self) - d.setFrameStyle(QFrame.HLine) + d.setFrameStyle(QFrame.Shape.HLine) v.addWidget(d) self.where_box = wb = WhereBox(self, emphasize=True) @@ -998,7 +998,7 @@ class SavedSearches(QWidget): v.addWidget(wr) self.d3 = d = QFrame(self) - d.setFrameStyle(QFrame.HLine) + d.setFrameStyle(QFrame.Shape.HLine) v.addWidget(d) self.description = d = SearchDescription(self) @@ -1017,7 +1017,7 @@ class SavedSearches(QWidget): m.addAction(_('Copy to search panel'), lambda : QTimer.singleShot(0, self.copy_to_search_panel)) b.setMenu(m) - self.searches.setFocus(Qt.OtherFocusReason) + self.searches.setFocus(Qt.FocusReason.OtherFocusReason) @property def state(self): @@ -1106,7 +1106,7 @@ class SavedSearches(QWidget): seen.add(index.row()) search = SearchWidget.DEFAULT_STATE.copy() del search['mode'] - search_index, s = index.data(Qt.UserRole) + search_index, s = index.data(Qt.ItemDataRole.UserRole) search.update(s) fill_in_search(search) searches.append(search) @@ -1159,10 +1159,10 @@ class SavedSearches(QWidget): return error_dialog(self, _('Cannot edit'), _( 'Cannot edit search - no search selected.'), show=True) if not self.editing_search: - search_index, search = index.data(Qt.UserRole) + search_index, search = index.data(Qt.ItemDataRole.UserRole) self.edit_search_widget.show_search(search=search, search_index=search_index) self.stack.setCurrentIndex(1) - self.edit_search_widget.find.setFocus(Qt.OtherFocusReason) + self.edit_search_widget.find.setFocus(Qt.FocusReason.OtherFocusReason) def remove_search(self): if self.editing_search: @@ -1178,7 +1178,7 @@ class SavedSearches(QWidget): return self.edit_search_widget.show_search() self.stack.setCurrentIndex(1) - self.edit_search_widget.search_name.setFocus(Qt.OtherFocusReason) + self.edit_search_widget.search_name.setFocus(Qt.FocusReason.OtherFocusReason) def _add_search(self): self.model.add_searches() @@ -1193,14 +1193,14 @@ class SavedSearches(QWidget): return self.edit_search_widget.show_search(state=state) self.stack.setCurrentIndex(1) - self.edit_search_widget.search_name.setFocus(Qt.OtherFocusReason) + self.edit_search_widget.search_name.setFocus(Qt.FocusReason.OtherFocusReason) def show_details(self): self.description.set_text(' \n \n ') i = self.searches.currentIndex() if i.isValid(): try: - search_index, search = i.data(Qt.UserRole) + search_index, search = i.data(Qt.ItemDataRole.UserRole) except TypeError: return # no saved searches cs = '✓' if search.get('case_sensitive', SearchWidget.DEFAULT_STATE['case_sensitive']) else '✗' @@ -1243,7 +1243,7 @@ class SavedSearches(QWidget): def copy_to_search_panel(self): ci = self.searches.selectionModel().currentIndex() if ci and ci.isValid(): - search = ci.data(Qt.UserRole)[-1] + search = ci.data(Qt.ItemDataRole.UserRole)[-1] self.copy_search_to_search_panel.emit(search) def export_searches(self, all=True): @@ -1255,7 +1255,7 @@ class SavedSearches(QWidget): else: searches = [] for index in self.searches.selectionModel().selectedIndexes(): - search = index.data(Qt.UserRole)[-1] + search = index.data(Qt.ItemDataRole.UserRole)[-1] searches.append(search.copy()) if not searches: return error_dialog(self, _('No searches'), _( diff --git a/src/calibre/gui2/tweak_book/spell.py b/src/calibre/gui2/tweak_book/spell.py index 436d3ae81c..2e680856d2 100644 --- a/src/calibre/gui2/tweak_book/spell.py +++ b/src/calibre/gui2/tweak_book/spell.py @@ -100,11 +100,11 @@ class AddDictionary(QDialog): # {{{ n.setPlaceholderText(_('Choose a nickname for this dictionary')) l.addRow(_('&Nickname:'), n) - 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) - b.setFocus(Qt.OtherFocusReason) + b.setFocus(Qt.FocusReason.OtherFocusReason) def choose_file(self): path = choose_files(self, 'choose-dict-for-import', _('Choose OXT Dictionary'), filters=[ @@ -163,12 +163,12 @@ class UserWordList(QListWidget): words = [] for item in (self.item(i) for i in range(self.count())): if item.isSelected(): - words.append(item.data(Qt.UserRole)[0]) + words.append(item.data(Qt.ItemDataRole.UserRole)[0]) if words: QApplication.clipboard().setText('\n'.join(words)) def keyPressEvent(self, ev): - if ev == QKeySequence.Copy: + if ev == QKeySequence.StandardKey.Copy: self.copy_to_clipboard() ev.accept() return @@ -241,9 +241,9 @@ class ManageUserDictionaries(Dialog): self.dictionaries.clear() for dic in sorted(dictionaries.all_user_dictionaries, key=lambda d:sort_key(d.name)): i = QListWidgetItem(dic.name, self.dictionaries) - i.setData(Qt.UserRole, dic) + i.setData(Qt.ItemDataRole.UserRole, dic) if dic.is_active: - i.setData(Qt.FontRole, self.emph_font) + i.setData(Qt.ItemDataRole.FontRole, self.emph_font) if current == dic.name: self.dictionaries.setCurrentItem(i) if current is None and self.dictionaries.count() > 0: @@ -294,7 +294,7 @@ class ManageUserDictionaries(Dialog): d = self.dictionaries.currentItem() if d is None: return - return d.data(Qt.UserRole) + return d.data(Qt.ItemDataRole.UserRole) def active_toggled(self): d = self.current_dictionary @@ -302,8 +302,8 @@ class ManageUserDictionaries(Dialog): dictionaries.mark_user_dictionary_as_active(d.name, self.is_active.isChecked()) self.dictionaries_changed = True for item in (self.dictionaries.item(i) for i in range(self.dictionaries.count())): - d = item.data(Qt.UserRole) - item.setData(Qt.FontRole, self.emph_font if d.is_active else None) + d = item.data(Qt.ItemDataRole.UserRole) + item.setData(Qt.ItemDataRole.FontRole, self.emph_font if d.is_active else None) def show_current_dictionary(self, *args): d = self.current_dictionary @@ -316,7 +316,7 @@ class ManageUserDictionaries(Dialog): self.words.clear() for word, lang in sorted(d.words, key=lambda x:sort_key(x[0])): i = QListWidgetItem('%s [%s]' % (word, get_language(lang)), self.words) - i.setData(Qt.UserRole, (word, lang)) + i.setData(Qt.ItemDataRole.UserRole, (word, lang)) def add_word(self): d = QDialog(self) @@ -328,7 +328,7 @@ class ManageUserDictionaries(Dialog): d.loc = loc = LanguagesEdit(parent=d) l.addRow(_('&Language:'), d.loc) loc.lang_codes = [canonicalize_lang(get_lang())] - d.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel) + d.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel) bb.accepted.connect(d.accept), bb.rejected.connect(d.reject) l.addRow(bb) if d.exec_() != d.Accepted: @@ -365,7 +365,7 @@ class ManageUserDictionaries(Dialog): if lc: le.lang_codes = [lc] l.addRow(_('&Language:'), le) - d.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel) + d.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel) l.addRow(bb) bb.accepted.connect(d.accept), bb.rejected.connect(d.reject) @@ -384,7 +384,7 @@ class ManageUserDictionaries(Dialog): self.dictionaries_changed = True def remove_word(self): - words = {i.data(Qt.UserRole) for i in self.words.selectedItems()} + words = {i.data(Qt.ItemDataRole.UserRole) for i in self.words.selectedItems()} if words: kwords = [(w, DictionaryLocale(l, None)) for w, l in words] d = self.current_dictionary @@ -396,7 +396,7 @@ class ManageUserDictionaries(Dialog): def find_word(self, word, lang): key = (word, lang) for i in range(self.words.count()): - if self.words.item(i).data(Qt.UserRole) == key: + if self.words.item(i).data(Qt.ItemDataRole.UserRole) == key: return i return -1 @@ -443,7 +443,7 @@ class ManageDictionaries(Dialog): # {{{ s.addWidget(w) self.dictionaries = d = QTreeWidget(self) - d.itemChanged.connect(self.data_changed, type=Qt.QueuedConnection) + d.itemChanged.connect(self.data_changed, type=Qt.ConnectionType.QueuedConnection) self.build_dictionaries() d.setCurrentIndex(d.model().index(0, 0)) d.header().close() @@ -474,7 +474,7 @@ class ManageDictionaries(Dialog): # {{{ def data_changed(self, item, column): if column == 0 and item.type() == DICTIONARY: - d = item.data(0, Qt.UserRole) + d = item.data(0, Qt.ItemDataRole.UserRole) if not d.builtin and unicode_type(item.text(0)) != d.name: rename_dictionary(d, unicode_type(item.text(0))) @@ -493,14 +493,14 @@ class ManageDictionaries(Dialog): # {{{ for lc in sorted(languages, key=lambda x:sort_key(calibre_langcode_to_name(x))): i = QTreeWidgetItem(self.dictionaries, LANG) i.setText(0, calibre_langcode_to_name(lc)) - i.setData(0, Qt.UserRole, lc) + i.setData(0, Qt.ItemDataRole.UserRole, lc) best_country = getattr(best_locale_for_language(lc), 'countrycode', None) for countrycode in sorted(languages[lc], key=lambda x: country_map()['names'].get(x, x)): j = QTreeWidgetItem(i, COUNTRY) j.setText(0, country_map()['names'].get(countrycode, countrycode)) - j.setData(0, Qt.UserRole, countrycode) + j.setData(0, Qt.ItemDataRole.UserRole, countrycode) if countrycode == best_country: - j.setData(0, Qt.FontRole, bf) + j.setData(0, Qt.ItemDataRole.FontRole, bf) pd = get_dictionary(DictionaryLocale(lc, countrycode)) for dictionary in sorted(languages[lc][countrycode], key=lambda d:(d.name or '')): k = QTreeWidgetItem(j, DICTIONARY) @@ -508,11 +508,11 @@ class ManageDictionaries(Dialog): # {{{ if dictionary.primary_locale.countrycode: pl += '-' + dictionary.primary_locale.countrycode.upper() k.setText(0, dictionary.name or (_('').format(pl))) - k.setData(0, Qt.UserRole, dictionary) + k.setData(0, Qt.ItemDataRole.UserRole, dictionary) if dictionary.name: - k.setFlags(k.flags() | Qt.ItemIsEditable) + k.setFlags(k.flags() | Qt.ItemFlag.ItemIsEditable) if pd == dictionary: - k.setData(0, Qt.FontRole, itf) + k.setData(0, Qt.ItemDataRole.FontRole, itf) self.dictionaries.expandAll() @@ -524,7 +524,7 @@ class ManageDictionaries(Dialog): # {{{ def remove_dictionary(self): item = self.dictionaries.currentItem() if item is not None and item.type() == DICTIONARY: - dic = item.data(0, Qt.UserRole) + dic = item.data(0, Qt.ItemDataRole.UserRole) if not dic.builtin: remove_dictionary(dic) self.build_dictionaries(reread=True) @@ -554,7 +554,7 @@ class ManageDictionaries(Dialog): # {{{ def init_country(self, item): pc = self.pcb - font = item.data(0, Qt.FontRole) + font = item.data(0, Qt.ItemDataRole.FontRole) preferred = bool(font and font.bold()) pc.setText((_( 'This is already the preferred variant for the {1} language') if preferred else _( @@ -567,31 +567,31 @@ class ManageDictionaries(Dialog): # {{{ bf = QFont(self.dictionaries.font()) bf.setBold(True) for x in (item.parent().child(i) for i in range(item.parent().childCount())): - x.setData(0, Qt.FontRole, bf if x is item else None) - lc = unicode_type(item.parent().data(0, Qt.UserRole)) + x.setData(0, Qt.ItemDataRole.FontRole, bf if x is item else None) + lc = unicode_type(item.parent().data(0, Qt.ItemDataRole.UserRole)) pl = dprefs['preferred_locales'] - pl[lc] = '%s-%s' % (lc, unicode_type(item.data(0, Qt.UserRole))) + pl[lc] = '%s-%s' % (lc, unicode_type(item.data(0, Qt.ItemDataRole.UserRole))) dprefs['preferred_locales'] = pl def init_dictionary(self, item): saf = self.fb - font = item.data(0, Qt.FontRole) + font = item.data(0, Qt.ItemDataRole.FontRole) preferred = bool(font and font.italic()) saf.setText((_( 'This is already the preferred dictionary') if preferred else _('Use this as the preferred dictionary'))) saf.setEnabled(not preferred) - self.remove_dictionary_button.setEnabled(not item.data(0, Qt.UserRole).builtin) + self.remove_dictionary_button.setEnabled(not item.data(0, Qt.ItemDataRole.UserRole).builtin) def set_favorite(self): item = self.dictionaries.currentItem() bf = QFont(self.dictionaries.font()) bf.setItalic(True) for x in (item.parent().child(i) for i in range(item.parent().childCount())): - x.setData(0, Qt.FontRole, bf if x is item else None) - cc = unicode_type(item.parent().data(0, Qt.UserRole)) - lc = unicode_type(item.parent().parent().data(0, Qt.UserRole)) - d = item.data(0, Qt.UserRole) + x.setData(0, Qt.ItemDataRole.FontRole, bf if x is item else None) + cc = unicode_type(item.parent().data(0, Qt.ItemDataRole.UserRole)) + lc = unicode_type(item.parent().parent().data(0, Qt.ItemDataRole.UserRole)) + d = item.data(0, Qt.ItemDataRole.UserRole) locale = '%s-%s' % (lc, cc) pl = dprefs['preferred_dictionaries'] pl[locale] = d.id @@ -635,27 +635,27 @@ class WordsModel(QAbstractTableModel): self.items =[] self.endResetModel() - def headerData(self, section, orientation, role=Qt.DisplayRole): - if orientation == Qt.Horizontal: - if role == Qt.DisplayRole: + def headerData(self, section, orientation, role=Qt.ItemDataRole.DisplayRole): + if orientation == Qt.Orientation.Horizontal: + if role == Qt.ItemDataRole.DisplayRole: try: return self.headers[section] except IndexError: pass - elif role == Qt.InitialSortOrderRole: - return Qt.DescendingOrder if section == 1 else Qt.AscendingOrder + elif role == Qt.ItemDataRole.InitialSortOrderRole: + return Qt.SortOrder.DescendingOrder if section == 1 else Qt.SortOrder.AscendingOrder def misspelled_text(self, w): if self.spell_map[w]: return _('Ignored') if dictionaries.is_word_ignored(*w) else '' return '✓' - def data(self, index, role=Qt.DisplayRole): + def data(self, index, role=Qt.ItemDataRole.DisplayRole): try: word, locale = self.items[index.row()] except IndexError: return - if role == Qt.DisplayRole: + if role == Qt.ItemDataRole.DisplayRole: col = index.column() if col == 0: return word @@ -669,11 +669,11 @@ class WordsModel(QAbstractTableModel): return pl if col == 3: return self.misspelled_text((word, locale)) - if role == Qt.TextAlignmentRole: - return Qt.AlignVCenter | (Qt.AlignLeft if index.column() == 0 else Qt.AlignHCenter) + if role == Qt.ItemDataRole.TextAlignmentRole: + return Qt.AlignmentFlag.AlignVCenter | (Qt.AlignmentFlag.AlignLeft if index.column() == 0 else Qt.AlignmentFlag.AlignHCenter) - def sort(self, column, order=Qt.AscendingOrder): - reverse = order != Qt.AscendingOrder + def sort(self, column, order=Qt.SortOrder.AscendingOrder): + reverse = order != Qt.SortOrder.AscendingOrder self.sort_on = (column, reverse) self.beginResetModel() self.do_sort() @@ -852,7 +852,7 @@ class WordsView(QTableView): self.verticalHeader().close() def keyPressEvent(self, ev): - if ev == QKeySequence.Copy: + if ev == QKeySequence.StandardKey.Copy: self.copy_to_clipboard() ev.accept() return @@ -927,8 +927,8 @@ class SpellCheck(Dialog): t.timeout.connect(self.do_current_word_changed) t.setSingleShot(True), t.setInterval(100) Dialog.__init__(self, _('Check spelling'), 'spell-check', parent) - self.work_finished.connect(self.work_done, type=Qt.QueuedConnection) - self.setAttribute(Qt.WA_DeleteOnClose, False) + self.work_finished.connect(self.work_done, type=Qt.ConnectionType.QueuedConnection) + self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, False) self.undo_cache = {} def setup_ui(self): @@ -953,12 +953,12 @@ class SpellCheck(Dialog): self.progress = p = QWidget(self) s.addWidget(p) p.l = l = QVBoxLayout(p) - l.setAlignment(Qt.AlignCenter) + l.setAlignment(Qt.AlignmentFlag.AlignCenter) self.progress_indicator = pi = ProgressIndicator(self, 256) - l.addWidget(pi, alignment=Qt.AlignHCenter), l.addSpacing(10) + l.addWidget(pi, alignment=Qt.AlignmentFlag.AlignHCenter), l.addSpacing(10) p.la = la = QLabel(_('Checking, please wait...')) la.setStyleSheet('QLabel { font-size: 30pt; font-weight: bold }') - l.addWidget(la, alignment=Qt.AlignHCenter) + l.addWidget(la, alignment=Qt.AlignmentFlag.AlignHCenter) self.main = m = QWidget(self) s.addWidget(m) @@ -1054,7 +1054,7 @@ class SpellCheck(Dialog): self.main.l.addLayout(h), h.addWidget(s), h.addWidget(om), h.addWidget(cs), h.addWidget(cs2) 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 Dialog.keyPressEvent(self, ev) @@ -1164,7 +1164,7 @@ class SpellCheck(Dialog): def change_to(self, w, new_word): if new_word is None: - self.suggested_word.setFocus(Qt.OtherFocusReason) + self.suggested_word.setFocus(Qt.FocusReason.OtherFocusReason) self.suggested_word.clear() return self.change_requested.emit(w, new_word) @@ -1290,7 +1290,7 @@ class SpellCheck(Dialog): row = 0 col, reverse = self.words_model.sort_on self.words_view.horizontalHeader().setSortIndicator( - col, Qt.DescendingOrder if reverse else Qt.AscendingOrder) + col, Qt.SortOrder.DescendingOrder if reverse else Qt.SortOrder.AscendingOrder) self.update_summary() self.initialize_user_dictionaries() if self.words_model.rowCount() > 0: diff --git a/src/calibre/gui2/tweak_book/text_search.py b/src/calibre/gui2/tweak_book/text_search.py index e63f42a813..b1220095d9 100644 --- a/src/calibre/gui2/tweak_book/text_search.py +++ b/src/calibre/gui2/tweak_book/text_search.py @@ -99,7 +99,7 @@ class TextSearch(QWidget): self.l = l = QVBoxLayout(self) self.la = la = QLabel(_('&Find:')) self.find = ft = HistoryComboBox(self) - ft.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) + ft.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) ft.initialize('tweak_book_text_search_history') la.setBuddy(ft) self.h = h = QHBoxLayout() diff --git a/src/calibre/gui2/tweak_book/toc.py b/src/calibre/gui2/tweak_book/toc.py index b6adc35c6d..4f200d16f5 100644 --- a/src/calibre/gui2/tweak_book/toc.py +++ b/src/calibre/gui2/tweak_book/toc.py @@ -43,7 +43,7 @@ class TOCEditor(QDialog): self.item_edit = ItemEdit(self, tprefs) s.addWidget(self.item_edit) - bb = self.bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel) + bb = self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel) l.addWidget(bb) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) @@ -106,7 +106,7 @@ class TOCEditor(QDialog): uid=self.toc_view.toc_uid) -DEST_ROLE = Qt.UserRole +DEST_ROLE = Qt.ItemDataRole.UserRole FRAG_ROLE = DEST_ROLE + 1 @@ -134,8 +134,8 @@ class TOCViewer(QWidget): self.view.setItemDelegate(self.delegate) self.view.setHeaderHidden(True) self.view.setAnimated(True) - self.view.setContextMenuPolicy(Qt.CustomContextMenu) - self.view.customContextMenuRequested.connect(self.show_context_menu, type=Qt.QueuedConnection) + self.view.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) + self.view.customContextMenuRequested.connect(self.show_context_menu, type=Qt.ConnectionType.QueuedConnection) self.view.itemActivated.connect(self.emit_navigate) self.view.itemPressed.connect(self.item_pressed) set_no_activate_on_click(self.view) @@ -168,7 +168,7 @@ class TOCViewer(QWidget): self.build() def item_pressed(self, item): - if QApplication.mouseButtons() & Qt.LeftButton: + if QApplication.mouseButtons() & Qt.MouseButton.LeftButton: QTimer.singleShot(0, self.emit_navigate) def show_context_menu(self, pos): @@ -213,7 +213,7 @@ class TOCViewer(QWidget): node.setData(0, FRAG_ROLE, child.frag or '') tt = _('File: {0}\nAnchor: {1}').format( child.dest or '', child.frag or _('Top of file')) - node.setData(0, Qt.ToolTipRole, tt) + node.setData(0, Qt.ItemDataRole.ToolTipRole, tt) process_node(child, node) self.view.clear() diff --git a/src/calibre/gui2/tweak_book/ui.py b/src/calibre/gui2/tweak_book/ui.py index e488251d31..04c3efa5d3 100644 --- a/src/calibre/gui2/tweak_book/ui.py +++ b/src/calibre/gui2/tweak_book/ui.py @@ -74,7 +74,7 @@ class Central(QStackedWidget): # {{{ ' it.')) self.addWidget(w) w.setWordWrap(True) - w.setAlignment(Qt.AlignTop | Qt.AlignHCenter) + w.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignHCenter) self.container = c = QWidget(self) self.addWidget(c) @@ -205,12 +205,12 @@ class Central(QStackedWidget): # {{{ def eventFilter(self, obj, event): base = super(Central, self) - if obj is not self.editor_tabs.tabBar() or event.type() != QEvent.MouseButtonPress or event.button() not in (Qt.RightButton, Qt.MidButton): + if obj is not self.editor_tabs.tabBar() or event.type() != QEvent.Type.MouseButtonPress or event.button() not in (Qt.MouseButton.RightButton, Qt.MouseButton.MidButton): return base.eventFilter(obj, event) index = self.editor_tabs.tabBar().tabAt(event.pos()) if index < 0: return base.eventFilter(obj, event) - if event.button() == Qt.MidButton: + if event.button() == Qt.MouseButton.MidButton: self._close_requested(index) ed = self.editor_tabs.widget(index) if ed is not None: @@ -273,12 +273,12 @@ class MessagePopup(QLabel): def __init__(self, parent): QLabel.__init__(self, parent) - self.setFocusPolicy(Qt.NoFocus) + self.setFocusPolicy(Qt.FocusPolicy.NoFocus) if QApplication.instance().is_dark_theme: c = builtin_colors_dark['green'] else: c = builtin_colors_light['green'] - self.color = self.palette().color(QPalette.WindowText).name() + self.color = self.palette().color(QPalette.ColorRole.WindowText).name() bg = QColor(c).getRgb() self.setStyleSheet(f'''QLabel {{ background-color: rgba({bg[0]}, {bg[1]}, {bg[2]}, 0.85); @@ -795,61 +795,61 @@ class Main(MainWindow): return d d = create(_('File browser'), 'files-browser') - d.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) + d.setAllowedAreas(Qt.DockWidgetArea.LeftDockWidgetArea | Qt.DockWidgetArea.RightDockWidgetArea) self.file_list = FileListWidget(d) d.setWidget(self.file_list) - self.addDockWidget(Qt.LeftDockWidgetArea, d) + self.addDockWidget(Qt.DockWidgetArea.LeftDockWidgetArea, d) d = create(_('File preview'), 'preview') - d.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) + d.setAllowedAreas(Qt.DockWidgetArea.LeftDockWidgetArea | Qt.DockWidgetArea.RightDockWidgetArea) self.preview = Preview(d) d.setWidget(self.preview) - self.addDockWidget(Qt.RightDockWidgetArea, d) + self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, d) d = create(_('Live CSS'), 'live-css') - d.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea | Qt.BottomDockWidgetArea | Qt.TopDockWidgetArea) + d.setAllowedAreas(Qt.DockWidgetArea.LeftDockWidgetArea | Qt.DockWidgetArea.RightDockWidgetArea | Qt.DockWidgetArea.BottomDockWidgetArea | Qt.DockWidgetArea.TopDockWidgetArea) self.live_css = LiveCSS(self.preview, parent=d) d.setWidget(self.live_css) - self.addDockWidget(Qt.RightDockWidgetArea, d) + self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, d) d.close() # Hidden by default d = create(_('Check book'), 'check-book') - d.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea | Qt.BottomDockWidgetArea | Qt.TopDockWidgetArea) + d.setAllowedAreas(Qt.DockWidgetArea.LeftDockWidgetArea | Qt.DockWidgetArea.RightDockWidgetArea | Qt.DockWidgetArea.BottomDockWidgetArea | Qt.DockWidgetArea.TopDockWidgetArea) d.setWidget(self.check_book) - self.addDockWidget(Qt.TopDockWidgetArea, d) + self.addDockWidget(Qt.DockWidgetArea.TopDockWidgetArea, d) d.close() # By default the check window is closed d = create(_('Inspector'), 'inspector') - d.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea | Qt.BottomDockWidgetArea | Qt.TopDockWidgetArea) + d.setAllowedAreas(Qt.DockWidgetArea.LeftDockWidgetArea | Qt.DockWidgetArea.RightDockWidgetArea | Qt.DockWidgetArea.BottomDockWidgetArea | Qt.DockWidgetArea.TopDockWidgetArea) d.setWidget(self.preview.inspector) self.preview.inspector.setParent(d) - self.addDockWidget(Qt.BottomDockWidgetArea, d) + self.addDockWidget(Qt.DockWidgetArea.BottomDockWidgetArea, d) d.close() # By default the inspector window is closed QTimer.singleShot(10, self.preview.inspector.connect_to_dock) d = create(_('Table of Contents'), 'toc-viewer') - d.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea | Qt.BottomDockWidgetArea | Qt.TopDockWidgetArea) + d.setAllowedAreas(Qt.DockWidgetArea.LeftDockWidgetArea | Qt.DockWidgetArea.RightDockWidgetArea | Qt.DockWidgetArea.BottomDockWidgetArea | Qt.DockWidgetArea.TopDockWidgetArea) d.setWidget(self.toc_view) - self.addDockWidget(Qt.LeftDockWidgetArea, d) + self.addDockWidget(Qt.DockWidgetArea.LeftDockWidgetArea, d) d.close() # Hidden by default d = create(_('Text search'), 'text-search') - d.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea | Qt.BottomDockWidgetArea | Qt.TopDockWidgetArea) + d.setAllowedAreas(Qt.DockWidgetArea.LeftDockWidgetArea | Qt.DockWidgetArea.RightDockWidgetArea | Qt.DockWidgetArea.BottomDockWidgetArea | Qt.DockWidgetArea.TopDockWidgetArea) d.setWidget(self.text_search) - self.addDockWidget(Qt.LeftDockWidgetArea, d) + self.addDockWidget(Qt.DockWidgetArea.LeftDockWidgetArea, d) d.close() # Hidden by default d = create(_('Checkpoints'), 'checkpoints') - d.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea | Qt.BottomDockWidgetArea | Qt.TopDockWidgetArea) + d.setAllowedAreas(Qt.DockWidgetArea.LeftDockWidgetArea | Qt.DockWidgetArea.RightDockWidgetArea | Qt.DockWidgetArea.BottomDockWidgetArea | Qt.DockWidgetArea.TopDockWidgetArea) self.checkpoints = CheckpointView(self.boss.global_undo, parent=d) d.setWidget(self.checkpoints) - self.addDockWidget(Qt.LeftDockWidgetArea, d) + self.addDockWidget(Qt.DockWidgetArea.LeftDockWidgetArea, d) d.close() # Hidden by default d = create(_('Saved searches'), 'saved-searches') - d.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea | Qt.BottomDockWidgetArea | Qt.TopDockWidgetArea) + d.setAllowedAreas(Qt.DockWidgetArea.LeftDockWidgetArea | Qt.DockWidgetArea.RightDockWidgetArea | Qt.DockWidgetArea.BottomDockWidgetArea | Qt.DockWidgetArea.TopDockWidgetArea) d.setWidget(self.saved_searches) - self.addDockWidget(Qt.LeftDockWidgetArea, d) + self.addDockWidget(Qt.DockWidgetArea.LeftDockWidgetArea, d) d.close() # Hidden by default def resizeEvent(self, ev): diff --git a/src/calibre/gui2/tweak_book/undo.py b/src/calibre/gui2/tweak_book/undo.py index be77d80ad0..b81a085cee 100644 --- a/src/calibre/gui2/tweak_book/undo.py +++ b/src/calibre/gui2/tweak_book/undo.py @@ -44,14 +44,14 @@ class GlobalUndoHistory(QAbstractListModel): def rowCount(self, parent=ROOT): return len(self.states) - def data(self, index, role=Qt.DisplayRole): - if role == Qt.DisplayRole: + def data(self, index, role=Qt.ItemDataRole.DisplayRole): + if role == Qt.ItemDataRole.DisplayRole: return self.label_for_row(index.row()) - if role == Qt.FontRole and index.row() == self.pos: + if role == Qt.ItemDataRole.FontRole and index.row() == self.pos: f = QApplication.instance().font() f.setBold(True) return f - if role == Qt.UserRole: + if role == Qt.ItemDataRole.UserRole: return self.states[index.row()] return None diff --git a/src/calibre/gui2/tweak_book/widgets.py b/src/calibre/gui2/tweak_book/widgets.py index 14de22e319..d03c0f2787 100644 --- a/src/calibre/gui2/tweak_book/widgets.py +++ b/src/calibre/gui2/tweak_book/widgets.py @@ -35,7 +35,7 @@ ignore_me class BusyCursor(object): def __enter__(self): - QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) + QApplication.setOverrideCursor(QCursor(Qt.CursorShape.WaitCursor)) def __exit__(self, *args): QApplication.restoreOverrideCursor() @@ -66,7 +66,7 @@ class InsertTag(Dialog): # {{{ la.setBuddy(ti) l.addWidget(ti) l.addWidget(self.bb) - ti.setFocus(Qt.OtherFocusReason) + ti.setFocus(Qt.FocusReason.OtherFocusReason) @property def tag(self): @@ -208,7 +208,7 @@ class ImportForeign(Dialog): # {{{ h1.addWidget(b) l.addRow(_('Source file:'), h1) b.clicked.connect(self.choose_source) - b.setFocus(Qt.OtherFocusReason) + b.setFocus(Qt.FocusReason.OtherFocusReason) self.h2 = h1 = QHBoxLayout() self.dest = src = QLineEdit(self) @@ -289,17 +289,17 @@ class Results(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent=parent) - self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) + self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) self.results = () self.current_result = -1 self.max_result = -1 self.mouse_hover_result = -1 self.setMouseTracking(True) - self.setFocusPolicy(Qt.NoFocus) + self.setFocusPolicy(Qt.FocusPolicy.NoFocus) self.text_option = to = QTextOption() to.setWrapMode(to.NoWrap) self.divider = QStaticText('\xa0→ \xa0') - self.divider.setTextFormat(Qt.PlainText) + self.divider.setTextFormat(Qt.TextFormat.PlainText) def item_from_y(self, y): if not self.results: @@ -347,7 +347,7 @@ class Results(QWidget): if results: self.current_result = 0 prefixes = [QStaticText('%s' % os.path.basename(x)) for x in results] - [(p.setTextFormat(Qt.RichText), p.setTextOption(self.text_option)) for p in prefixes] + [(p.setTextFormat(Qt.TextFormat.RichText), p.setTextOption(self.text_option)) for p in prefixes] self.maxwidth = max([x.size().width() for x in prefixes]) self.results = tuple((prefix, self.make_text(text, positions), text) for prefix, (text, positions) in zip(prefixes, iteritems(results))) @@ -361,7 +361,7 @@ class Results(QWidget): def make_text(self, text, positions): text = QStaticText(make_highlighted_text(emphasis_style(), text, positions)) text.setTextOption(self.text_option) - text.setTextFormat(Qt.RichText) + text.setTextFormat(Qt.TextFormat.RichText) return text def paintEvent(self, ev): @@ -380,7 +380,7 @@ class Results(QWidget): if i in (self.current_result, self.mouse_hover_result): p.save() if i != self.current_result: - p.setPen(Qt.DotLine) + p.setPen(Qt.PenStyle.DotLine) p.drawLine(offset, QPoint(self.width(), offset.y())) p.restore() offset.setY(offset.y() + self.MARGIN // 2) @@ -394,11 +394,11 @@ class Results(QWidget): offset.setX(0) p.save() if i != self.current_result: - p.setPen(Qt.DotLine) + p.setPen(Qt.PenStyle.DotLine) p.drawLine(offset, QPoint(self.width(), offset.y())) p.restore() else: - p.drawText(self.rect(), Qt.AlignCenter, _('No results found')) + p.drawText(self.rect(), Qt.AlignmentFlag.AlignCenter, _('No results found')) p.end() @@ -445,17 +445,17 @@ class QuickOpen(Dialog): t.textEdited.connect(self.update_matches) t.setClearButtonEnabled(True) t.setPlaceholderText(_('Search')) - l.addWidget(t, alignment=Qt.AlignTop) + l.addWidget(t, alignment=Qt.AlignmentFlag.AlignTop) self.help_label = hl = QLabel(self.help_text) - hl.setContentsMargins(50, 50, 50, 50), hl.setAlignment(Qt.AlignTop | Qt.AlignHCenter) + hl.setContentsMargins(50, 50, 50, 50), hl.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignHCenter) l.addWidget(hl) self.results = Results(self) self.results.setVisible(False) self.results.item_selected.connect(self.accept) l.addWidget(self.results) - l.addWidget(self.bb, alignment=Qt.AlignBottom) + l.addWidget(self.bb, alignment=Qt.AlignmentFlag.AlignBottom) def update_matches(self, text): text = unicode_type(text).strip() @@ -466,9 +466,9 @@ class QuickOpen(Dialog): self.matches = tuple(matches) def keyPressEvent(self, ev): - if ev.key() in (Qt.Key_Up, Qt.Key_Down): + if ev.key() in (Qt.Key.Key_Up, Qt.Key.Key_Down): ev.accept() - self.results.change_current(delta=-1 if ev.key() == Qt.Key_Up else 1) + self.results.change_current(delta=-1 if ev.key() == Qt.Key.Key_Up else 1) return return Dialog.keyPressEvent(self, ev) @@ -498,22 +498,22 @@ class NamesDelegate(QStyledItemDelegate): def paint(self, painter, option, index): QStyledItemDelegate.paint(self, painter, option, index) - text, positions = index.data(Qt.UserRole) + text, positions = index.data(Qt.ItemDataRole.UserRole) self.initStyleOption(option, index) painter.save() painter.setFont(option.font) 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.setClipRect(option.rect) if positions is None or -1 in positions: painter.setPen(c) - painter.drawText(option.rect, Qt.AlignLeft | Qt.AlignVCenter | Qt.TextSingleLine, text) + painter.drawText(option.rect, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter | Qt.TextFlag.TextSingleLine, text) else: to = QTextOption() to.setWrapMode(to.NoWrap) - to.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) + to.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter) positions = sorted(set(positions) - {-1}, reverse=True) text = '%s' % make_highlighted_text(emphasis_style(), text, positions) doc = QTextDocument() @@ -547,9 +547,9 @@ class NamesModel(QAbstractListModel): return len(self.items) def data(self, index, role): - if role == Qt.UserRole: + if role == Qt.ItemDataRole.UserRole: return self.items[index.row()] - if role == Qt.DisplayRole: + if role == Qt.ItemDataRole.DisplayRole: return '\xa0' * 20 def filter(self, query): @@ -605,11 +605,11 @@ class AnchorsModel(QAbstractListModel): return len(self.items) def data(self, index, role): - if role == Qt.UserRole: + if role == Qt.ItemDataRole.UserRole: return self.items[index.row()] - if role == Qt.DisplayRole: + if role == Qt.ItemDataRole.DisplayRole: return '\n'.join(self.items[index.row()]) - if role == Qt.ToolTipRole: + if role == Qt.ItemDataRole.ToolTipRole: text, frag = self.items[index.row()] return _('Anchor: {0}\nLeading text: {1}').format(frag, text) @@ -658,7 +658,7 @@ class InsertLink(Dialog): fn.setSpacing(5) self.anchor_names, self.anchor_names_filter = fn, f fn.selectionModel().selectionChanged.connect(self.update_target) - fn.doubleClicked.connect(self.accept, type=Qt.QueuedConnection) + fn.doubleClicked.connect(self.accept, type=Qt.ConnectionType.QueuedConnection) self.anl = fnl = QVBoxLayout() self.la2 = la = QLabel(_('Choose a &location (anchor) in the file:')) la.setBuddy(fn) @@ -708,7 +708,7 @@ class InsertLink(Dialog): if not rows: self.anchor_names.model().set_names([]) else: - name, positions = self.file_names.model().data(rows[0], Qt.UserRole) + name, positions = self.file_names.model().data(rows[0], Qt.ItemDataRole.UserRole) self.populate_anchors(name) def populate_anchors(self, name): @@ -730,7 +730,7 @@ class InsertLink(Dialog): rows = list(self.file_names.selectionModel().selectedRows()) if not rows: return - name = self.file_names.model().data(rows[0], Qt.UserRole)[0] + name = self.file_names.model().data(rows[0], Qt.ItemDataRole.UserRole)[0] if name == self.source_name: href = '' else: @@ -738,7 +738,7 @@ class InsertLink(Dialog): frag = '' rows = list(self.anchor_names.selectionModel().selectedRows()) if rows: - anchor = self.anchor_names.model().data(rows[0], Qt.UserRole)[1] + anchor = self.anchor_names.model().data(rows[0], Qt.ItemDataRole.UserRole)[1] if anchor: frag = '#' + anchor href += frag @@ -865,7 +865,7 @@ class InsertSemantics(Dialog): fn, f = create_filterable_names_list([], filter_text=_('Filter locations'), parent=self) self.anchor_names, self.anchor_names_filter = fn, f fn.selectionModel().selectionChanged.connect(self.update_target) - fn.doubleClicked.connect(self.accept, type=Qt.QueuedConnection) + fn.doubleClicked.connect(self.accept, type=Qt.ConnectionType.QueuedConnection) self.anl = fnl = QVBoxLayout() self.la2 = la = QLabel(_('Choose a &location (anchor) in the file:')) la.setBuddy(fn) @@ -924,7 +924,7 @@ class InsertSemantics(Dialog): if not rows: self.anchor_names.model().set_names([]) else: - name, positions = self.file_names.model().data(rows[0], Qt.UserRole) + name, positions = self.file_names.model().data(rows[0], Qt.ItemDataRole.UserRole) self.populate_anchors(name) def populate_anchors(self, name): @@ -940,12 +940,12 @@ class InsertSemantics(Dialog): rows = list(self.file_names.selectionModel().selectedRows()) if not rows: return - name = self.file_names.model().data(rows[0], Qt.UserRole)[0] + name = self.file_names.model().data(rows[0], Qt.ItemDataRole.UserRole)[0] href = name frag = '' rows = list(self.anchor_names.selectionModel().selectedRows()) if rows: - anchor = self.anchor_names.model().data(rows[0], Qt.UserRole)[0] + anchor = self.anchor_names.model().data(rows[0], Qt.ItemDataRole.UserRole)[0] if anchor: frag = '#' + anchor href += frag @@ -1057,7 +1057,7 @@ class CoverView(QWidget): QWidget.__init__(self, parent) self.current_pixmap_size = QSize(0, 0) self.pixmap = QPixmap() - self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) + self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) def set_pixmap(self, data): self.pixmap.loadFromData(data) @@ -1080,9 +1080,9 @@ class CoverView(QWidget): y = int(extray/2.) target = QRect(x, y, min(canvas_size.width(), width), min(canvas_size.height(), height)) p = QPainter(self) - p.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform) + p.setRenderHints(QPainter.RenderHint.Antialiasing | QPainter.RenderHint.SmoothPixmapTransform) p.drawPixmap(target, self.pixmap.scaled(target.size(), - Qt.KeepAspectRatio, Qt.SmoothTransformation)) + Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)) p.end() def sizeHint(self): @@ -1112,7 +1112,7 @@ class AddCover(Dialog): gb.setLayout(v), gb.setFlat(True) self.names, self.names_filter = create_filterable_names_list( sorted(self.image_names, key=sort_key), filter_text=_('Filter the list of images'), parent=self) - self.names.doubleClicked.connect(self.double_clicked, type=Qt.QueuedConnection) + self.names.doubleClicked.connect(self.double_clicked, type=Qt.ConnectionType.QueuedConnection) self.cover_view = CoverView(self) l.addWidget(self.names_filter) v.addWidget(self.names) @@ -1134,7 +1134,7 @@ class AddCover(Dialog): p.setVisible(self.container.book_type != 'azw3') def on_state_change(s): - tprefs.set('add_cover_preserve_aspect_ratio', s == Qt.Checked) + tprefs.set('add_cover_preserve_aspect_ratio', s == Qt.CheckState.Checked) p.stateChanged.connect(on_state_change) self.info_label = il = QLabel('\xa0') @@ -1145,7 +1145,7 @@ class AddCover(Dialog): b = self.bb.addButton(_('Import &image'), self.bb.ActionRole) b.clicked.connect(self.import_image) b.setIcon(QIcon(I('document_open.png'))) - self.names.setFocus(Qt.OtherFocusReason) + self.names.setFocus(Qt.FocusReason.OtherFocusReason) self.names.selectionModel().currentChanged.connect(self.current_image_changed) cname = get_raster_cover_name(self.container) if cname: diff --git a/src/calibre/gui2/ui.py b/src/calibre/gui2/ui.py index 9da47455d0..8e81325dcd 100644 --- a/src/calibre/gui2/ui.py +++ b/src/calibre/gui2/ui.py @@ -117,7 +117,7 @@ class Main(MainWindow, MainWindowMixin, DeviceMixin, EmailMixin, # {{{ self.setWindowIcon(QApplication.instance().windowIcon()) self.jobs_pointer = Pointer(self) self.proceed_requested.connect(self.do_proceed, - type=Qt.QueuedConnection) + type=Qt.ConnectionType.QueuedConnection) self.proceed_question = ProceedQuestion(self) self.job_error_dialog = JobError(self) self.keyboard = Manager(self) @@ -343,11 +343,11 @@ class Main(MainWindow, MainWindowMixin, DeviceMixin, EmailMixin, # {{{ self.library_view.model().count_changed() self.bars_manager.database_changed(self.library_view.model().db) self.library_view.model().database_changed.connect(self.bars_manager.database_changed, - type=Qt.QueuedConnection) + type=Qt.ConnectionType.QueuedConnection) # ########################## Tags Browser ############################## TagBrowserMixin.init_tag_browser_mixin(self, db) - self.library_view.model().database_changed.connect(self.populate_tb_manage_menu, type=Qt.QueuedConnection) + self.library_view.model().database_changed.connect(self.populate_tb_manage_menu, type=Qt.ConnectionType.QueuedConnection) # ######################## Search Restriction ########################## if db.new_api.pref('virtual_lib_on_startup'): @@ -447,11 +447,11 @@ class Main(MainWindow, MainWindowMixin, DeviceMixin, EmailMixin, # {{{ if view is self.library_view: self.focus_library_view() else: - view.setFocus(Qt.OtherFocusReason) + view.setFocus(Qt.FocusReason.OtherFocusReason) shift_esc = focus_current_view def focus_library_view(self): - self.library_view.alternate_views.current_view.setFocus(Qt.OtherFocusReason) + self.library_view.alternate_views.current_view.setFocus(Qt.FocusReason.OtherFocusReason) def ctrl_esc(self): self.apply_virtual_library() @@ -545,7 +545,7 @@ class Main(MainWindow, MainWindowMixin, DeviceMixin, EmailMixin, # {{{ pass def system_tray_icon_activated(self, r=False): - if r in (QSystemTrayIcon.Trigger, QSystemTrayIcon.MiddleClick, False): + if r in (QSystemTrayIcon.ActivationReason.Trigger, QSystemTrayIcon.ActivationReason.MiddleClick, False): if self.isVisible(): if self.isMinimized(): self.showNormal() @@ -764,7 +764,7 @@ class Main(MainWindow, MainWindowMixin, DeviceMixin, EmailMixin, # {{{ argv = () if isinstance(argv, (list, tuple)) and len(argv) > 1: self.handle_cli_args(argv[1:]) - self.setWindowState(self.windowState() & ~Qt.WindowMinimized|Qt.WindowActive) + self.setWindowState(self.windowState() & ~Qt.WindowState.WindowMinimized|Qt.WindowState.WindowActive) self.show_windows() self.raise_() self.activateWindow() diff --git a/src/calibre/gui2/update.py b/src/calibre/gui2/update.py index d44d7d0734..e3773dc6b6 100644 --- a/src/calibre/gui2/update.py +++ b/src/calibre/gui2/update.py @@ -129,7 +129,7 @@ class UpdateNotification(QDialog): def __init__(self, calibre_version, plugin_updates, parent=None): QDialog.__init__(self, parent) - self.setAttribute(Qt.WA_QuitOnClose, False) + self.setAttribute(Qt.WidgetAttribute.WA_QuitOnClose, False) self.resize(400, 250) self.l = QGridLayout() self.setLayout(self.l) @@ -162,7 +162,7 @@ class UpdateNotification(QDialog): if plugin_updates > 0: b = self.bb.addButton(_('Update &plugins'), self.bb.ActionRole) b.setIcon(QIcon(I('plugins/plugin_updater.png'))) - b.clicked.connect(self.get_plugins, type=Qt.QueuedConnection) + b.clicked.connect(self.get_plugins, type=Qt.ConnectionType.QueuedConnection) self.bb.addButton(self.bb.Cancel) self.l.addWidget(self.bb, 2, 0, 1, -1) self.bb.accepted.connect(self.accept) @@ -201,7 +201,7 @@ class UpdateMixin(object): if not opts.no_update_check: self.update_checker = CheckForUpdates(self) self.update_checker.signal.update_found.connect(self.update_found, - type=Qt.QueuedConnection) + type=Qt.ConnectionType.QueuedConnection) self.update_checker.start() def recalc_update_label(self, number_of_plugin_updates): diff --git a/src/calibre/gui2/viewer/bookmarks.py b/src/calibre/gui2/viewer/bookmarks.py index ccf5f49c3c..c9dc87cae2 100644 --- a/src/calibre/gui2/viewer/bookmarks.py +++ b/src/calibre/gui2/viewer/bookmarks.py @@ -29,7 +29,7 @@ class BookmarksList(QListWidget): QListWidget.__init__(self, parent) self.setAlternatingRowColors(True) self.setStyleSheet('QListView::item { padding: 0.5ex }') - self.setContextMenuPolicy(Qt.ActionsContextMenu) + self.setContextMenuPolicy(Qt.ContextMenuPolicy.ActionsContextMenu) self.ac_edit = ac = QAction(QIcon(I('edit_input.png')), _('Rename this bookmark'), self) self.addAction(ac) self.ac_delete = ac = QAction(QIcon(I('trash.png')), _('Remove this bookmark'), self) @@ -39,18 +39,18 @@ class BookmarksList(QListWidget): def current_non_removed_item(self): ans = self.currentItem() if ans is not None: - bm = ans.data(Qt.UserRole) + bm = ans.data(Qt.ItemDataRole.UserRole) if not bm.get('removed'): return ans 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): i = self.current_non_removed_item if i is not None: self.bookmark_activated.emit(i) ev.accept() return - if ev.key() in (Qt.Key_Delete, Qt.Key_Backspace): + if ev.key() in (Qt.Key.Key_Delete, Qt.Key.Key_Backspace): i = self.current_non_removed_item if i is not None: self.ac_delete.trigger() @@ -181,16 +181,16 @@ class BookmarkManager(QWidget): self.bookmarks_list.clear() for bm in bookmarks: i = QListWidgetItem(bm['title']) - i.setData(Qt.ToolTipRole, bm['title']) - i.setData(Qt.UserRole, self.bm_to_item(bm)) - i.setFlags(i.flags() | Qt.ItemIsEditable) + i.setData(Qt.ItemDataRole.ToolTipRole, bm['title']) + i.setData(Qt.ItemDataRole.UserRole, self.bm_to_item(bm)) + i.setFlags(i.flags() | Qt.ItemFlag.ItemIsEditable) self.bookmarks_list.addItem(i) if bm.get('removed'): i.setHidden(True) for i in range(self.bookmarks_list.count()): item = self.bookmarks_list.item(i) if not item.isHidden(): - self.bookmarks_list.setCurrentItem(item, QItemSelectionModel.ClearAndSelect) + self.bookmarks_list.setCurrentItem(item, QItemSelectionModel.SelectionFlag.ClearAndSelect) break if current_bookmark_id is not None: self.current_bookmark_id = current_bookmark_id @@ -199,14 +199,14 @@ class BookmarkManager(QWidget): def current_bookmark_id(self): item = self.bookmarks_list.currentItem() if item is not None: - return item.data(Qt.DisplayRole) + return item.data(Qt.ItemDataRole.DisplayRole) @current_bookmark_id.setter def current_bookmark_id(self, val): for i, q in enumerate(self): if q['title'] == val: item = self.bookmarks_list.item(i) - self.bookmarks_list.setCurrentItem(item, QItemSelectionModel.ClearAndSelect) + self.bookmarks_list.setCurrentItem(item, QItemSelectionModel.SelectionFlag.ClearAndSelect) self.bookmarks_list.scrollToItem(item) def set_current_bookmark(self, bm): @@ -214,7 +214,7 @@ class BookmarkManager(QWidget): if bm == q: l = self.bookmarks_list item = l.item(i) - l.setCurrentItem(item, QItemSelectionModel.ClearAndSelect) + l.setCurrentItem(item, QItemSelectionModel.SelectionFlag.ClearAndSelect) l.scrollToItem(item) def __iter__(self): @@ -225,7 +225,7 @@ class BookmarkManager(QWidget): remove = [] for i in range(self.bookmarks_list.count()): item = self.bookmarks_list.item(i) - bm = item.data(Qt.UserRole) + bm = item.data(Qt.ItemDataRole.UserRole) if bm.get('removed') and bm['title'] == base: remove.append(i) for i in reversed(remove): @@ -240,21 +240,21 @@ class BookmarkManager(QWidget): def item_changed(self, item): self.bookmarks_list.blockSignals(True) - title = unicode_type(item.data(Qt.DisplayRole)) or _('Unknown') + title = unicode_type(item.data(Qt.ItemDataRole.DisplayRole)) or _('Unknown') title = self.uniqify_bookmark_title(title) - item.setData(Qt.DisplayRole, title) - item.setData(Qt.ToolTipRole, title) - bm = item.data(Qt.UserRole) + item.setData(Qt.ItemDataRole.DisplayRole, title) + item.setData(Qt.ItemDataRole.ToolTipRole, title) + bm = item.data(Qt.ItemDataRole.UserRole) bm['title'] = title bm['timestamp'] = utcnow().isoformat() - item.setData(Qt.UserRole, bm) + item.setData(Qt.ItemDataRole.UserRole, bm) self.bookmarks_list.blockSignals(False) self.edited.emit(self.get_bookmarks()) def delete_bookmark(self): item = self.bookmarks_list.current_non_removed_item if item is not None: - bm = item.data(Qt.UserRole) + bm = item.data(Qt.ItemDataRole.UserRole) if confirm( _('Are you sure you want to delete the bookmark: {0}?').format(bm['title']), 'delete-bookmark-from-viewer', parent=self, config_set=vprefs @@ -262,7 +262,7 @@ class BookmarkManager(QWidget): bm['removed'] = True bm['timestamp'] = utcnow().isoformat() self.bookmarks_list.blockSignals(True) - item.setData(Qt.UserRole, bm) + item.setData(Qt.ItemDataRole.UserRole, bm) self.bookmarks_list.blockSignals(False) item.setHidden(True) self.edited.emit(self.get_bookmarks()) @@ -276,7 +276,7 @@ class BookmarkManager(QWidget): return bm.copy() def item_to_bm(self, item): - return item.data(Qt.UserRole).copy() + return item.data(Qt.ItemDataRole.UserRole).copy() def get_bookmarks(self): return list(self) @@ -370,7 +370,7 @@ class BookmarkManager(QWidget): def keyPressEvent(self, ev): sc = get_shortcut_for(self, ev) - if ev.key() == Qt.Key_Escape or sc == 'toggle_bookmarks': + if ev.key() == Qt.Key.Key_Escape or sc == 'toggle_bookmarks': self.toggle_requested.emit() return if sc == 'new_bookmark': diff --git a/src/calibre/gui2/viewer/highlights.py b/src/calibre/gui2/viewer/highlights.py index 71d2cf2f54..0cf65f9feb 100644 --- a/src/calibre/gui2/viewer/highlights.py +++ b/src/calibre/gui2/viewer/highlights.py @@ -76,22 +76,22 @@ def decoration_for_style(palette, style, icon_size, device_pixel_ratio, is_dark) if q is not None: style = q sz = int(math.ceil(icon_size * device_pixel_ratio)) - canvas = QImage(sz, sz, QImage.Format_ARGB32) - canvas.fill(Qt.transparent) + canvas = QImage(sz, sz, QImage.Format.Format_ARGB32) + canvas.fill(Qt.GlobalColor.transparent) canvas.setDevicePixelRatio(device_pixel_ratio) p = QPainter(canvas) - p.setRenderHint(QPainter.Antialiasing, True) + p.setRenderHint(QPainter.RenderHint.Antialiasing, True) p.setPen(palette.color(palette.WindowText)) irect = QRect(0, 0, icon_size, icon_size) adjust = -2 - text_rect = p.drawText(irect.adjusted(0, adjust, 0, adjust), Qt.AlignHCenter| Qt.AlignTop, 'a') + text_rect = p.drawText(irect.adjusted(0, adjust, 0, adjust), Qt.AlignmentFlag.AlignHCenter| Qt.AlignmentFlag.AlignTop, 'a') p.drawRect(irect) fm = p.fontMetrics() pen = p.pen() if 'text-decoration-color' in style: pen.setColor(QColor(style['text-decoration-color'])) lstyle = style.get('text-decoration-style') or 'solid' - q = {'dotted': Qt.DotLine, 'dashed': Qt.DashLine, }.get(lstyle) + q = {'dotted': Qt.PenStyle.DotLine, 'dashed': Qt.PenStyle.DashLine, }.get(lstyle) if q is not None: pen.setStyle(q) lw = fm.lineWidth() @@ -151,7 +151,7 @@ class Highlights(QTreeWidget): def __init__(self, parent=None): QTreeWidget.__init__(self, parent) - self.setContextMenuPolicy(Qt.CustomContextMenu) + self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.customContextMenuRequested.connect(self.show_context_menu) self.default_decoration = QIcon(I('blank.png')) self.setHeaderHidden(True) @@ -166,7 +166,7 @@ class Highlights(QTreeWidget): def show_context_menu(self, point): index = self.indexAt(point) - h = index.data(Qt.UserRole) + h = index.data(Qt.ItemDataRole.UserRole) self.context_menu = m = QMenu(self) if h is not None: m.addAction(QIcon(I('edit_input.png')), _('Modify this highlight'), self.edit_requested.emit) @@ -183,7 +183,7 @@ class Highlights(QTreeWidget): return True def current_item_changed(self, current, previous): - self.current_highlight_changed.emit(current.data(0, Qt.UserRole) if current is not None else None) + self.current_highlight_changed.emit(current.data(0, Qt.ItemDataRole.UserRole) if current is not None else None) def load(self, highlights): s = self.style() @@ -214,7 +214,7 @@ class Highlights(QTreeWidget): section_map[sec].append(h) for secnum, (sec, items) in enumerate(section_map.items()): section = QTreeWidgetItem([sec], 1) - section.setFlags(Qt.ItemIsEnabled) + section.setFlags(Qt.ItemFlag.ItemIsEnabled) section.setFont(0, self.section_font) tt = section_tt_map.get(sec) if tt: @@ -229,8 +229,8 @@ class Highlights(QTreeWidget): if len(txt) > 100: txt = txt[:100] + '…' item = QTreeWidgetItem(section, [txt], 2) - item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemNeverHasChildren) - item.setData(0, Qt.UserRole, h) + item.setFlags(Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemNeverHasChildren) + item.setData(0, Qt.ItemDataRole.UserRole, h) try: dec = decoration_for_style(self.palette(), h.get('style') or {}, icon_size, dpr, is_dark) except Exception: @@ -239,7 +239,7 @@ class Highlights(QTreeWidget): dec = None if dec is None: dec = self.default_decoration - item.setData(0, Qt.DecorationRole, dec) + item.setData(0, Qt.ItemDataRole.DecorationRole, dec) self.uuid_map[h['uuid']] = secnum, itemnum self.num_of_items += 1 @@ -280,7 +280,7 @@ class Highlights(QTreeWidget): if ch: q = ch['uuid'] for i, item in enumerate(items): - h = item.data(0, Qt.UserRole) + h = item.data(0, Qt.ItemDataRole.UserRole) if h['uuid'] == q: cr = i if query.backwards: @@ -292,7 +292,7 @@ class Highlights(QTreeWidget): cr = -1 indices = chain(range(cr + 1, count), range(0, cr + 1)) for i in indices: - h = items[i].data(0, Qt.UserRole) + h = items[i].data(0, Qt.ItemDataRole.UserRole) if pat.search(h['highlighted_text']) is not None or pat.search(h.get('notes') or '') is not None: self.set_current_row(*self.uuid_map[h['uuid']]) return True @@ -310,12 +310,12 @@ class Highlights(QTreeWidget): if sec is not None: item = sec.child(item_idx) if item is not None: - self.setCurrentItem(item, 0, QItemSelectionModel.ClearAndSelect) + self.setCurrentItem(item, 0, QItemSelectionModel.SelectionFlag.ClearAndSelect) return True return False def item_activated(self, item): - h = item.data(0, Qt.UserRole) + h = item.data(0, Qt.ItemDataRole.UserRole) if h is not None: self.jump_to_highlight.emit(h) @@ -323,24 +323,24 @@ class Highlights(QTreeWidget): def current_highlight(self): i = self.currentItem() if i is not None: - return i.data(0, Qt.UserRole) + return i.data(0, Qt.ItemDataRole.UserRole) @property def all_highlights(self): for item in self.iteritems(): - yield item.data(0, Qt.UserRole) + yield item.data(0, Qt.ItemDataRole.UserRole) @property def selected_highlights(self): for item in self.selectedItems(): - yield item.data(0, Qt.UserRole) + yield item.data(0, Qt.ItemDataRole.UserRole) def keyPressEvent(self, ev): - if ev.matches(QKeySequence.Delete): + if ev.matches(QKeySequence.StandardKey.Delete): self.delete_requested.emit() ev.accept() return - if ev.key() == Qt.Key_F2: + if ev.key() == Qt.Key.Key_F2: self.edit_requested.emit() ev.accept() return @@ -374,7 +374,7 @@ class NotesDisplay(Details): def __init__(self, parent=None): Details.__init__(self, parent) - self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum) + self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Maximum) self.anchorClicked.connect(self.edit_notes) self.current_notes = '' @@ -403,7 +403,7 @@ class HighlightsPanel(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) - self.setFocusPolicy(Qt.NoFocus) + self.setFocusPolicy(Qt.FocusPolicy.NoFocus) self.l = l = QVBoxLayout(self) l.setContentsMargins(0, 0, 0, 0) self.search_input = si = SearchInput(self, 'highlights-search') @@ -429,7 +429,7 @@ class HighlightsPanel(QWidget): def button(icon, text, tt, target): b = QPushButton(QIcon(I(icon)), text, self) b.setToolTip(tt) - b.setFocusPolicy(Qt.NoFocus) + b.setFocusPolicy(Qt.FocusPolicy.NoFocus) b.clicked.connect(target) return b @@ -455,7 +455,7 @@ class HighlightsPanel(QWidget): if a: def as_text(idx): - return index_to_key_sequence(idx).toString(QKeySequence.NativeText) + return index_to_key_sequence(idx).toString(QKeySequence.SequenceFormat.NativeText) tt = self.add_button.toolTip().partition('[')[0].strip() keys = sorted(filter(None, map(as_text, a))) @@ -468,7 +468,7 @@ class HighlightsPanel(QWidget): 'No highlights match the search: {}').format(query.text), show=True) def focus(self): - self.highlights.setFocus(Qt.OtherFocusReason) + self.highlights.setFocus(Qt.FocusReason.OtherFocusReason) def jump_to_highlight(self, highlight): self.request_highlight_action.emit(highlight['uuid'], 'goto') @@ -519,6 +519,6 @@ class HighlightsPanel(QWidget): def keyPressEvent(self, ev): sc = get_shortcut_for(self, ev) - if sc == 'toggle_highlights' or ev.key() == Qt.Key_Escape: + if sc == 'toggle_highlights' or ev.key() == Qt.Key.Key_Escape: self.toggle_requested.emit() return super().keyPressEvent(ev) diff --git a/src/calibre/gui2/viewer/lookup.py b/src/calibre/gui2/viewer/lookup.py index 34d6da4a80..71c084616a 100644 --- a/src/calibre/gui2/viewer/lookup.py +++ b/src/calibre/gui2/viewer/lookup.py @@ -78,7 +78,7 @@ class SourceEditor(Dialog): l.addRow(la) l.addRow(self.bb) if self.initial_name: - u.setFocus(Qt.OtherFocusReason) + u.setFocus(Qt.FocusReason.OtherFocusReason) @property def source_name(self): @@ -128,7 +128,7 @@ class SourcesEditor(Dialog): e.viewport().setAcceptDrops(True) e.setDropIndicatorShown(True) e.setDragDropMode(e.InternalMove) - e.setDefaultDropAction(Qt.MoveAction) + e.setDefaultDropAction(Qt.DropAction.MoveAction) l.addWidget(e) l.addWidget(self.bb) self.build_entries(vprefs['lookup_locations']) @@ -144,7 +144,7 @@ class SourcesEditor(Dialog): def add_entry(self, entry, prepend=False): i = QListWidgetItem(entry['name']) - i.setData(Qt.UserRole, entry.copy()) + i.setData(Qt.ItemDataRole.UserRole, entry.copy()) self.entries.insertItem(0, i) if prepend else self.entries.addItem(i) def build_entries(self, entries): @@ -157,7 +157,7 @@ class SourcesEditor(Dialog): def add_source(self): d = SourceEditor(self) - if d.exec_() == QDialog.Accepted: + if d.exec_() == QDialog.DialogCode.Accepted: self.add_entry(d.entry, prepend=True) def remove_source(self): @@ -166,14 +166,14 @@ class SourcesEditor(Dialog): self.entries.takeItem(idx) def edit_source(self, source_item): - d = SourceEditor(self, source_item.data(Qt.UserRole)) - if d.exec_() == QDialog.Accepted: - source_item.setData(Qt.UserRole, d.entry) - source_item.setData(Qt.DisplayRole, d.name) + d = SourceEditor(self, source_item.data(Qt.ItemDataRole.UserRole)) + if d.exec_() == QDialog.DialogCode.Accepted: + source_item.setData(Qt.ItemDataRole.UserRole, d.entry) + source_item.setData(Qt.ItemDataRole.DisplayRole, d.name) @property def all_entries(self): - return [self.entries.item(r).data(Qt.UserRole) for r in range(self.entries.count())] + return [self.entries.item(r).data(Qt.ItemDataRole.UserRole) for r in range(self.entries.count())] def accept(self): entries = self.all_entries @@ -194,7 +194,7 @@ def create_profile(): ans.setHttpUserAgent(random_user_agent(allow_ie=False)) ans.setCachePath(os.path.join(cache_dir(), 'ev2vl')) js = P('lookup.js', data=True, allow_user_override=False) - insert_scripts(ans, create_script('lookup.js', js, injection_point=QWebEngineScript.DocumentCreation)) + insert_scripts(ans, create_script('lookup.js', js, injection_point=QWebEngineScript.InjectionPoint.DocumentCreation)) s = ans.settings() s.setDefaultTextEncoding('utf-8') create_profile.ans = ans @@ -204,7 +204,7 @@ def create_profile(): class Page(QWebEnginePage): 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') if source_id == 'userscript:lookup.js': prints('%s: %s:%s: %s' % (prefix, source_id, linenumber, msg), file=sys.stderr) @@ -296,16 +296,16 @@ class Lookup(QWidget): d.setWindowTitle('Inspect Lookup page') v = QVBoxLayout(d) v.addWidget(self._devtools_view) - d.bb = QDialogButtonBox(QDialogButtonBox.Close) + d.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) d.bb.rejected.connect(d.reject) v.addWidget(d.bb) d.resize(QSize(800, 600)) - d.setAttribute(Qt.WA_DeleteOnClose, False) + d.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, False) self._devtools_dialog.show() - self._page.triggerAction(QWebEnginePage.InspectElement) + self._page.triggerAction(QWebEnginePage.WebAction.InspectElement) def add_sources(self): - if SourcesEditor(self).exec_() == QDialog.Accepted: + if SourcesEditor(self).exec_() == QDialog.DialogCode.Accepted: self.populate_sources() self.source_box.setCurrentIndex(0) self.update_query() @@ -322,7 +322,7 @@ class Lookup(QWidget): sb.blockSignals(True) for item in vprefs['lookup_locations']: sb.addItem(item['name'], item) - idx = sb.findText(vprefs['lookup_location'], Qt.MatchExactly) + idx = sb.findText(vprefs['lookup_location'], Qt.MatchFlag.MatchExactly) if idx > -1: sb.setCurrentIndex(idx) sb.blockSignals(False) diff --git a/src/calibre/gui2/viewer/main.py b/src/calibre/gui2/viewer/main.py index 628435cce4..19edb4292b 100644 --- a/src/calibre/gui2/viewer/main.py +++ b/src/calibre/gui2/viewer/main.py @@ -155,7 +155,7 @@ def run_gui(app, opts, args, internal_book_data, listener=None): acc.got_file.connect(main.handle_commandline_arg) main.show() if listener is not None: - listener.message_received.connect(main.message_from_other_instance, type=Qt.QueuedConnection) + listener.message_received.connect(main.message_from_other_instance, type=Qt.ConnectionType.QueuedConnection) QTimer.singleShot(0, acc.flush) if opts.raise_window: main.raise_() @@ -171,7 +171,7 @@ def main(args=sys.argv): reset_base_dir() scheme = QWebEngineUrlScheme(FAKE_PROTOCOL.encode('ascii')) scheme.setSyntax(QWebEngineUrlScheme.Syntax.Host) - scheme.setFlags(QWebEngineUrlScheme.SecureScheme) + scheme.setFlags(QWebEngineUrlScheme.Flag.SecureScheme) QWebEngineUrlScheme.registerScheme(scheme) override = 'calibre-ebook-viewer' if islinux else None processed_args = [] diff --git a/src/calibre/gui2/viewer/overlay.py b/src/calibre/gui2/viewer/overlay.py index a02dc448e4..71d4d81482 100644 --- a/src/calibre/gui2/viewer/overlay.py +++ b/src/calibre/gui2/viewer/overlay.py @@ -17,8 +17,8 @@ class LoadingOverlay(QWidget): self.setVisible(False) self.label = QLabel(self) self.label.setText('testing with some long and wrap worthy message that should hopefully still render well') - self.label.setTextFormat(Qt.RichText) - self.label.setAlignment(Qt.AlignTop | Qt.AlignHCenter) + self.label.setTextFormat(Qt.TextFormat.RichText) + self.label.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignHCenter) self.label.setWordWrap(True) if parent is None: self.resize(300, 300) @@ -47,11 +47,11 @@ class LoadingOverlay(QWidget): self.move(0, 0) self.setVisible(True) self.raise_() - self.setFocus(Qt.OtherFocusReason) + self.setFocus(Qt.FocusReason.OtherFocusReason) self.update() def hide(self): - self.parent().web_view.setFocus(Qt.OtherFocusReason) + self.parent().web_view.setFocus(Qt.FocusReason.OtherFocusReason) self.pi.stop() return QWidget.hide(self) diff --git a/src/calibre/gui2/viewer/search.py b/src/calibre/gui2/viewer/search.py index 329e6195d6..66b3f0bbb0 100644 --- a/src/calibre/gui2/viewer/search.py +++ b/src/calibre/gui2/viewer/search.py @@ -317,14 +317,14 @@ class SearchInput(QWidget): # {{{ 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.find_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.find_previous) nb.setToolTip(_('Find previous match')) @@ -333,7 +333,7 @@ class SearchInput(QWidget): # {{{ h.setContentsMargins(0, 0, 0, 0) l.addLayout(h) self.query_type = qt = QComboBox(self) - qt.setFocusPolicy(Qt.NoFocus) + qt.setFocusPolicy(Qt.FocusPolicy.NoFocus) qt.addItem(_('Contains'), 'normal') qt.addItem(_('Whole words'), 'word') qt.addItem(_('Regex'), 'regex') @@ -348,7 +348,7 @@ class SearchInput(QWidget): # {{{ h.addWidget(qt) self.case_sensitive = cs = QCheckBox(_('&Case sensitive'), self) - cs.setFocusPolicy(Qt.NoFocus) + cs.setFocusPolicy(Qt.FocusPolicy.NoFocus) cs.setChecked(bool(vprefs.get('viewer-{}-case-sensitive'.format(self.panel_name), False))) cs.stateChanged.connect(self.save_search_type) h.addWidget(cs) @@ -413,7 +413,7 @@ class SearchInput(QWidget): # {{{ def focus_input(self, text=None): if text and hasattr(text, 'rstrip'): self.search_box.setText(text) - self.search_box.setFocus(Qt.OtherFocusReason) + self.search_box.setFocus(Qt.FocusReason.OtherFocusReason) le = self.search_box.lineEdit() le.end(False) le.selectAll() @@ -429,7 +429,7 @@ class Results(QTreeWidget): # {{{ def __init__(self, parent=None): QTreeWidget.__init__(self, parent) self.setHeaderHidden(True) - self.setFocusPolicy(Qt.NoFocus) + self.setFocusPolicy(Qt.FocusPolicy.NoFocus) self.delegate = ResultsDelegate(self) self.setItemDelegate(self.delegate) self.itemClicked.connect(self.item_activated) @@ -444,7 +444,7 @@ class Results(QTreeWidget): # {{{ 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, SearchResult): self.current_result_changed.emit(r) else: @@ -463,7 +463,7 @@ class Results(QTreeWidget): # {{{ section = self.section_map.get(section_key) if section is None: section = QTreeWidgetItem([section_title], 1) - section.setFlags(Qt.ItemIsEnabled) + section.setFlags(Qt.ItemFlag.ItemIsEnabled) section.setFont(0, self.section_font) lines = [] for i, node in enumerate(toc_nodes): @@ -476,13 +476,13 @@ class Results(QTreeWidget): # {{{ self.addTopLevelItem(section) section.setExpanded(True) item = QTreeWidgetItem(section, [' '], 2) - item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemNeverHasChildren) - item.setData(0, Qt.UserRole, result) - item.setData(0, Qt.UserRole + 1, len(self.search_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, len(self.search_results)) if isinstance(result, SearchResult): tt = '

…' + 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()