【问题标题】:How to draw custom oval shape in PyQt?如何在 PyQt 中绘制自定义椭圆形状?
【发布时间】:2021-11-13 21:23:32
【问题描述】:

所以我一直在尝试使用 QGraphicsEllipseItem 制作自定义椭圆形状。

在阅读了关于QGraphicsEllipseItem 的Qt 官方文档后,我似乎没有找到如何管理它。

这是自定义的椭圆形状:

【问题讨论】:

  • 这看起来不是“椭圆形”,它更像是一条复杂的曲线。考虑到这一点,请提供一个minimal reproducible example 来说明您迄今为止所做的尝试,因为现在您的问题太模糊,我们不提供广泛方面的答案。另外请花点时间查看tour 并阅读How to Ask
  • 嗨@musicamante 感谢您的反馈。我已阅读您的建议,我会确保牢记这些指导方针。我没有提供代码,因为我的代码仅包含使用 QGraphicsEllipseItem 制作的形状,我认为这不是绘制复杂曲线的可能方法。

标签: python pyqt pyqt5 pyside pyside2


【解决方案1】:

如果你想实现复杂的形状,那么一个可能的解决方案是使用 QPainterPathItem:

from PyQt5.QtCore import QRectF
from PyQt5.QtGui import QColor, QPainterPath
from PyQt5.QtWidgets import (
    QApplication,
    QGraphicsPathItem,
    QGraphicsScene,
    QGraphicsView,
)


def main():
    app = QApplication([])

    radius = 20
    length = 100

    square = QRectF(0, 0, 2 * radius, 2 * radius)

    path = QPainterPath()
    path.moveTo(radius, 0)
    path.arcTo(square, 90, 180)
    path.lineTo(length, 2 * radius)
    square.moveRight(length + 2 * radius)
    path.arcTo(square, -90, 180)
    path.lineTo(radius, 0)

    item = QGraphicsPathItem()
    item.setBrush(QColor("red"))
    item.setPen(QColor("green"))
    item.setPath(path)

    scene = QGraphicsScene()
    view = QGraphicsView(scene)
    scene.addItem(item)
    view.show()

    app.exec_()


main()

【讨论】:

  • 嗨@eyllanesc,非常感谢您的帮助!您对我在哪里可以找到更多学习 QGraphicsPathItem 的示例有什么建议吗?我已经阅读了官方的 Qt 文档,但仍然没有清楚地掌握所有内容。再次感谢。
  • @husniandre 你应该检查doc.qt.io/qt-5/qpainterpath.html
  • 我看过你对很多 PyQt 问题的回答,我相信你的工作帮助了很多其他人。非常感谢@eyllanesc 的支持!
猜你喜欢
  • 2015-11-17
  • 1970-01-01
  • 2017-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多