我试图了解path1.subtracted(path2)
的工作原理。
以下是代码:
from PyQt5.QtCore import QPointF
from PyQt5.QtCore import QRectF, Qt
from PyQt5.QtGui import QPainterPath, QPen
from PyQt5.QtGui import QPolygonF
from PyQt5.QtWidgets import QApplication, QGraphicsScene, \
QGraphicsView, QPushButton, QWidget, \
QVBoxLayout, QGraphicsItem, QGraphicsPathItem, QGraphicsRectItem
class Window(QWidget):
scene = None
def __init__(self):
QWidget.__init__(self)
self.view = View(self)
self.button = QPushButton('Clear View', self)
self.button.clicked.connect(self.handleClearView)
layout = QVBoxLayout(self)
layout.addWidget(self.view)
layout.addWidget(self.button)
def handleClearView(self):
self.view.scene.clear()
class View(QGraphicsView):
def __init__(self, parent):
self.scribing = False
self.erasing = False
QGraphicsView.__init__(self, parent)
self.scene = QGraphicsScene()
self.setScene(self.scene)
def resizeEvent(self, QResizeEvent):
self.setSceneRect(QRectF(self.viewport().rect()))
def mousePressEvent(self, event):
if event.buttons() == Qt.LeftButton:
self.scribing = True
self.path1 = QPainterPath()
self.path2 = QPainterPath()
self.polygon1 = QPolygonF()
self.polygon1.append(QPointF(100,100))
self.polygon1.append(QPointF(100, 300))
self.polygon1.append(QPointF(300, 300))
self.polygon1.append(QPointF(300, 100))
self.polygon2 = QPolygonF()
self.polygon2.append(QPointF(300,100))
self.polygon2.append(QPointF(300, 300))
self.polygon2.append(QPointF(100, 300))
self.path1.addPolygon(self.polygon1)
self.path2.addPolygon(self.polygon2)
path3 = self.path1.subtracted(self.path2)
# self.scene.addPath(self.path1, QPen(Qt.blue))
# self.scene.addPath(self.path2, QPen(Qt.green))
self.scene.addPath(path3, QPen(Qt.red))
if event.buttons() == Qt.RightButton:
self.erasing = True
def mouseMoveEvent(self, event):
if (event.buttons() & Qt.LeftButton) and self.scribing:
if self.free_draw_item:
pass
if event.buttons() & Qt.RightButton and self.erasing:
pass
def mouseReleaseEvent(self, event):
self.scribing = False
self.erasing = False
# if self.eraser_item != None:
# self.scene.removeItem(self.eraser_item)
# if self.free_draw_item != None:
# self.free_draw_item.setSelected(True)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = Window()
window.resize(640, 480)
window.show()
sys.exit(app.exec_())
在此示例中,我使用了QPolygonF
。我还尝试创建p1=QPainterPath()
,p2=QPainterPath()
并减去p3
。但是,没有成功,得到相同的结果。
答案 0 :(得分:1)
QpainterPath.subtracted()
不会减去路径元素,而是减去路径区域,
see documentation
如果使用QpainterPath::operator-()
,效果相同:
# path3 = self.path1.subtracted(self.path2)
path3 = self.path1 – self.path2
您可以通过类似的内容识别路径的元素
c = path3.elementCount()
for i in range(c):
e = path3.elementAt(i)
print('Element-nr.: ', i, 'Type: ', e.type, 'x: ', e.x, 'y: ', e.y) # type: 0 = MoveTo, 1 = LineTo
我认为,你必须编写一个自己的方法,它从path1和path2的元素创建path3。