【问题标题】:QGraphicsPathItem .setPen() impacts text styleQGraphicsPathItem .setPen() 影响文本样式
【发布时间】:2020-02-01 14:33:28
【问题描述】:

堆栈溢出社区。让我参考下面的代码解释我的问题

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_())

我的问题是以下几行:

  • pen=QtGui.QPen(QtGui.QColor("black"), 2)
  • self.setPen(笔)

冲击线:

  • path.addText(20, 25, QtGui.QFont('Times', 20), self.__partName)

你知道如何独立添加文字吗?当我尝试添加它时,我遇到的问题是绘图和文本没有连接,只有符号可以用鼠标移动,而不能同时移动(绘图和文本)。

【问题讨论】:

    标签: python python-3.x pyqt pyqt5 qgraphicspathitem


    【解决方案1】:

    一种可能的解决方案是创建另一个 QGraphicsPathItem 作为项目的子项,这样相对坐标不会改变,并且父项的 QPen 不会影响他。

    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)
    

    【讨论】:

    • 谢谢。这是一个聪明的解决方案。根据您的建议,信件未填写。只有轮廓是黑色的。是否也可以用黑色填充字母?
    • 谢谢,这正是我想要的。
    猜你喜欢
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    • 2020-01-14
    • 2015-09-07
    相关资源
    最近更新 更多