diff options
author | Cristian Maureira-Fredes <Cristian.Maureira-Fredes@qt.io> | 2021-05-12 17:10:35 +0200 |
---|---|---|
committer | Cristian Maureira-Fredes <Cristian.Maureira-Fredes@qt.io> | 2021-05-14 13:23:50 +0200 |
commit | 3e6510ab70e488f3876c5e97458c8eaccae52ef9 (patch) | |
tree | ebc87f9db949f0e1dc348479f08a143134e54994 | |
parent | fc8ef9977a88a148ac6eb91b2aafb794ee8daec8 (diff) |
examples: clean and improve code
- removing '\' from long lines,
- use f-strings instead of concatenating strings
- Use f-strings instead of the old '%' formatting
Task-number: PYSIDE-841
Change-Id: I4983c25a6272e10119d5d1a74c180828ca6f64e6
Reviewed-by: Christian Tismer <tismer@stackless.com>
(cherry picked from commit 3c1a6f732a3a2c69e7133d07b89db0bdd788316b)
Reviewed-by: Friedemann Kleint <Friedemann.Kleint@qt.io>
21 files changed, 73 insertions, 70 deletions
diff --git a/examples/axcontainer/axviewer/axviewer.py b/examples/axcontainer/axviewer/axviewer.py index fd4972a34..e7e03d2c9 100644 --- a/examples/axcontainer/axviewer/axviewer.py +++ b/examples/axcontainer/axviewer/axviewer.py @@ -73,7 +73,7 @@ class MainWindow(QMainWindow): if axSelect.exec() == QDialog.Accepted: clsid = axSelect.clsid() if not self.axWidget.setControl(clsid): - QMessageBox.warning(self, "AxViewer", "Unable to load " + clsid + ".") + QMessageBox.warning(self, "AxViewer", f"Unable to load {clsid}.") if __name__ == '__main__': diff --git a/examples/corelib/threads/mandelbrot.py b/examples/corelib/threads/mandelbrot.py index 2e45afadc..c95966119 100644 --- a/examples/corelib/threads/mandelbrot.py +++ b/examples/corelib/threads/mandelbrot.py @@ -67,8 +67,8 @@ NUM_PASSES = 8 INFO_KEY = 'info' -HELP = "Use mouse wheel or the '+' and '-' keys to zoom. Press and " \ - "hold left mouse button to scroll." +HELP = ("Use mouse wheel or the '+' and '-' keys to zoom. Press and " + "hold left mouse button to scroll.") class RenderThread(QThread): diff --git a/examples/multimedia/audiooutput/audiooutput.py b/examples/multimedia/audiooutput/audiooutput.py index 322603c2b..0e9a2c10a 100644 --- a/examples/multimedia/audiooutput/audiooutput.py +++ b/examples/multimedia/audiooutput/audiooutput.py @@ -69,40 +69,40 @@ class Generator(QIODevice): self.m_pos = 0 self.close() - def generateData(self, format, durationUs, sampleRate): + def generateData(self, fmt, durationUs, sampleRate): pack_format = '' - if format.sampleSize() == 8: - if format.sampleType() == QAudioFormat.UnSignedInt: + if fmt.sampleSize() == 8: + if fmt.sampleType() == QAudioFormat.UnSignedInt: scaler = lambda x: ((1.0 + x) / 2 * 255) pack_format = 'B' - elif format.sampleType() == QAudioFormat.SignedInt: + elif fmt.sampleType() == QAudioFormat.SignedInt: scaler = lambda x: x * 127 pack_format = 'b' - elif format.sampleSize() == 16: - if format.sampleType() == QAudioFormat.UnSignedInt: + elif fmt.sampleSize() == 16: + if fmt.sampleType() == QAudioFormat.UnSignedInt: scaler = lambda x: (1.0 + x) / 2 * 65535 - pack_format = '<H' if format.byteOrder() == QAudioFormat.LittleEndian else '>H' - elif format.sampleType() == QAudioFormat.SignedInt: + pack_format = '<H' if fmt.byteOrder() == QAudioFormat.LittleEndian else '>H' + elif fmt.sampleType() == QAudioFormat.SignedInt: scaler = lambda x: x * 32767 - pack_format = '<h' if format.byteOrder() == QAudioFormat.LittleEndian else '>h' + pack_format = '<h' if fmt.byteOrder() == QAudioFormat.LittleEndian else '>h' assert(pack_format != '') - channelBytes = format.sampleSize() // 8 - sampleBytes = format.channelCount() * channelBytes + channelBytes = fmt.sampleSize() // 8 + sampleBytes = fmt.channelCount() * channelBytes - length = (format.sampleRate() * format.channelCount() * (format.sampleSize() // 8)) * durationUs // 100000 + length = (fmt.sampleRate() * fmt.channelCount() * (fmt.sampleSize() // 8)) * durationUs // 100000 self.m_buffer.clear() sampleIndex = 0 - factor = 2 * pi * sampleRate / format.sampleRate() + factor = 2 * pi * sampleRate / fmt.sampleRate() while length != 0: - x = sin((sampleIndex % format.sampleRate()) * factor) + x = sin((sampleIndex % fmt.sampleRate()) * factor) packed = pack(pack_format, int(scaler(x))) - for _ in range(format.channelCount()): + for _ in range(fmt.channelCount()): self.m_buffer.append(packed) length -= channelBytes @@ -230,10 +230,12 @@ class AudioTest(QMainWindow): self.m_audioOutput.setVolume(value / 100.0) def notified(self): - qWarning("bytesFree = %d, elapsedUSecs = %d, processedUSecs = %d" % ( - self.m_audioOutput.bytesFree(), - self.m_audioOutput.elapsedUSecs(), - self.m_audioOutput.processedUSecs())) + bytes_free = self.m_audioOutput.bytesFree() + elapsed = self.m_audioOutput.elapsedUSecs() + processed = self.m_audioOutput.processedUSecs() + qWarning(f"bytesFree = {bytes_free}, " + f"elapsedUSecs = {elapsed}, " + f"processedUSecs = {processed}") def pullTimerExpired(self): if self.m_audioOutput is not None and self.m_audioOutput.state() != QAudio.StoppedState: @@ -284,7 +286,8 @@ class AudioTest(QMainWindow): QAudio.IdleState: "IdleState"} def handleStateChanged(self, state): - qWarning("state = " + self.stateMap.get(state, "Unknown")) + state = self.stateMap.get(state, 'Unknown') + qWarning(f"state = {state}") if __name__ == '__main__': diff --git a/examples/multimedia/camera/camera.py b/examples/multimedia/camera/camera.py index e7e12cbe7..8ec3c869d 100644 --- a/examples/multimedia/camera/camera.py +++ b/examples/multimedia/camera/camera.py @@ -127,8 +127,8 @@ class MainWindow(QMainWindow): if self.camera.status() != QCamera.UnavailableStatus: name = self.cameraInfo.description() - self.setWindowTitle("PySide6 Camera Example (" + name + ")") - self.statusBar().showMessage("Starting: '" + name + "'", 5000) + self.setWindowTitle(f"PySide6 Camera Example ({name})") + self.statusBar().showMessage(f"Starting: '{name}'", 5000) self.camera.start() else: self.setWindowTitle("PySide6 Camera Example") @@ -138,7 +138,7 @@ class MainWindow(QMainWindow): def nextImageFileName(self): picturesLocation = QStandardPaths.writableLocation(QStandardPaths.PicturesLocation) dateString = QDate.currentDate().toString("yyyyMMdd") - pattern = picturesLocation + "/pyside6_camera_" + dateString + "_{:03d}.jpg" + pattern = f"{picturesLocation}/pyside6_camera_{dateString}_{:03d}.jpg" n = 1 while True: result = pattern.format(n) diff --git a/examples/opengl/textures/textures.py b/examples/opengl/textures/textures.py index 521c099b3..cbefe41d6 100644 --- a/examples/opengl/textures/textures.py +++ b/examples/opengl/textures/textures.py @@ -110,7 +110,7 @@ class GLWidget(QtOpenGL.QGLWidget): if not GLWidget.sharedObject: self.textures = [] for i in range(6): - self.textures.append(self.bindTexture(QtGui.QPixmap(":/images/side%d.png" % (i + 1)))) + self.textures.append(self.bindTexture(QtGui.QPixmap(f":/images/side{i + 1}.png"))) GLWidget.sharedObject = self.makeObject() GLWidget.refCount += 1 diff --git a/examples/samplebinding/main.py b/examples/samplebinding/main.py index f6f9f1fa9..bc5e16eec 100644 --- a/examples/samplebinding/main.py +++ b/examples/samplebinding/main.py @@ -64,7 +64,7 @@ class VanillaChocolateCherryIcecream(VanillaChocolateIcecream): def getFlavor(self): base_flavor = super(VanillaChocolateCherryIcecream, self).getFlavor() - return base_flavor + " and a cherry" + return f"{base_flavor} and a cherry" if __name__ == '__main__': diff --git a/examples/sql/books/bookwindow.py b/examples/sql/books/bookwindow.py index 0b6cc5f44..c57db4afb 100644 --- a/examples/sql/books/bookwindow.py +++ b/examples/sql/books/bookwindow.py @@ -114,7 +114,7 @@ class BookWindow(QMainWindow, Ui_BookWindow): def showError(err): QMessageBox.critical(self, "Unable to initialize Database", - "Error initializing database: " + err.text()) + f"Error initializing database: {err.text()}") def create_menubar(self): file_menu = self.menuBar().addMenu(self.tr("&File")) diff --git a/examples/webchannel/standalone/main.py b/examples/webchannel/standalone/main.py index f61954fc5..68f199336 100644 --- a/examples/webchannel/standalone/main.py +++ b/examples/webchannel/standalone/main.py @@ -61,7 +61,7 @@ if __name__ == '__main__': print('The example requires SSL support.') sys.exit(-1) cur_dir = os.path.dirname(os.path.abspath(__file__)) - jsFileInfo = QFileInfo(cur_dir + "/qwebchannel.js") + jsFileInfo = QFileInfo(f"{cur_dir}/qwebchannel.js") if not jsFileInfo.exists(): QFile.copy(":/qtwebchannel/qwebchannel.js", jsFileInfo.absoluteFilePath()) @@ -88,7 +88,7 @@ if __name__ == '__main__': channel.registerObject("core", core) # open a browser window with the client HTML page - url = QUrl.fromLocalFile(cur_dir + "/index.html") + url = QUrl.fromLocalFile(f"{cur_dir}/index.html") QDesktopServices.openUrl(url) message = f"Initialization complete, opening browser at {url.toDisplayString()}." diff --git a/examples/widgets/animation/easing/easing.py b/examples/widgets/animation/easing/easing.py index 24d37bd55..ba7f2d363 100644 --- a/examples/widgets/animation/easing/easing.py +++ b/examples/widgets/animation/easing/easing.py @@ -166,10 +166,10 @@ class Window(QWidget): # different curve types. We do the Python equivalant (but without # cheating) curve_types = [(n, c) for n, c in QEasingCurve.__dict__.items() - if isinstance(c, QEasingCurve.Type) \ - and c != QEasingCurve.Custom \ - and c != QEasingCurve.NCurveTypes \ - and c != QEasingCurve.TCBSpline] + if (isinstance(c, QEasingCurve.Type) + and c != QEasingCurve.Custom + and c != QEasingCurve.NCurveTypes + and c != QEasingCurve.TCBSpline)] curve_types.sort(key=lambda ct: ct[1]) painter.begin(pix) diff --git a/examples/widgets/dialogs/classwizard/classwizard.py b/examples/widgets/dialogs/classwizard/classwizard.py index 1daf91bbf..a7c7e2c58 100644 --- a/examples/widgets/dialogs/classwizard/classwizard.py +++ b/examples/widgets/dialogs/classwizard/classwizard.py @@ -65,9 +65,9 @@ BASE_CLASSES = ['<None>', 'PySide6.QtCore.QObject', PYTHON_TYPES = ['int', 'list', 'str'] -INTRODUCTION = """This wizard will generate a skeleton Python class definition,\ - including a few functions. You simply need to specify the class name and set\ - a few options to produce a Python file.""" +INTRODUCTION = ("This wizard will generate a skeleton Python class definition, " + "including a few functions. You simply need to specify the class name and set " + "a few options to produce a Python file.") def property_accessors(property_type, name): @@ -361,14 +361,14 @@ class OutputFilesPage(QWizardPage): self._file_line_edit.setText(class_name.lower() + '.py') self.set_output_dir(QDir.tempPath()) - def set_output_dir(self, dir): - self._output_dir_line_edit.setText(QDir.toNativeSeparators(dir)) + def set_output_dir(self, directory): + self._output_dir_line_edit.setText(QDir.toNativeSeparators(directory)) def output_dir(self): return QDir.fromNativeSeparators(self._output_dir_line_edit.text()) def file_name(self): - return self.output_dir() + '/' + self._file_line_edit.text() + return f"{self.output_dir()}/{self._file_line_edit.text()}" def _choose_output_dir(self): directory = QFileDialog.getExistingDirectory(self, "Output Directory", diff --git a/examples/widgets/dialogs/standarddialogs/standarddialogs.py b/examples/widgets/dialogs/standarddialogs/standarddialogs.py index 86397adc2..fb2dbc184 100644 --- a/examples/widgets/dialogs/standarddialogs/standarddialogs.py +++ b/examples/widgets/dialogs/standarddialogs/standarddialogs.py @@ -75,10 +75,10 @@ class DialogOptionsWidget(QGroupBox): class Dialog(QDialog): - MESSAGE = "<p>Message boxes have a caption, a text, and up to three " \ - "buttons, each with standard or custom texts.</p>" \ - "<p>Click a button to close the message box. Pressing the Esc " \ - "button will activate the detected escape button (if any).</p>" + MESSAGE = ("<p>Message boxes have a caption, a text, and up to three " + "buttons, each with standard or custom texts.</p>" + "<p>Click a button to close the message box. Pressing the Esc " + "button will activate the detected escape button (if any).</p>") def __init__(self, parent=None): super().__init__(parent) @@ -285,7 +285,7 @@ class Dialog(QDialog): d, ok = QInputDialog.getDouble(self, "QInputDialog.getDouble()", "Amount:", 37.56, -10000, 10000, 2) if ok: - self._double_label.setText("$%g" % d) + self._double_label.setText(f"${d:g}") def set_item(self): items = ("Spring", "Summer", "Fall", "Winter") diff --git a/examples/widgets/gallery/widgetgallery.py b/examples/widgets/gallery/widgetgallery.py index 0693750ac..bd7f8ce6b 100644 --- a/examples/widgets/gallery/widgetgallery.py +++ b/examples/widgets/gallery/widgetgallery.py @@ -305,7 +305,7 @@ class WidgetGallery(QDialog): # Create centered/italic HTML rich text rich_text = "<html><head/><body><i>" for line in POEM.split('\n'): - rich_text += "<center>" + line + "</center>" + rich_text += f"<center>{line}</center>" rich_text += "</i></body></html>" text_edit = QTextEdit(rich_text) diff --git a/examples/widgets/graphicsview/diagramscene/diagramscene.py b/examples/widgets/graphicsview/diagramscene/diagramscene.py index 7588c50a0..b068a8253 100644 --- a/examples/widgets/graphicsview/diagramscene/diagramscene.py +++ b/examples/widgets/graphicsview/diagramscene/diagramscene.py @@ -367,10 +367,10 @@ class DiagramScene(QGraphicsScene): self.removeItem(self.line) self.line = None - if len(start_items) and len(end_items) and \ - isinstance(start_items[0], DiagramItem) and \ - isinstance(end_items[0], DiagramItem) and \ - start_items[0] != end_items[0]: + if (len(start_items) and len(end_items) and + isinstance(start_items[0], DiagramItem) and + isinstance(end_items[0], DiagramItem) and + start_items[0] != end_items[0]): start_item = start_items[0] end_item = end_items[0] arrow = Arrow(start_item, end_item) diff --git a/examples/widgets/graphicsview/dragdroprobot/dragdroprobot.py b/examples/widgets/graphicsview/dragdroprobot/dragdroprobot.py index 8732c1c67..4f074aa19 100644 --- a/examples/widgets/graphicsview/dragdroprobot/dragdroprobot.py +++ b/examples/widgets/graphicsview/dragdroprobot/dragdroprobot.py @@ -142,8 +142,8 @@ class RobotPart(QGraphicsItem): self.setAcceptDrops(True) def dragEnterEvent(self, event): - if event.mimeData().hasColor() or \ - (isinstance(self, RobotHead) and event.mimeData().hasImage()): + if (event.mimeData().hasColor() or + (isinstance(self, RobotHead) and event.mimeData().hasImage())): event.setAccepted(True) self._drag_over = True self.update() diff --git a/examples/widgets/itemviews/addressbook/adddialogwidget.py b/examples/widgets/itemviews/addressbook/adddialogwidget.py index eb848c4d6..1462711a8 100644 --- a/examples/widgets/itemviews/addressbook/adddialogwidget.py +++ b/examples/widgets/itemviews/addressbook/adddialogwidget.py @@ -99,5 +99,5 @@ if __name__ == "__main__": if (dialog.exec()): name = dialog.name address = dialog.address - print("Name:" + name) - print("Address:" + address) + print(f"Name: {name}") + print(f"Address: {address}") diff --git a/examples/widgets/itemviews/addressbook/newaddresstab.py b/examples/widgets/itemviews/addressbook/newaddresstab.py index 63ccbcc30..407c48aec 100644 --- a/examples/widgets/itemviews/addressbook/newaddresstab.py +++ b/examples/widgets/itemviews/addressbook/newaddresstab.py @@ -81,8 +81,8 @@ class NewAddressTab(QWidget): if __name__ == "__main__": def print_address(name, address): - print("Name:" + name) - print("Address:" + address) + print(f"Name: {name}") + print(f"Address: {address}") import sys from PySide6.QtWidgets import QApplication diff --git a/examples/widgets/itemviews/jsonmodel/jsonmodel.py b/examples/widgets/itemviews/jsonmodel/jsonmodel.py index 5fa324a03..432bc4b33 100644 --- a/examples/widgets/itemviews/jsonmodel/jsonmodel.py +++ b/examples/widgets/itemviews/jsonmodel/jsonmodel.py @@ -170,7 +170,7 @@ class JsonModel(QAbstractItemModel): assert isinstance( document, (dict, list, tuple) - ), "`document` must be of dict, list or tuple, " "not %s" % type(document) + ), "`document` must be of dict, list or tuple, " f"not {type(document)}" self.beginResetModel() diff --git a/examples/widgets/layouts/dynamiclayouts/dynamiclayouts.py b/examples/widgets/layouts/dynamiclayouts/dynamiclayouts.py index 994a6fb45..c0e3266ce 100644 --- a/examples/widgets/layouts/dynamiclayouts/dynamiclayouts.py +++ b/examples/widgets/layouts/dynamiclayouts/dynamiclayouts.py @@ -124,8 +124,8 @@ class Dialog(QDialog): self._rotable_widgets.append(QProgressBar()) count = len(self._rotable_widgets) for i in range(count): - self._rotable_widgets[i].valueChanged[int].\ - connect(self._rotable_widgets[(i + 1) % count].setValue) + element = self._rotable_widgets[(i + 1) % count] + self._rotable_widgets[i].valueChanged[int].connect(element.setValue) self._rotable_layout = QGridLayout() self._rotable_group_box.setLayout(self._rotable_layout) diff --git a/examples/widgets/mainwindows/mdi/mdi.py b/examples/widgets/mainwindows/mdi/mdi.py index 29ee71204..c674ab783 100644 --- a/examples/widgets/mainwindows/mdi/mdi.py +++ b/examples/widgets/mainwindows/mdi/mdi.py @@ -68,7 +68,7 @@ class MdiChild(QTextEdit): self._is_untitled = True self._cur_file = f"document{MdiChild.sequence_number}.txt" MdiChild.sequence_number += 1 - self.setWindowTitle(self._cur_file + '[*]') + self.setWindowTitle(f"{self._cur_file}[*]") self.document().contentsChanged.connect(self.document_was_modified) @@ -161,7 +161,7 @@ class MdiChild(QTextEdit): self._is_untitled = False self.document().setModified(False) self.setWindowModified(False) - self.setWindowTitle(self.user_friendly_current_file() + "[*]") + self.setWindowTitle(f"{self.user_friendly_current_file()}[*]") def stripped_name(self, fullFileName): return QFileInfo(fullFileName).fileName() diff --git a/examples/widgets/painting/basicdrawing/basicdrawing.py b/examples/widgets/painting/basicdrawing/basicdrawing.py index 941fe4256..d7849b0cc 100644 --- a/examples/widgets/painting/basicdrawing/basicdrawing.py +++ b/examples/widgets/painting/basicdrawing/basicdrawing.py @@ -59,8 +59,8 @@ class RenderArea(QWidget): QPoint(90, 70) ]) - Line, Points, Polyline, Polygon, Rect, RoundedRect, Ellipse, Arc, Chord, \ - Pie, Path, Text, Pixmap = range(13) + (Line, Points, Polyline, Polygon, Rect, RoundedRect, Ellipse, + Arc, Chord, Pie, Path, Text, Pixmap) = range(13) def __init__(self, parent=None): super().__init__(parent) diff --git a/examples/widgets/state-machine/rogue/rogue.py b/examples/widgets/state-machine/rogue/rogue.py index acf213ae6..1234bea0b 100644 --- a/examples/widgets/state-machine/rogue/rogue.py +++ b/examples/widgets/state-machine/rogue/rogue.py @@ -53,11 +53,11 @@ class MovementTransition(QEventTransition): self.window = window def eventTest(self, event): - if event.type() == QEvent.StateMachineWrapped and \ - event.event().type() == QEvent.KeyPress: + if (event.type() == QEvent.StateMachineWrapped and + event.event().type() == QEvent.KeyPress): key = event.event().key() - return key == Qt.Key_2 or key == Qt.Key_8 or \ - key == Qt.Key_6 or key == Qt.Key_4 + return (key == Qt.Key_2 or key == Qt.Key_8 or + key == Qt.Key_6 or key == Qt.Key_4) return False def onTransition(self, event): @@ -109,8 +109,8 @@ class MainWindow(QMainWindow): for x in range(self.width): column = [] for y in range(self.height): - if x == 0 or x == self.width - 1 or y == 0 or \ - y == self.height - 1 or generator.bounded(0, 40) == 0: + if (x == 0 or x == self.width - 1 or y == 0 or + y == self.height - 1 or generator.bounded(0, 40) == 0): column.append('#') else: column.append('.') |