stack overflow community. Let me explain my question refering to the code snipped below
from PyQt5 import QtCore, QtGui, QtWidgets
class PortItem(QtWidgets.QGraphicsPathItem):
def __init__(self, parent=None):
super().__init__(parent)
pen=QtGui.QPen(QtGui.QColor("black"), 2)
self.setPen(pen)
self.end_ports = []
self.setFlags(QtWidgets.QGraphicsItem.ItemIsMovable | QtWidgets.QGraphicsItem.ItemSendsGeometryChanges)
class Symbol_Z(PortItem):
__partCounter=0
def __init__(self):
super().__init__()
self.__partName= "FixedTerms"
self.__partCounter+=1
self.drawSymbol()
def drawSymbol(self):
path=QtGui.QPainterPath()
path.moveTo(0, 40)
path.lineTo(20, 40)
path.addRect(QtCore.QRectF(20, 30, 40, 20))
path.moveTo(60, 40)
path.lineTo(80, 40)
path.addText(20, 25, QtGui.QFont('Times', 20), self.__partName)
self.setPath(path)
class GraphicsView(QtWidgets.QGraphicsView):
def __init__(self, scene=None, parent=None):
super().__init__(scene, parent)
self.setRenderHints(QtGui.QPainter.Antialiasing)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
scene=QtWidgets.QGraphicsScene()
graphicsview=GraphicsView(scene)
item=Symbol_Z()
item.setPos(QtCore.QPointF(0, 250))
scene.addItem(item)
self.setCentralWidget(graphicsview)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())
My problem is that the lines:
impact the line:
Do you know how to add text independet? When I tried to add it I had the problem that the drawing and the text are not connected and only the symbol could be mouved with the mouse and not both (drawing and text) together.
One possible solution is to create another QGraphicsPathItem that is the child of the item so the relative coordinates will not change and the parent's QPen will not affect him.
def drawSymbol(self):
path = QtGui.QPainterPath()
path.moveTo(0, 40)
path.lineTo(20, 40)
path.addRect(QtCore.QRectF(20, 30, 40, 20))
path.moveTo(60, 40)
path.lineTo(80, 40)
self.setPath(path)
text_item = QtWidgets.QGraphicsPathItem(self)
text_item.setBrush(QtGui.QColor("black"))
child_path = QtGui.QPainterPath()
child_path.addText(20, 25, QtGui.QFont("Times", 20), self.__partName)
text_item.setPath(child_path)