在PyQT中,我如何在给定的点上绘制小的“节点”并用边连接它们? 我找到的所有PyQT教程都是“绘制按钮!绘制复选框!”
我曾经很痛苦地寻找一个好的解释(截至2014年底),由于这个问题正是我在寻找的,所以我将发布一个转录(从C++到Python)我在this post中发现的内容。
下面是代码,这里是原理:
QGrahpicsItem
、QPainterPath
和QPainterPath.Element
是你需要寻找的类。特别地,QPainterPath实现了在像CorelDraw、Adobe Illustrator或Inkscape这样的应用程序中所期望的矢量功能。QGraphicsEllipseItem
(用于渲染节点)和QGraphicsPathItem
(用于渲染路径本身),它们都继承自QGraphicsItem
。Path
构造函数遍历QPainterPath
元素,为每个元素创建一个Node
项;每个Node
项会向其父级Path
对象发送更新,该对象随即相应地更新其path
属性。#!/usr/bin/env python
# coding: utf-8
from PyQt4.QtGui import *
from PyQt4.QtCore import *
rad = 5
class Node(QGraphicsEllipseItem):
def __init__(self, path, index):
super(Node, self).__init__(-rad, -rad, 2*rad, 2*rad)
self.rad = rad
self.path = path
self.index = index
self.setZValue(1)
self.setFlag(QGraphicsItem.ItemIsMovable)
self.setFlag(QGraphicsItem.ItemSendsGeometryChanges)
self.setBrush(Qt.green)
def itemChange(self, change, value):
if change == QGraphicsItem.ItemPositionChange:
self.path.updateElement(self.index, value.toPointF())
return QGraphicsEllipseItem.itemChange(self, change, value)
class Path(QGraphicsPathItem):
def __init__(self, path, scene):
super(Path, self).__init__(path)
for i in xrange(path.elementCount()):
node = Node(self, i)
node.setPos(QPointF(path.elementAt(i)))
scene.addItem(node)
self.setPen(QPen(Qt.red, 1.75))
def updateElement(self, index, pos):
path.setElementPositionAt(index, pos.x(), pos.y())
self.setPath(path)
if __name__ == "__main__":
app = QApplication([])
path = QPainterPath()
path.moveTo(0,0)
path.cubicTo(-30, 70, 35, 115, 100, 100);
path.lineTo(200, 100);
path.cubicTo(200, 30, 150, -35, 60, -30);
scene = QGraphicsScene()
scene.addItem(Path(path, scene))
view = QGraphicsView(scene)
view.setRenderHint(QPainter.Antialiasing)
view.resize(600, 400)
view.show()
app.exec_()
QGraphicsItem
开始搜索。 - heltonbikerhoverEnterEvent
和hoverLeaveEvent
,在这里找到。 - heltonbiker