在下图中,我将场景中的QGraphicsPathItem
作为红色部分,并将其形状覆盖为蓝色部分。我想要当红色空间被拖动和移动时,项目被线性地加长或缩短,当蓝色空间被拖动时,整个项目必须被移动。
这是我试过的
import sys
from PyQt5.QtCore import QRectF, Qt, QPointF
from PyQt5.QtGui import QPainterPath, QPen, QPainterPathStroker, QPainter
from PyQt5.QtWidgets import QApplication, QMainWindow, QGraphicsScene, QGraphicsView, QGraphicsPathItem, QGraphicsItem
class Item(QGraphicsPathItem):
circle = QPainterPath()
circle.addEllipse(QRectF(-5, -5, 10, 10))
def __init__(self):
super(Item, self).__init__()
self.setPath(Item.circle)
self.setFlag(QGraphicsItem.ItemIsSelectable, True)
self.setFlag(QGraphicsItem.ItemIsMovable, True)
def paint(self, painter, option, widget):
color = Qt.red if self.isSelected() else Qt.black
painter.setPen(QPen(color, 2, Qt.SolidLine))
painter.drawPath(self.path())
# To paint path of shape
painter.setPen(QPen(Qt.blue, 1, Qt.SolidLine))
painter.drawPath(self.shape())
def shape(self):
startPoint = self.mapFromScene(self.pos())
endPoint = self.mapFromScene(QPointF(10, 10))
path = QPainterPath(startPoint)
path.lineTo(endPoint)
stroke = QPainterPathStroker()
stroke.setWidth(10)
return stroke.createStroke(path)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = QMainWindow()
window.show()
scene = QGraphicsScene()
scene.setSceneRect(0, 0, 200, 200)
view = QGraphicsView()
view.setScene(scene)
window.setCentralWidget(view)
scene.addItem(Item())
sys.exit(app.exec_())
在同一个项目中处理大小调整和拉伸任务是复杂的,因此为了避免这种情况,我使用了两个项目:一个手柄和一个管道。因此,每个人管理自己的任务并更新其他元素的位置:
更新:
如果您想要实现您想要的逻辑,那么它就更复杂了。错误的原因是paint()方法使用boundingRect()设置绘制区域,但在您的情况下,它没有考虑到绘制区域的变化,可能的解决方案如下:
相关问题 更多 >
编程相关推荐