Мне нужен перетаскиваемый прямоугольник по всему холсту, который скроет все, что находится за пределами прямоугольника. Подумайте о «тумане войны» в видеоигре, где вы не можете видеть ничего за пределами прямоугольника.
Каждый из выбранных мной подходов не скрывает все на холсте. Это маленькое приложение помещает на холст несколько зеленых прямоугольников и пытается создать перетаскиваемый прямоугольник, который скроет весь холст отдельно от того, что находится внутри прямоугольника.
import sys
from PyQt6.QtWidgets import QApplication, QGraphicsView, QGraphicsScene, QGraphicsRectItem
from PyQt6.QtGui import QPainter, QPainterPath, QPen, QBrush
from PyQt6.QtCore import QRectF, Qt
class ClipRectItem(QGraphicsRectItem):
def __init__(self, rect):
super().__init__(rect)
self.setFlag(QGraphicsRectItem.GraphicsItemFlag.ItemIsMovable)
self.setFlag(QGraphicsRectItem.GraphicsItemFlag.ItemIsSelectable)
self.setBrush(QBrush(Qt.GlobalColor.transparent))
self.setPen(QPen(Qt.GlobalColor.red, 2, Qt.PenStyle.DashLine))
def paint(self, painter, option, widget):
# Draw the rectangle
painter.setPen(self.pen())
painter.setBrush(self.brush())
painter.drawRect(self.rect())
# Set clipping to only inside the rectangle
clip_path = QPainterPath()
clip_path.addRect(self.rect())
painter.setClipPath(clip_path)
class Example(QGraphicsView):
def __init__(self):
super().__init__()
# Create a scene
self.scene = QGraphicsScene()
self.setScene(self.scene)
self.initUI()
def initUI(self):
# Add some example items to the scene
for i in range(5):
rect_item = QGraphicsRectItem(i * 100, i * 50, 80, 40)
rect_item.setBrush(QBrush(Qt.GlobalColor.green))
self.scene.addItem(rect_item)
# Create a draggable rectangle for clipping
self.clip_rect = ClipRectItem(QRectF(50, 50, 200, 150))
self.scene.addItem(self.clip_rect)
# Set up the view
self.setGeometry(300, 300, 600, 400)
self.setWindowTitle('Clip Outside Rectangle Example')
def drawForeground(self, painter, rect):
if self.clip_rect:
clip_path = QPainterPath()
clip_path.addRect(self.clip_rect.rect())
painter.setClipPath(clip_path)
rectf = QRectF(painter.viewport())
self.scene.render(painter, target=rectf, source=self.sceneRect())
if __name__ == '__main__':
app = QApplication(sys.argv)
view = Example()
view.show()
sys.exit(app.exec())
Подробнее здесь: https://stackoverflow.com/questions/791 ... ps-and-hid
(pyqt6) Как настроить перетаскиваемый прямоугольник обрезки, который полностью обрезает и скрывает все на холсте, что не ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение