diff options
Diffstat (limited to 'examples/widgets/widgets')
17 files changed, 947 insertions, 789 deletions
diff --git a/examples/widgets/widgets/charactermap/charactermap.pyproject b/examples/widgets/widgets/charactermap/charactermap.pyproject new file mode 100644 index 000000000..c2b2c2068 --- /dev/null +++ b/examples/widgets/widgets/charactermap/charactermap.pyproject @@ -0,0 +1,4 @@ +{ + "files": ["main.py", "characterwidget.py", "fontinfodialog.py", + "mainwindow.py"] +} diff --git a/examples/widgets/widgets/charactermap/characterwidget.py b/examples/widgets/widgets/charactermap/characterwidget.py new file mode 100644 index 000000000..0f01f9684 --- /dev/null +++ b/examples/widgets/widgets/charactermap/characterwidget.py @@ -0,0 +1,133 @@ +# Copyright (C) 2022 The Qt Company Ltd. +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +from textwrap import dedent + +from PySide6.QtCore import QSize, Qt, Slot, Signal +from PySide6.QtGui import (QBrush, QFont, QFontDatabase, QFontMetrics, + QPainter, QPen) +from PySide6.QtWidgets import QToolTip, QWidget + +COLUMNS = 16 + + +class CharacterWidget(QWidget): + + character_selected = Signal(str) + + def __init__(self, parent=None): + super().__init__(parent) + + self._display_font = QFont() + self._last_key = -1 + self._square_size = int(0) + + self.calculate_square_size() + self.setMouseTracking(True) + + @Slot(QFont) + def update_font(self, font): + self._display_font.setFamily(font.family()) + self.calculate_square_size() + self.adjustSize() + self.update() + + @Slot(str) + def update_size(self, fontSize): + self._display_font.setPointSize(int(fontSize)) + self.calculate_square_size() + self.adjustSize() + self.update() + + @Slot(str) + def update_style(self, fontStyle): + old_strategy = self._display_font.styleStrategy() + self._display_font = QFontDatabase.font(self._display_font.family(), + fontStyle, + self._display_font.pointSize()) + self._display_font.setStyleStrategy(old_strategy) + self.calculate_square_size() + self.adjustSize() + self.update() + + @Slot(bool) + def update_font_merging(self, enable): + if enable: + self._display_font.setStyleStrategy(QFont.PreferDefault) + else: + self._display_font.setStyleStrategy(QFont.NoFontMerging) + self.adjustSize() + self.update() + + def calculate_square_size(self): + h = QFontMetrics(self._display_font, self).height() + self._square_size = max(16, 4 + h) + + def sizeHint(self): + return QSize(COLUMNS * self._square_size, + (65536 / COLUMNS) * self._square_size) + + def _unicode_from_pos(self, point): + row = int(point.y() / self._square_size) + return row * COLUMNS + int(point.x() / self._square_size) + + def mouseMoveEvent(self, event): + widget_position = self.mapFromGlobal(event.globalPosition().toPoint()) + key = self._unicode_from_pos(widget_position) + c = chr(key) + family = self._display_font.family() + text = dedent(f''' + <p>Character: <span style="font-size: 24pt; font-family: {family}"> + {c}</span><p>Value: 0x{key:x} + ''') + QToolTip.showText(event.globalPosition().toPoint(), text, self) + + def mousePressEvent(self, event): + if event.button() == Qt.LeftButton: + self._last_key = self._unicode_from_pos(event.position().toPoint()) + if self._last_key != -1: + c = chr(self._last_key) + self.character_selected.emit(f"{c}") + self.update() + else: + super().mousePressEvent(event) + + def paintEvent(self, event): + with QPainter(self) as painter: + self.render(event, painter) + + def render(self, event, painter): + painter = QPainter(self) + painter.fillRect(event.rect(), QBrush(Qt.white)) + painter.setFont(self._display_font) + redraw_rect = event.rect() + begin_row = int(redraw_rect.top() / self._square_size) + end_row = int(redraw_rect.bottom() / self._square_size) + begin_column = int(redraw_rect.left() / self._square_size) + end_column = int(redraw_rect.right() / self._square_size) + painter.setPen(QPen(Qt.gray)) + for row in range(begin_row, end_row + 1): + for column in range(begin_column, end_column + 1): + x = int(column * self._square_size) + y = int(row * self._square_size) + painter.drawRect(x, y, self._square_size, self._square_size) + + font_metrics = QFontMetrics(self._display_font) + painter.setPen(QPen(Qt.black)) + for row in range(begin_row, end_row + 1): + for column in range(begin_column, end_column + 1): + key = int(row * COLUMNS + column) + painter.setClipRect(column * self._square_size, + row * self._square_size, + self._square_size, self._square_size) + + if key == self._last_key: + painter.fillRect(column * self._square_size + 1, + row * self._square_size + 1, + self._square_size, self._square_size, QBrush(Qt.red)) + + text = chr(key) + painter.drawText(column * self._square_size + (self._square_size / 2) + - font_metrics.horizontalAdvance(text) / 2, + row * self._square_size + 4 + font_metrics.ascent(), + text) diff --git a/examples/widgets/widgets/charactermap/doc/charactermap.rst b/examples/widgets/widgets/charactermap/doc/charactermap.rst new file mode 100644 index 000000000..1a38615c4 --- /dev/null +++ b/examples/widgets/widgets/charactermap/doc/charactermap.rst @@ -0,0 +1,8 @@ +Character Map Example +===================== + +The example displays an array of characters which the user can click on +to enter text in a line edit. The contents of the line edit can then be +copied into the clipboard, and pasted into other applications. The +purpose behind this sort of tool is to allow users to enter characters +that may be unavailable or difficult to locate on their keyboards. diff --git a/examples/widgets/widgets/charactermap/fontinfodialog.py b/examples/widgets/widgets/charactermap/fontinfodialog.py new file mode 100644 index 000000000..aa874884f --- /dev/null +++ b/examples/widgets/widgets/charactermap/fontinfodialog.py @@ -0,0 +1,47 @@ +# Copyright (C) 2022 The Qt Company Ltd. +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +from PySide6.QtCore import Qt, qVersion, qFuzzyCompare +from PySide6.QtGui import QGuiApplication, QFontDatabase +from PySide6.QtWidgets import (QDialog, QDialogButtonBox, + QPlainTextEdit, QVBoxLayout) + + +def _format_font(font): + family = font.family() + size = font.pointSizeF() + return f"{family}, {size}pt" + + +class FontInfoDialog(QDialog): + + def __init__(self, parent): + super().__init__(parent) + self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint) + main_layout = QVBoxLayout(self) + text_edit = QPlainTextEdit(self.text(), self) + text_edit.setReadOnly(True) + text_edit.setFont(QFontDatabase.systemFont(QFontDatabase.FixedFont)) + main_layout.addWidget(text_edit) + button_box = QDialogButtonBox(QDialogButtonBox.Close, self) + button_box.rejected.connect(self.reject) + main_layout.addWidget(button_box) + + def text(self): + default_font = QFontDatabase.systemFont(QFontDatabase.GeneralFont) + fixed_font = QFontDatabase.systemFont(QFontDatabase.FixedFont) + title_font = QFontDatabase.systemFont(QFontDatabase.TitleFont) + smallest_readable_font = QFontDatabase.systemFont(QFontDatabase.SmallestReadableFont) + + v = qVersion() + platform = QGuiApplication.platformName() + dpi = self.logicalDpiX() + dpr = self.devicePixelRatio() + text = f"Qt {v} on {platform}, {dpi}DPI" + if not qFuzzyCompare(dpr, float(1)): + text += f", device pixel ratio: {dpr}" + text += ("\n\nDefault font : " + _format_font(default_font) + + "\nFixed font : " + _format_font(fixed_font) + + "\nTitle font : " + _format_font(title_font) + + "\nSmallest font: " + _format_font(smallest_readable_font)) + return text diff --git a/examples/widgets/widgets/charactermap/main.py b/examples/widgets/widgets/charactermap/main.py new file mode 100644 index 000000000..e84a1d8af --- /dev/null +++ b/examples/widgets/widgets/charactermap/main.py @@ -0,0 +1,17 @@ +# Copyright (C) 2022 The Qt Company Ltd. +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +import sys + +from PySide6.QtWidgets import QApplication + +from mainwindow import MainWindow + +"""PySide6 port of the widgets/widgets/ charactermap example from Qt6""" + + +if __name__ == "__main__": + app = QApplication(sys.argv) + window = MainWindow() + window.show() + sys.exit(app.exec()) diff --git a/examples/widgets/widgets/charactermap/mainwindow.py b/examples/widgets/widgets/charactermap/mainwindow.py new file mode 100644 index 000000000..d79285def --- /dev/null +++ b/examples/widgets/widgets/charactermap/mainwindow.py @@ -0,0 +1,167 @@ +# Copyright (C) 2022 The Qt Company Ltd. +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +from PySide6.QtCore import Qt, QSignalBlocker, Slot +from PySide6.QtGui import QGuiApplication, QClipboard, QFont, QFontDatabase +from PySide6.QtWidgets import (QCheckBox, QComboBox, QFontComboBox, + QHBoxLayout, QLabel, QLineEdit, QMainWindow, + QPushButton, QScrollArea, + QVBoxLayout, QWidget) + +from characterwidget import CharacterWidget +from fontinfodialog import FontInfoDialog + + +class MainWindow(QMainWindow): + + def __init__(self, parent=None): + super().__init__(parent) + + self._character_widget = CharacterWidget() + self._filter_combo = QComboBox() + self._style_combo = QComboBox() + self._size_combo = QComboBox() + self._font_combo = QFontComboBox() + self._line_edit = QLineEdit() + self._scroll_area = QScrollArea() + self._font_merging = QCheckBox() + + file_menu = self.menuBar().addMenu("File") + file_menu.addAction("Quit", self.close) + help_menu = self.menuBar().addMenu("Help") + help_menu.addAction("Show Font Info", self.show_info) + help_menu.addAction("About &Qt", qApp.aboutQt) # noqa: F821 + + central_widget = QWidget() + + self._filter_label = QLabel("Filter:") + self._filter_combo = QComboBox() + self._filter_combo.addItem("All", int(QFontComboBox.AllFonts.value)) + self._filter_combo.addItem("Scalable", int(QFontComboBox.ScalableFonts.value)) + self._filter_combo.addItem("Monospaced", int(QFontComboBox.MonospacedFonts.value)) + self._filter_combo.addItem("Proportional", int(QFontComboBox.ProportionalFonts.value)) + self._filter_combo.setCurrentIndex(0) + self._filter_combo.currentIndexChanged.connect(self.filter_changed) + + self._font_label = QLabel("Font:") + self._font_combo = QFontComboBox() + self._size_label = QLabel("Size:") + self._size_combo = QComboBox() + self._style_label = QLabel("Style:") + self._style_combo = QComboBox() + self._font_merging_label = QLabel("Automatic Font Merging:") + self._font_merging = QCheckBox() + self._font_merging.setChecked(True) + + self._scroll_area = QScrollArea() + self._character_widget = CharacterWidget() + self._scroll_area.setWidget(self._character_widget) + self.find_styles(self._font_combo.currentFont()) + self.find_sizes(self._font_combo.currentFont()) + + self._line_edit = QLineEdit() + self._line_edit.setClearButtonEnabled(True) + self._clipboard_button = QPushButton("To clipboard") + self._font_combo.currentFontChanged.connect(self.find_styles) + self._font_combo.currentFontChanged.connect(self.find_sizes) + self._font_combo.currentFontChanged.connect(self._character_widget.update_font) + self._size_combo.currentTextChanged.connect(self._character_widget.update_size) + self._style_combo.currentTextChanged.connect(self._character_widget.update_style) + self._character_widget.character_selected.connect(self.insert_character) + + self._clipboard_button.clicked.connect(self.update_clipboard) + self._font_merging.toggled.connect(self._character_widget.update_font_merging) + + controls_layout = QHBoxLayout() + controls_layout.addWidget(self._filter_label) + controls_layout.addWidget(self._filter_combo, 1) + controls_layout.addWidget(self._font_label) + controls_layout.addWidget(self._font_combo, 1) + controls_layout.addWidget(self._size_label) + controls_layout.addWidget(self._size_combo, 1) + controls_layout.addWidget(self._style_label) + controls_layout.addWidget(self._style_combo, 1) + controls_layout.addWidget(self._font_merging_label) + controls_layout.addWidget(self._font_merging, 1) + controls_layout.addStretch(1) + + line_layout = QHBoxLayout() + line_layout.addWidget(self._line_edit, 1) + line_layout.addSpacing(12) + line_layout.addWidget(self._clipboard_button) + + central_layout = QVBoxLayout(central_widget) + central_layout.addLayout(controls_layout) + central_layout.addWidget(self._scroll_area, 1) + central_layout.addSpacing(4) + central_layout.addLayout(line_layout) + + self.setCentralWidget(central_widget) + self.setWindowTitle("Character Map") + + @Slot(QFont) + def find_styles(self, font): + current_item = self._style_combo.currentText() + self._style_combo.clear() + styles = QFontDatabase.styles(font.family()) + for style in styles: + self._style_combo.addItem(style) + + style_index = self._style_combo.findText(current_item) + + if style_index == -1: + self._style_combo.setCurrentIndex(0) + else: + self._style_combo.setCurrentIndex(style_index) + + @Slot(int) + def filter_changed(self, f): + filter = QFontComboBox.FontFilter(self._filter_combo.itemData(f)) + self._font_combo.setFontFilters(filter) + count = self._font_combo.count() + self.statusBar().showMessage(f"{count} font(s) found") + + @Slot(QFont) + def find_sizes(self, font): + current_size = self._size_combo.currentText() + with QSignalBlocker(self._size_combo): + # sizeCombo signals are now blocked until end of scope + self._size_combo.clear() + + style = QFontDatabase.styleString(font) + if QFontDatabase.isSmoothlyScalable(font.family(), style): + sizes = QFontDatabase.standardSizes() + for size in sizes: + self._size_combo.addItem(f"{size}") + self._size_combo.setEditable(True) + else: + sizes = QFontDatabase.smoothSizes(font.family(), style) + for size in sizes: + self._size_combo.addItem(f"{size}") + self._size_combo.setEditable(False) + + size_index = self._size_combo.findText(current_size) + + if size_index == -1: + self._size_combo.setCurrentIndex(max(0, self._size_combo.count() / 3)) + else: + self._size_combo.setCurrentIndex(size_index) + + @Slot(str) + def insert_character(self, character): + self._line_edit.insert(character) + + @Slot() + def update_clipboard(self): + clipboard = QGuiApplication.clipboard() + clipboard.setText(self._line_edit.text(), QClipboard.Clipboard) + clipboard.setText(self._line_edit.text(), QClipboard.Selection) + + @Slot() + def show_info(self): + screen_geometry = self.screen().geometry() + dialog = FontInfoDialog(self) + dialog.setWindowTitle("Fonts") + dialog.setAttribute(Qt.WA_DeleteOnClose) + dialog.resize(screen_geometry.width() / 4, screen_geometry.height() / 4) + dialog.show() diff --git a/examples/widgets/widgets/digitalclock/digitalclock.py b/examples/widgets/widgets/digitalclock/digitalclock.py new file mode 100644 index 000000000..f0030b356 --- /dev/null +++ b/examples/widgets/widgets/digitalclock/digitalclock.py @@ -0,0 +1,41 @@ +# Copyright (C) 2022 The Qt Company Ltd. +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause +import sys + +from PySide6.QtCore import QTime, QTimer, Slot +from PySide6.QtWidgets import QApplication, QLCDNumber + + +class DigitalClock(QLCDNumber): + def __init__(self, parent=None): + super().__init__(parent) + self.setSegmentStyle(QLCDNumber.Filled) + self.setDigitCount(8) + + self.timer = QTimer(self) + self.timer.timeout.connect(self.show_time) + self.timer.start(1000) + + self.show_time() + + self.setWindowTitle("Digital Clock") + self.resize(250, 60) + + @Slot() + def show_time(self): + time = QTime.currentTime() + text = time.toString("hh:mm:ss") + + # Blinking effect + if (time.second() % 2) == 0: + text = text.replace(":", " ") + + self.display(text) + + +if __name__ == "__main__": + + app = QApplication(sys.argv) + clock = DigitalClock() + clock.show() + sys.exit(app.exec()) diff --git a/examples/widgets/widgets/digitalclock/digitalclock.pyproject b/examples/widgets/widgets/digitalclock/digitalclock.pyproject new file mode 100644 index 000000000..03c3b6bb7 --- /dev/null +++ b/examples/widgets/widgets/digitalclock/digitalclock.pyproject @@ -0,0 +1,3 @@ +{ + "files": ["digitalclock.py"] +} diff --git a/examples/widgets/widgets/digitalclock/doc/digitalclock-screenshot.png b/examples/widgets/widgets/digitalclock/doc/digitalclock-screenshot.png Binary files differnew file mode 100644 index 000000000..2234d7665 --- /dev/null +++ b/examples/widgets/widgets/digitalclock/doc/digitalclock-screenshot.png diff --git a/examples/widgets/widgets/digitalclock/doc/digitalclock.rst b/examples/widgets/widgets/digitalclock/doc/digitalclock.rst new file mode 100644 index 000000000..d13275d24 --- /dev/null +++ b/examples/widgets/widgets/digitalclock/doc/digitalclock.rst @@ -0,0 +1,14 @@ +Digital Clock Example +===================== + +.. tags:: Android + +The Digital Clock example shows how to use QLCDNumber to display a number with +LCD-like digits. + +.. image:: digitalclock-screenshot.png + :width: 400 + :alt: Digital Clock Screenshot + +This example also demonstrates how QTimer can be used to update a widget at +regular intervals. diff --git a/examples/widgets/widgets/hellogl_openglwidget_legacy.py b/examples/widgets/widgets/hellogl_openglwidget_legacy.py deleted file mode 100644 index 8745b4e8d..000000000 --- a/examples/widgets/widgets/hellogl_openglwidget_legacy.py +++ /dev/null @@ -1,288 +0,0 @@ - -############################################################################ -## -## Copyright (C) 2017 The Qt Company Ltd. -## Contact: http://www.qt.io/licensing/ -## -## This file is part of the Qt for Python examples of the Qt Toolkit. -## -## $QT_BEGIN_LICENSE:BSD$ -## You may use this file under the terms of the BSD license as follows: -## -## "Redistribution and use in source and binary forms, with or without -## modification, are permitted provided that the following conditions are -## met: -## * Redistributions of source code must retain the above copyright -## notice, this list of conditions and the following disclaimer. -## * Redistributions in binary form must reproduce the above copyright -## notice, this list of conditions and the following disclaimer in -## the documentation and/or other materials provided with the -## distribution. -## * Neither the name of The Qt Company Ltd nor the names of its -## contributors may be used to endorse or promote products derived -## from this software without specific prior written permission. -## -## -## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -## -## $QT_END_LICENSE$ -## -############################################################################ - -"""PySide2 port of the opengl/legacy/hellogl example from Qt v5.x modified to use a QOpenGLWidget to demonstrate porting from QGLWidget to QOpenGLWidget""" - -import sys -import math -from PySide2 import QtCore, QtGui, QtWidgets - -try: - from OpenGL import GL -except ImportError: - app = QtWidgets.QApplication(sys.argv) - messageBox = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Critical, "OpenGL hellogl", - "PyOpenGL must be installed to run this example.", - QtWidgets.QMessageBox.Close) - messageBox.setDetailedText("Run:\npip install PyOpenGL PyOpenGL_accelerate") - messageBox.exec_() - sys.exit(1) - - -class Window(QtWidgets.QWidget): - def __init__(self, parent=None): - QtWidgets.QWidget.__init__(self, parent) - - self.glWidget = GLWidget() - - self.xSlider = self.createSlider(QtCore.SIGNAL("xRotationChanged(int)"), - self.glWidget.setXRotation) - self.ySlider = self.createSlider(QtCore.SIGNAL("yRotationChanged(int)"), - self.glWidget.setYRotation) - self.zSlider = self.createSlider(QtCore.SIGNAL("zRotationChanged(int)"), - self.glWidget.setZRotation) - - mainLayout = QtWidgets.QHBoxLayout() - mainLayout.addWidget(self.glWidget) - mainLayout.addWidget(self.xSlider) - mainLayout.addWidget(self.ySlider) - mainLayout.addWidget(self.zSlider) - self.setLayout(mainLayout) - - self.xSlider.setValue(170 * 16) - self.ySlider.setValue(160 * 16) - self.zSlider.setValue(90 * 16) - - self.setWindowTitle(self.tr("QOpenGLWidget")) - - def createSlider(self, changedSignal, setterSlot): - slider = QtWidgets.QSlider(QtCore.Qt.Vertical) - - slider.setRange(0, 360 * 16) - slider.setSingleStep(16) - slider.setPageStep(15 * 16) - slider.setTickInterval(15 * 16) - slider.setTickPosition(QtWidgets.QSlider.TicksRight) - - self.glWidget.connect(slider, QtCore.SIGNAL("valueChanged(int)"), setterSlot) - self.connect(self.glWidget, changedSignal, slider, QtCore.SLOT("setValue(int)")) - - return slider - - -class GLWidget(QtWidgets.QOpenGLWidget): - xRotationChanged = QtCore.Signal(int) - yRotationChanged = QtCore.Signal(int) - zRotationChanged = QtCore.Signal(int) - - def __init__(self, parent=None): - QtWidgets.QOpenGLWidget.__init__(self, parent) - - self.object = 0 - self.xRot = 0 - self.yRot = 0 - self.zRot = 0 - - self.lastPos = QtCore.QPoint() - - self.trolltechGreen = QtGui.QColor.fromCmykF(0.40, 0.0, 1.0, 0.0) - self.trolltechPurple = QtGui.QColor.fromCmykF(0.39, 0.39, 0.0, 0.0) - - def xRotation(self): - return self.xRot - - def yRotation(self): - return self.yRot - - def zRotation(self): - return self.zRot - - def minimumSizeHint(self): - return QtCore.QSize(50, 50) - - def sizeHint(self): - return QtCore.QSize(400, 400) - - def setXRotation(self, angle): - angle = self.normalizeAngle(angle) - if angle != self.xRot: - self.xRot = angle - self.emit(QtCore.SIGNAL("xRotationChanged(int)"), angle) - self.update() - - def setYRotation(self, angle): - angle = self.normalizeAngle(angle) - if angle != self.yRot: - self.yRot = angle - self.emit(QtCore.SIGNAL("yRotationChanged(int)"), angle) - self.update() - - def setZRotation(self, angle): - angle = self.normalizeAngle(angle) - if angle != self.zRot: - self.zRot = angle - self.emit(QtCore.SIGNAL("zRotationChanged(int)"), angle) - self.update() - - def initializeGL(self): - darkTrolltechPurple = self.trolltechPurple.darker() - GL.glClearColor(darkTrolltechPurple.redF(), darkTrolltechPurple.greenF(), darkTrolltechPurple.blueF(), darkTrolltechPurple.alphaF()) - self.object = self.makeObject() - GL.glShadeModel(GL.GL_FLAT) - GL.glEnable(GL.GL_DEPTH_TEST) - GL.glEnable(GL.GL_CULL_FACE) - - def paintGL(self): - GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) - GL.glLoadIdentity() - GL.glTranslated(0.0, 0.0, -10.0) - GL.glRotated(self.xRot / 16.0, 1.0, 0.0, 0.0) - GL.glRotated(self.yRot / 16.0, 0.0, 1.0, 0.0) - GL.glRotated(self.zRot / 16.0, 0.0, 0.0, 1.0) - GL.glCallList(self.object) - - def resizeGL(self, width, height): - side = min(width, height) - GL.glViewport(int((width - side) / 2),int((height - side) / 2), side, side) - - GL.glMatrixMode(GL.GL_PROJECTION) - GL.glLoadIdentity() - GL.glOrtho(-0.5, +0.5, -0.5, +0.5, 4.0, 15.0) - GL.glMatrixMode(GL.GL_MODELVIEW) - - def mousePressEvent(self, event): - self.lastPos = QtCore.QPoint(event.pos()) - - def mouseMoveEvent(self, event): - dx = event.x() - self.lastPos.x() - dy = event.y() - self.lastPos.y() - - if event.buttons() & QtCore.Qt.LeftButton: - self.setXRotation(self.xRot + 8 * dy) - self.setYRotation(self.yRot + 8 * dx) - elif event.buttons() & QtCore.Qt.RightButton: - self.setXRotation(self.xRot + 8 * dy) - self.setZRotation(self.zRot + 8 * dx) - - self.lastPos = QtCore.QPoint(event.pos()) - - def makeObject(self): - genList = GL.glGenLists(1) - GL.glNewList(genList, GL.GL_COMPILE) - - GL.glBegin(GL.GL_QUADS) - - x1 = +0.06 - y1 = -0.14 - x2 = +0.14 - y2 = -0.06 - x3 = +0.08 - y3 = +0.00 - x4 = +0.30 - y4 = +0.22 - - self.quad(x1, y1, x2, y2, y2, x2, y1, x1) - self.quad(x3, y3, x4, y4, y4, x4, y3, x3) - - self.extrude(x1, y1, x2, y2) - self.extrude(x2, y2, y2, x2) - self.extrude(y2, x2, y1, x1) - self.extrude(y1, x1, x1, y1) - self.extrude(x3, y3, x4, y4) - self.extrude(x4, y4, y4, x4) - self.extrude(y4, x4, y3, x3) - - Pi = 3.14159265358979323846 - NumSectors = 200 - - for i in range(NumSectors): - angle1 = (i * 2 * Pi) / NumSectors - x5 = 0.30 * math.sin(angle1) - y5 = 0.30 * math.cos(angle1) - x6 = 0.20 * math.sin(angle1) - y6 = 0.20 * math.cos(angle1) - - angle2 = ((i + 1) * 2 * Pi) / NumSectors - x7 = 0.20 * math.sin(angle2) - y7 = 0.20 * math.cos(angle2) - x8 = 0.30 * math.sin(angle2) - y8 = 0.30 * math.cos(angle2) - - self.quad(x5, y5, x6, y6, x7, y7, x8, y8) - - self.extrude(x6, y6, x7, y7) - self.extrude(x8, y8, x5, y5) - - GL.glEnd() - GL.glEndList() - - return genList - - def quad(self, x1, y1, x2, y2, x3, y3, x4, y4): - GL.glColor(self.trolltechGreen.redF(), self.trolltechGreen.greenF(), self.trolltechGreen.blueF(), self.trolltechGreen.alphaF()) - - GL.glVertex3d(x1, y1, +0.05) - GL.glVertex3d(x2, y2, +0.05) - GL.glVertex3d(x3, y3, +0.05) - GL.glVertex3d(x4, y4, +0.05) - - GL.glVertex3d(x4, y4, -0.05) - GL.glVertex3d(x3, y3, -0.05) - GL.glVertex3d(x2, y2, -0.05) - GL.glVertex3d(x1, y1, -0.05) - - def extrude(self, x1, y1, x2, y2): - darkTrolltechGreen = self.trolltechGreen.darker(250 + int(100 * x1)) - GL.glColor(darkTrolltechGreen.redF(), darkTrolltechGreen.greenF(), darkTrolltechGreen.blueF(), darkTrolltechGreen.alphaF()) - - GL.glVertex3d(x1, y1, -0.05) - GL.glVertex3d(x2, y2, -0.05) - GL.glVertex3d(x2, y2, +0.05) - GL.glVertex3d(x1, y1, +0.05) - - def normalizeAngle(self, angle): - while angle < 0: - angle += 360 * 16 - while angle > 360 * 16: - angle -= 360 * 16 - return angle - - def freeResources(self): - self.makeCurrent() - GL.glDeleteLists(self.object, 1) - -if __name__ == '__main__': - app = QtWidgets.QApplication(sys.argv) - window = Window() - window.show() - res = app.exec_() - window.glWidget.freeResources() - sys.exit(res) diff --git a/examples/widgets/widgets/tetrix.py b/examples/widgets/widgets/tetrix.py deleted file mode 100644 index f90793ca9..000000000 --- a/examples/widgets/widgets/tetrix.py +++ /dev/null @@ -1,498 +0,0 @@ - -############################################################################# -## -## Copyright (C) 2013 Riverbank Computing Limited. -## Copyright (C) 2016 The Qt Company Ltd. -## Contact: http://www.qt.io/licensing/ -## -## This file is part of the Qt for Python examples of the Qt Toolkit. -## -## $QT_BEGIN_LICENSE:BSD$ -## You may use this file under the terms of the BSD license as follows: -## -## "Redistribution and use in source and binary forms, with or without -## modification, are permitted provided that the following conditions are -## met: -## * Redistributions of source code must retain the above copyright -## notice, this list of conditions and the following disclaimer. -## * Redistributions in binary form must reproduce the above copyright -## notice, this list of conditions and the following disclaimer in -## the documentation and/or other materials provided with the -## distribution. -## * Neither the name of The Qt Company Ltd nor the names of its -## contributors may be used to endorse or promote products derived -## from this software without specific prior written permission. -## -## -## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -## -## $QT_END_LICENSE$ -## -############################################################################# - -"""PySide2 port of the widgets/widgets/tetrix example from Qt v5.x""" - -import random - -from PySide2 import QtCore, QtGui, QtWidgets - - -NoShape, ZShape, SShape, LineShape, TShape, SquareShape, LShape, MirroredLShape = range(8) - - -class TetrixWindow(QtWidgets.QWidget): - def __init__(self): - super(TetrixWindow, self).__init__() - - self.board = TetrixBoard() - - nextPieceLabel = QtWidgets.QLabel() - nextPieceLabel.setFrameStyle(QtWidgets.QFrame.Box | QtWidgets.QFrame.Raised) - nextPieceLabel.setAlignment(QtCore.Qt.AlignCenter) - self.board.setNextPieceLabel(nextPieceLabel) - - scoreLcd = QtWidgets.QLCDNumber(5) - scoreLcd.setSegmentStyle(QtWidgets.QLCDNumber.Filled) - levelLcd = QtWidgets.QLCDNumber(2) - levelLcd.setSegmentStyle(QtWidgets.QLCDNumber.Filled) - linesLcd = QtWidgets.QLCDNumber(5) - linesLcd.setSegmentStyle(QtWidgets.QLCDNumber.Filled) - - startButton = QtWidgets.QPushButton("&Start") - startButton.setFocusPolicy(QtCore.Qt.NoFocus) - quitButton = QtWidgets.QPushButton("&Quit") - quitButton.setFocusPolicy(QtCore.Qt.NoFocus) - pauseButton = QtWidgets.QPushButton("&Pause") - pauseButton.setFocusPolicy(QtCore.Qt.NoFocus) - - startButton.clicked.connect(self.board.start) - pauseButton.clicked.connect(self.board.pause) - quitButton.clicked.connect(QtWidgets.qApp.quit) - self.board.scoreChanged.connect(scoreLcd.display) - self.board.levelChanged.connect(levelLcd.display) - self.board.linesRemovedChanged.connect(linesLcd.display) - - layout = QtWidgets.QGridLayout() - layout.addWidget(self.createLabel("NEXT"), 0, 0) - layout.addWidget(nextPieceLabel, 1, 0) - layout.addWidget(self.createLabel("LEVEL"), 2, 0) - layout.addWidget(levelLcd, 3, 0) - layout.addWidget(startButton, 4, 0) - layout.addWidget(self.board, 0, 1, 6, 1) - layout.addWidget(self.createLabel("SCORE"), 0, 2) - layout.addWidget(scoreLcd, 1, 2) - layout.addWidget(self.createLabel("LINES REMOVED"), 2, 2) - layout.addWidget(linesLcd, 3, 2) - layout.addWidget(quitButton, 4, 2) - layout.addWidget(pauseButton, 5, 2) - self.setLayout(layout) - - self.setWindowTitle("Tetrix") - self.resize(550, 370) - - def createLabel(self, text): - lbl = QtWidgets.QLabel(text) - lbl.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignBottom) - return lbl - - -class TetrixBoard(QtWidgets.QFrame): - BoardWidth = 10 - BoardHeight = 22 - - scoreChanged = QtCore.Signal(int) - - levelChanged = QtCore.Signal(int) - - linesRemovedChanged = QtCore.Signal(int) - - def __init__(self, parent=None): - super(TetrixBoard, self).__init__(parent) - - self.timer = QtCore.QBasicTimer() - self.nextPieceLabel = None - self.isWaitingAfterLine = False - self.curPiece = TetrixPiece() - self.nextPiece = TetrixPiece() - self.curX = 0 - self.curY = 0 - self.numLinesRemoved = 0 - self.numPiecesDropped = 0 - self.score = 0 - self.level = 0 - self.board = None - - self.setFrameStyle(QtWidgets.QFrame.Panel | QtWidgets.QFrame.Sunken) - self.setFocusPolicy(QtCore.Qt.StrongFocus) - self.isStarted = False - self.isPaused = False - self.clearBoard() - - self.nextPiece.setRandomShape() - - def shapeAt(self, x, y): - return self.board[(y * TetrixBoard.BoardWidth) + x] - - def setShapeAt(self, x, y, shape): - self.board[(y * TetrixBoard.BoardWidth) + x] = shape - - def timeoutTime(self): - return 1000 / (1 + self.level) - - def squareWidth(self): - return self.contentsRect().width() / TetrixBoard.BoardWidth - - def squareHeight(self): - return self.contentsRect().height() / TetrixBoard.BoardHeight - - def setNextPieceLabel(self, label): - self.nextPieceLabel = label - - def sizeHint(self): - return QtCore.QSize(TetrixBoard.BoardWidth * 15 + self.frameWidth() * 2, - TetrixBoard.BoardHeight * 15 + self.frameWidth() * 2) - - def minimumSizeHint(self): - return QtCore.QSize(TetrixBoard.BoardWidth * 5 + self.frameWidth() * 2, - TetrixBoard.BoardHeight * 5 + self.frameWidth() * 2) - - def start(self): - if self.isPaused: - return - - self.isStarted = True - self.isWaitingAfterLine = False - self.numLinesRemoved = 0 - self.numPiecesDropped = 0 - self.score = 0 - self.level = 1 - self.clearBoard() - - self.linesRemovedChanged.emit(self.numLinesRemoved) - self.scoreChanged.emit(self.score) - self.levelChanged.emit(self.level) - - self.newPiece() - self.timer.start(self.timeoutTime(), self) - - def pause(self): - if not self.isStarted: - return - - self.isPaused = not self.isPaused - if self.isPaused: - self.timer.stop() - else: - self.timer.start(self.timeoutTime(), self) - - self.update() - - def paintEvent(self, event): - super(TetrixBoard, self).paintEvent(event) - - painter = QtGui.QPainter(self) - rect = self.contentsRect() - - if self.isPaused: - painter.drawText(rect, QtCore.Qt.AlignCenter, "Pause") - return - - boardTop = rect.bottom() - TetrixBoard.BoardHeight * self.squareHeight() - - for i in range(TetrixBoard.BoardHeight): - for j in range(TetrixBoard.BoardWidth): - shape = self.shapeAt(j, TetrixBoard.BoardHeight - i - 1) - if shape != NoShape: - self.drawSquare(painter, - rect.left() + j * self.squareWidth(), - boardTop + i * self.squareHeight(), shape) - - if self.curPiece.shape() != NoShape: - for i in range(4): - x = self.curX + self.curPiece.x(i) - y = self.curY - self.curPiece.y(i) - self.drawSquare(painter, rect.left() + x * self.squareWidth(), - boardTop + (TetrixBoard.BoardHeight - y - 1) * self.squareHeight(), - self.curPiece.shape()) - - def keyPressEvent(self, event): - if not self.isStarted or self.isPaused or self.curPiece.shape() == NoShape: - super(TetrixBoard, self).keyPressEvent(event) - return - - key = event.key() - if key == QtCore.Qt.Key_Left: - self.tryMove(self.curPiece, self.curX - 1, self.curY) - elif key == QtCore.Qt.Key_Right: - self.tryMove(self.curPiece, self.curX + 1, self.curY) - elif key == QtCore.Qt.Key_Down: - self.tryMove(self.curPiece.rotatedRight(), self.curX, self.curY) - elif key == QtCore.Qt.Key_Up: - self.tryMove(self.curPiece.rotatedLeft(), self.curX, self.curY) - elif key == QtCore.Qt.Key_Space: - self.dropDown() - elif key == QtCore.Qt.Key_D: - self.oneLineDown() - else: - super(TetrixBoard, self).keyPressEvent(event) - - def timerEvent(self, event): - if event.timerId() == self.timer.timerId(): - if self.isWaitingAfterLine: - self.isWaitingAfterLine = False - self.newPiece() - self.timer.start(self.timeoutTime(), self) - else: - self.oneLineDown() - else: - super(TetrixBoard, self).timerEvent(event) - - def clearBoard(self): - self.board = [NoShape for i in range(TetrixBoard.BoardHeight * TetrixBoard.BoardWidth)] - - def dropDown(self): - dropHeight = 0 - newY = self.curY - while newY > 0: - if not self.tryMove(self.curPiece, self.curX, newY - 1): - break - newY -= 1 - dropHeight += 1 - - self.pieceDropped(dropHeight) - - def oneLineDown(self): - if not self.tryMove(self.curPiece, self.curX, self.curY - 1): - self.pieceDropped(0) - - def pieceDropped(self, dropHeight): - for i in range(4): - x = self.curX + self.curPiece.x(i) - y = self.curY - self.curPiece.y(i) - self.setShapeAt(x, y, self.curPiece.shape()) - - self.numPiecesDropped += 1 - if self.numPiecesDropped % 25 == 0: - self.level += 1 - self.timer.start(self.timeoutTime(), self) - self.levelChanged.emit(self.level) - - self.score += dropHeight + 7 - self.scoreChanged.emit(self.score) - self.removeFullLines() - - if not self.isWaitingAfterLine: - self.newPiece() - - def removeFullLines(self): - numFullLines = 0 - - for i in range(TetrixBoard.BoardHeight - 1, -1, -1): - lineIsFull = True - - for j in range(TetrixBoard.BoardWidth): - if self.shapeAt(j, i) == NoShape: - lineIsFull = False - break - - if lineIsFull: - numFullLines += 1 - for k in range(TetrixBoard.BoardHeight - 1): - for j in range(TetrixBoard.BoardWidth): - self.setShapeAt(j, k, self.shapeAt(j, k + 1)) - - for j in range(TetrixBoard.BoardWidth): - self.setShapeAt(j, TetrixBoard.BoardHeight - 1, NoShape) - - if numFullLines > 0: - self.numLinesRemoved += numFullLines - self.score += 10 * numFullLines - self.linesRemovedChanged.emit(self.numLinesRemoved) - self.scoreChanged.emit(self.score) - - self.timer.start(500, self) - self.isWaitingAfterLine = True - self.curPiece.setShape(NoShape) - self.update() - - def newPiece(self): - self.curPiece = self.nextPiece - self.nextPiece.setRandomShape() - self.showNextPiece() - self.curX = TetrixBoard.BoardWidth // 2 + 1 - self.curY = TetrixBoard.BoardHeight - 1 + self.curPiece.minY() - - if not self.tryMove(self.curPiece, self.curX, self.curY): - self.curPiece.setShape(NoShape) - self.timer.stop() - self.isStarted = False - - def showNextPiece(self): - if self.nextPieceLabel is not None: - return - - dx = self.nextPiece.maxX() - self.nextPiece.minX() + 1 - dy = self.nextPiece.maxY() - self.nextPiece.minY() + 1 - - pixmap = QtGui.QPixmap(dx * self.squareWidth(), dy * self.squareHeight()) - painter = QtGui.QPainter(pixmap) - painter.fillRect(pixmap.rect(), self.nextPieceLabel.palette().background()) - - for int in range(4): - x = self.nextPiece.x(i) - self.nextPiece.minX() - y = self.nextPiece.y(i) - self.nextPiece.minY() - self.drawSquare(painter, x * self.squareWidth(), - y * self.squareHeight(), self.nextPiece.shape()) - - self.nextPieceLabel.setPixmap(pixmap) - - def tryMove(self, newPiece, newX, newY): - for i in range(4): - x = newX + newPiece.x(i) - y = newY - newPiece.y(i) - if x < 0 or x >= TetrixBoard.BoardWidth or y < 0 or y >= TetrixBoard.BoardHeight: - return False - if self.shapeAt(x, y) != NoShape: - return False - - self.curPiece = newPiece - self.curX = newX - self.curY = newY - self.update() - return True - - def drawSquare(self, painter, x, y, shape): - colorTable = [0x000000, 0xCC6666, 0x66CC66, 0x6666CC, - 0xCCCC66, 0xCC66CC, 0x66CCCC, 0xDAAA00] - - color = QtGui.QColor(colorTable[shape]) - painter.fillRect(x + 1, y + 1, self.squareWidth() - 2, - self.squareHeight() - 2, color) - - painter.setPen(color.lighter()) - painter.drawLine(x, y + self.squareHeight() - 1, x, y) - painter.drawLine(x, y, x + self.squareWidth() - 1, y) - - painter.setPen(color.darker()) - painter.drawLine(x + 1, y + self.squareHeight() - 1, - x + self.squareWidth() - 1, y + self.squareHeight() - 1) - painter.drawLine(x + self.squareWidth() - 1, - y + self.squareHeight() - 1, x + self.squareWidth() - 1, y + 1) - - -class TetrixPiece(object): - coordsTable = ( - ((0, 0), (0, 0), (0, 0), (0, 0)), - ((0, -1), (0, 0), (-1, 0), (-1, 1)), - ((0, -1), (0, 0), (1, 0), (1, 1)), - ((0, -1), (0, 0), (0, 1), (0, 2)), - ((-1, 0), (0, 0), (1, 0), (0, 1)), - ((0, 0), (1, 0), (0, 1), (1, 1)), - ((-1, -1), (0, -1), (0, 0), (0, 1)), - ((1, -1), (0, -1), (0, 0), (0, 1)) - ) - - def __init__(self): - self.coords = [[0,0] for _ in range(4)] - self.pieceShape = NoShape - - self.setShape(NoShape) - - def shape(self): - return self.pieceShape - - def setShape(self, shape): - table = TetrixPiece.coordsTable[shape] - for i in range(4): - for j in range(2): - self.coords[i][j] = table[i][j] - - self.pieceShape = shape - - def setRandomShape(self): - self.setShape(random.randint(1, 7)) - - def x(self, index): - return self.coords[index][0] - - def y(self, index): - return self.coords[index][1] - - def setX(self, index, x): - self.coords[index][0] = x - - def setY(self, index, y): - self.coords[index][1] = y - - def minX(self): - m = self.coords[0][0] - for i in range(4): - m = min(m, self.coords[i][0]) - - return m - - def maxX(self): - m = self.coords[0][0] - for i in range(4): - m = max(m, self.coords[i][0]) - - return m - - def minY(self): - m = self.coords[0][1] - for i in range(4): - m = min(m, self.coords[i][1]) - - return m - - def maxY(self): - m = self.coords[0][1] - for i in range(4): - m = max(m, self.coords[i][1]) - - return m - - def rotatedLeft(self): - if self.pieceShape == SquareShape: - return self - - result = TetrixPiece() - result.pieceShape = self.pieceShape - for i in range(4): - result.setX(i, self.y(i)) - result.setY(i, -self.x(i)) - - return result - - def rotatedRight(self): - if self.pieceShape == SquareShape: - return self - - result = TetrixPiece() - result.pieceShape = self.pieceShape - for i in range(4): - result.setX(i, -self.y(i)) - result.setY(i, self.x(i)) - - return result - - -if __name__ == '__main__': - - import sys - - app = QtWidgets.QApplication(sys.argv) - window = TetrixWindow() - window.show() - random.seed(None) - sys.exit(app.exec_()) diff --git a/examples/widgets/widgets/tetrix/doc/tetrix-screenshot.png b/examples/widgets/widgets/tetrix/doc/tetrix-screenshot.png Binary files differnew file mode 100644 index 000000000..2c3dade39 --- /dev/null +++ b/examples/widgets/widgets/tetrix/doc/tetrix-screenshot.png diff --git a/examples/widgets/widgets/tetrix/doc/tetrix.rst b/examples/widgets/widgets/tetrix/doc/tetrix.rst new file mode 100644 index 000000000..0749de9de --- /dev/null +++ b/examples/widgets/widgets/tetrix/doc/tetrix.rst @@ -0,0 +1,38 @@ +Tetrix +====== + +The Tetrix example is a Qt version of the classic Tetrix game. + +.. image:: tetrix-screenshot.png + :width: 400 + :alt: Tetrix main window + +The object of the game is to stack pieces dropped from the top of the playing +area so that they fill entire rows at the bottom of the playing area. + +When a row is filled, all the blocks on that row are removed, the player earns +a number of points, and the pieces above are moved down to occupy that row. If +more than one row is filled, the blocks on each row are removed, and the player +earns extra points. + +The **Left** cursor key moves the current piece one space to the left, the +**Right** cursor key moves it one space to the right, the **Up** cursor key +rotates the piece counter-clockwise by 90 degrees, and the **Down** cursor key +rotates the piece clockwise by 90 degrees. + +To avoid waiting for a piece to fall to the bottom of the board, press **D** to +immediately move the piece down by one row, or press the **Space** key to drop +it as close to the bottom of the board as possible. + +This example shows how a simple game can be created using only three classes: + +* The ``TetrixWindow`` class is used to display the player's score, number of + lives, and information about the next piece to appear. +* The ``TetrixBoard`` class contains the game logic, handles keyboard input, and + displays the pieces on the playing area. +* The ``TetrixPiece`` class contains information about each piece. + +In this approach, the ``TetrixBoard`` class is the most complex class, since it +handles the game logic and rendering. One benefit of this is that the +``TetrixWindow`` and ``TetrixPiece`` classes are very simple and contain only a +minimum of code. diff --git a/examples/widgets/widgets/tetrix/tetrix.py b/examples/widgets/widgets/tetrix/tetrix.py new file mode 100644 index 000000000..b5df2aa35 --- /dev/null +++ b/examples/widgets/widgets/tetrix/tetrix.py @@ -0,0 +1,472 @@ +# Copyright (C) 2013 Riverbank Computing Limited. +# Copyright (C) 2022 The Qt Company Ltd. +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +"""PySide6 port of the widgets/widgets/tetrix example from Qt v5.x""" + +from enum import IntEnum +import random +import sys + +from PySide6.QtCore import QBasicTimer, QSize, Qt, Signal, Slot +from PySide6.QtGui import QColor, QPainter, QPixmap +from PySide6.QtWidgets import (QApplication, QFrame, QGridLayout, QLabel, + QLCDNumber, QPushButton, QWidget) + + +class Piece(IntEnum): + NoShape = 0 + ZShape = 1 + SShape = 2 + LineShape = 3 + TShape = 4 + SquareShape = 5 + LShape = 6 + MirroredLShape = 7 + + +class TetrixWindow(QWidget): + def __init__(self): + super().__init__() + + self.board = TetrixBoard() + + next_piece_label = QLabel() + next_piece_label.setFrameStyle(QFrame.Box | QFrame.Raised) + next_piece_label.setAlignment(Qt.AlignCenter) + self.board.set_next_piece_label(next_piece_label) + + score_lcd = QLCDNumber(5) + score_lcd.setSegmentStyle(QLCDNumber.Filled) + level_lcd = QLCDNumber(2) + level_lcd.setSegmentStyle(QLCDNumber.Filled) + lines_lcd = QLCDNumber(5) + lines_lcd.setSegmentStyle(QLCDNumber.Filled) + + start_button = QPushButton("&Start") + start_button.setFocusPolicy(Qt.NoFocus) + quit_button = QPushButton("&Quit") + quit_button.setFocusPolicy(Qt.NoFocus) + pause_button = QPushButton("&Pause") + pause_button.setFocusPolicy(Qt.NoFocus) + + start_button.clicked.connect(self.board.start) + pause_button.clicked.connect(self.board.pause) + quit_button.clicked.connect(qApp.quit) # noqa: F821 + self.board.score_changed.connect(score_lcd.display) + self.board.level_changed.connect(level_lcd.display) + self.board.lines_removed_changed.connect(lines_lcd.display) + + layout = QGridLayout(self) + layout.addWidget(self.create_label("NEXT"), 0, 0) + layout.addWidget(next_piece_label, 1, 0) + layout.addWidget(self.create_label("LEVEL"), 2, 0) + layout.addWidget(level_lcd, 3, 0) + layout.addWidget(start_button, 4, 0) + layout.addWidget(self.board, 0, 1, 6, 1) + layout.addWidget(self.create_label("SCORE"), 0, 2) + layout.addWidget(score_lcd, 1, 2) + layout.addWidget(self.create_label("LINES REMOVED"), 2, 2) + layout.addWidget(lines_lcd, 3, 2) + layout.addWidget(quit_button, 4, 2) + layout.addWidget(pause_button, 5, 2) + + self.setWindowTitle("Tetrix") + self.resize(550, 370) + + def create_label(self, text): + lbl = QLabel(text) + lbl.setAlignment(Qt.AlignHCenter | Qt.AlignBottom) + return lbl + + +class TetrixBoard(QFrame): + board_width = 10 + board_height = 22 + + score_changed = Signal(int) + + level_changed = Signal(int) + + lines_removed_changed = Signal(int) + + def __init__(self, parent=None): + super().__init__(parent) + + self.timer = QBasicTimer() + self.nextPieceLabel = None + self._is_waiting_after_line = False + self._cur_piece = TetrixPiece() + self._next_piece = TetrixPiece() + self._cur_x = 0 + self._cur_y = 0 + self._num_lines_removed = 0 + self._num_pieces_dropped = 0 + self.score = 0 + self.level = 0 + self.board = None + + self.setFrameStyle(QFrame.Panel | QFrame.Sunken) + self.setFocusPolicy(Qt.StrongFocus) + self._is_started = False + self._is_paused = False + self.clear_board() + + self._next_piece.set_random_shape() + + def shape_at(self, x, y): + return self.board[(y * TetrixBoard.board_width) + x] + + def set_shape_at(self, x, y, shape): + self.board[(y * TetrixBoard.board_width) + x] = shape + + def timeout_time(self): + return 1000 / (1 + self.level) + + def square_width(self): + return self.contentsRect().width() / TetrixBoard.board_width + + def square_height(self): + return self.contentsRect().height() / TetrixBoard.board_height + + def set_next_piece_label(self, label): + self.nextPieceLabel = label + + def sizeHint(self): + return QSize(TetrixBoard.board_width * 15 + self.frameWidth() * 2, + TetrixBoard.board_height * 15 + self.frameWidth() * 2) + + def minimum_size_hint(self): + return QSize(TetrixBoard.board_width * 5 + self.frameWidth() * 2, + TetrixBoard.board_height * 5 + self.frameWidth() * 2) + + @Slot() + def start(self): + if self._is_paused: + return + + self._is_started = True + self._is_waiting_after_line = False + self._num_lines_removed = 0 + self._num_pieces_dropped = 0 + self.score = 0 + self.level = 1 + self.clear_board() + + self.lines_removed_changed.emit(self._num_lines_removed) + self.score_changed.emit(self.score) + self.level_changed.emit(self.level) + + self.new_piece() + self.timer.start(self.timeout_time(), self) + + @Slot() + def pause(self): + if not self._is_started: + return + + self._is_paused = not self._is_paused + if self._is_paused: + self.timer.stop() + else: + self.timer.start(self.timeout_time(), self) + + self.update() + + def paintEvent(self, event): + super(TetrixBoard, self).paintEvent(event) + + with QPainter(self) as painter: + rect = self.contentsRect() + + if self._is_paused: + painter.drawText(rect, Qt.AlignCenter, "Pause") + return + + board_top = rect.bottom() - TetrixBoard.board_height * self.square_height() + + for i in range(TetrixBoard.board_height): + for j in range(TetrixBoard.board_width): + shape = self.shape_at(j, TetrixBoard.board_height - i - 1) + if shape != Piece.NoShape: + self.draw_square(painter, + rect.left() + j * self.square_width(), + board_top + i * self.square_height(), shape) + + if self._cur_piece.shape() != Piece.NoShape: + for i in range(4): + x = self._cur_x + self._cur_piece.x(i) + y = self._cur_y - self._cur_piece.y(i) + self.draw_square(painter, rect.left() + x * self.square_width(), + board_top + + (TetrixBoard.board_height - y - 1) * self.square_height(), + self._cur_piece.shape()) + + def keyPressEvent(self, event): + if not self._is_started or self._is_paused or self._cur_piece.shape() == Piece.NoShape: + super(TetrixBoard, self).keyPressEvent(event) + return + + key = event.key() + if key == Qt.Key_Left: + self.try_move(self._cur_piece, self._cur_x - 1, self._cur_y) + elif key == Qt.Key_Right: + self.try_move(self._cur_piece, self._cur_x + 1, self._cur_y) + elif key == Qt.Key_Down: + self.try_move(self._cur_piece.rotated_right(), self._cur_x, self._cur_y) + elif key == Qt.Key_Up: + self.try_move(self._cur_piece.rotated_left(), self._cur_x, self._cur_y) + elif key == Qt.Key_Space: + self.drop_down() + elif key == Qt.Key_D: + self.one_line_down() + else: + super(TetrixBoard, self).keyPressEvent(event) + + def timerEvent(self, event): + if event.timerId() == self.timer.timerId(): + if self._is_waiting_after_line: + self._is_waiting_after_line = False + self.new_piece() + self.timer.start(self.timeout_time(), self) + else: + self.one_line_down() + else: + super(TetrixBoard, self).timerEvent(event) + + def clear_board(self): + self.board = [ + Piece.NoShape for _ in range(TetrixBoard.board_height * TetrixBoard.board_width)] + + def drop_down(self): + drop_height = 0 + new_y = self._cur_y + while new_y > 0: + if not self.try_move(self._cur_piece, self._cur_x, new_y - 1): + break + new_y -= 1 + drop_height += 1 + + self.piece_dropped(drop_height) + + def one_line_down(self): + if not self.try_move(self._cur_piece, self._cur_x, self._cur_y - 1): + self.piece_dropped(0) + + def piece_dropped(self, dropHeight): + for i in range(4): + x = self._cur_x + self._cur_piece.x(i) + y = self._cur_y - self._cur_piece.y(i) + self.set_shape_at(x, y, self._cur_piece.shape()) + + self._num_pieces_dropped += 1 + if self._num_pieces_dropped % 25 == 0: + self.level += 1 + self.timer.start(self.timeout_time(), self) + self.level_changed.emit(self.level) + + self.score += dropHeight + 7 + self.score_changed.emit(self.score) + self.remove_full_lines() + + if not self._is_waiting_after_line: + self.new_piece() + + def remove_full_lines(self): + num_full_lines = 0 + + for i in range(TetrixBoard.board_height - 1, -1, -1): + line_is_full = True + + for j in range(TetrixBoard.board_width): + if self.shape_at(j, i) == Piece.NoShape: + line_is_full = False + break + + if line_is_full: + num_full_lines += 1 + for k in range(i, TetrixBoard.board_height - 1): + for j in range(TetrixBoard.board_width): + self.set_shape_at(j, k, self.shape_at(j, k + 1)) + + for j in range(TetrixBoard.board_width): + self.set_shape_at(j, TetrixBoard.board_height - 1, Piece.NoShape) + + if num_full_lines > 0: + self._num_lines_removed += num_full_lines + self.score += 10 * num_full_lines + self.lines_removed_changed.emit(self._num_lines_removed) + self.score_changed.emit(self.score) + + self.timer.start(500, self) + self._is_waiting_after_line = True + self._cur_piece.set_shape(Piece.NoShape) + self.update() + + def new_piece(self): + self._cur_piece = self._next_piece + self._next_piece.set_random_shape() + self.show_next_piece() + self._cur_x = TetrixBoard.board_width // 2 + 1 + self._cur_y = TetrixBoard.board_height - 1 + self._cur_piece.min_y() + + if not self.try_move(self._cur_piece, self._cur_x, self._cur_y): + self._cur_piece.set_shape(Piece.NoShape) + self.timer.stop() + self._is_started = False + + def show_next_piece(self): + if self.nextPieceLabel is not None: + return + + dx = self._next_piece.max_x() - self._next_piece.min_x() + 1 + dy = self._next_piece.max_y() - self._next_piece.min_y() + 1 + + pixmap = QPixmap(dx * self.square_width(), dy * self.square_height()) + with QPainter(pixmap) as painter: + painter.fillRect(pixmap.rect(), self.nextPieceLabel.palette().background()) + + for i in range(4): + x = self._next_piece.x(i) - self._next_piece.min_x() + y = self._next_piece.y(i) - self._next_piece.min_y() + self.draw_square(painter, x * self.square_width(), + y * self.square_height(), self._next_piece.shape()) + + self.nextPieceLabel.setPixmap(pixmap) + + def try_move(self, newPiece, newX, newY): + for i in range(4): + x = newX + newPiece.x(i) + y = newY - newPiece.y(i) + if x < 0 or x >= TetrixBoard.board_width or y < 0 or y >= TetrixBoard.board_height: + return False + if self.shape_at(x, y) != Piece.NoShape: + return False + + self._cur_piece = newPiece + self._cur_x = newX + self._cur_y = newY + self.update() + return True + + def draw_square(self, painter, x, y, shape): + color_table = [0x000000, 0xCC6666, 0x66CC66, 0x6666CC, + 0xCCCC66, 0xCC66CC, 0x66CCCC, 0xDAAA00] + + color = QColor(color_table[shape]) + painter.fillRect(x + 1, y + 1, self.square_width() - 2, self.square_height() - 2, color) + + painter.setPen(color.lighter()) + painter.drawLine(x, y + self.square_height() - 1, x, y) + painter.drawLine(x, y, x + self.square_width() - 1, y) + + painter.setPen(color.darker()) + painter.drawLine(x + 1, y + self.square_height() - 1, + x + self.square_width() - 1, y + self.square_height() - 1) + painter.drawLine(x + self.square_width() - 1, + y + self.square_height() - 1, x + self.square_width() - 1, y + 1) + + +class TetrixPiece(object): + coords_table = ( + ((0, 0), (0, 0), (0, 0), (0, 0)), + ((0, -1), (0, 0), (-1, 0), (-1, 1)), + ((0, -1), (0, 0), (1, 0), (1, 1)), + ((0, -1), (0, 0), (0, 1), (0, 2)), + ((-1, 0), (0, 0), (1, 0), (0, 1)), + ((0, 0), (1, 0), (0, 1), (1, 1)), + ((-1, -1), (0, -1), (0, 0), (0, 1)), + ((1, -1), (0, -1), (0, 0), (0, 1)) + ) + + def __init__(self): + self.coords = [[0, 0] for _ in range(4)] + self._piece_shape = Piece.NoShape + + self.set_shape(Piece.NoShape) + + def shape(self): + return self._piece_shape + + def set_shape(self, shape): + table = TetrixPiece.coords_table[shape] + for i in range(4): + for j in range(2): + self.coords[i][j] = table[i][j] + + self._piece_shape = shape + + def set_random_shape(self): + self.set_shape(random.randint(1, 7)) + + def x(self, index): + return self.coords[index][0] + + def y(self, index): + return self.coords[index][1] + + def set_x(self, index, x): + self.coords[index][0] = x + + def set_y(self, index, y): + self.coords[index][1] = y + + def min_x(self): + m = self.coords[0][0] + for i in range(4): + m = min(m, self.coords[i][0]) + + return m + + def max_x(self): + m = self.coords[0][0] + for i in range(4): + m = max(m, self.coords[i][0]) + + return m + + def min_y(self): + m = self.coords[0][1] + for i in range(4): + m = min(m, self.coords[i][1]) + + return m + + def max_y(self): + m = self.coords[0][1] + for i in range(4): + m = max(m, self.coords[i][1]) + + return m + + def rotated_left(self): + if self._piece_shape == Piece.SquareShape: + return self + + result = TetrixPiece() + result._piece_shape = self._piece_shape + for i in range(4): + result.set_x(i, self.y(i)) + result.set_y(i, -self.x(i)) + + return result + + def rotated_right(self): + if self._piece_shape == Piece.SquareShape: + return self + + result = TetrixPiece() + result._piece_shape = self._piece_shape + for i in range(4): + result.set_x(i, -self.y(i)) + result.set_y(i, self.x(i)) + + return result + + +if __name__ == '__main__': + app = QApplication(sys.argv) + window = TetrixWindow() + window.show() + random.seed(None) + sys.exit(app.exec()) diff --git a/examples/widgets/widgets/tetrix/tetrix.pyproject b/examples/widgets/widgets/tetrix/tetrix.pyproject new file mode 100644 index 000000000..75121ea64 --- /dev/null +++ b/examples/widgets/widgets/tetrix/tetrix.pyproject @@ -0,0 +1,3 @@ +{ + "files": ["tetrix.py"] +} diff --git a/examples/widgets/widgets/widgets.pyproject b/examples/widgets/widgets/widgets.pyproject deleted file mode 100644 index b4e3ef67e..000000000 --- a/examples/widgets/widgets/widgets.pyproject +++ /dev/null @@ -1,3 +0,0 @@ -{ - "files": ["tetrix.py", "hellogl_openglwidget_legacy.py"] -} |