【问题标题】:How to dynamically set outline border on the matplotlib canvas?如何在 matplotlib 画布上动态设置轮廓边框?
【发布时间】:2021-09-24 12:52:20
【问题描述】:

我有 9 个由 matplotlib 在我的 PyQt5 GUI 上绘制的画布,可以在这里看到:

画布是动态生成的:

class Canvas(FigureCanvas):
    def __init__(self, parent=None):
        super().__init__(Figure(figsize=(5, 3)))
        self.setParent(parent)
        self.mpl_connect("button_press_event", self.on_press)

    def on_press(self, event):
        print(self, event)

canvas = Canvas()
ax = canvas.figure.subplots()
ax.plot(x, y_leak, '--rs', label='Y_leak')
ax.plot(x, y_lin, '-g*', label='Y_lin')
ax.plot(x, y_sat, ':bo', label='Y_sat')
ax.legend()

我的问题是如何在调用 on_press 事件时为它们中的每一个设置画布的轮廓边框,如下所示。:

【问题讨论】:

    标签: python matplotlib pyqt pyqt5


    【解决方案1】:

    Qt 实现的一个解决方案是使用一个标志来指示画布是否被按下,然后使用该信息绘制边框覆盖paintEvent 方法。

    class Canvas(FigureCanvas):
        def __init__(self, parent=None):
            super().__init__(Figure(figsize=(5, 3)))
            self.setParent(parent)
            self.mpl_connect("button_press_event", self.on_press)
            self._draw_border = False
    
        def on_press(self, event):
            self._draw_border = True
            self.update()
    
        def paintEvent(self, event):
            super().paintEvent(event)
            if self._draw_border:
                painter = QPainter(self)
                pen_width = 5
                painter.setPen(QPen(QColor("#00ff00"), 2 * pen_width))
                painter.drawRect(self.rect())
    

    【讨论】:

    • 非常感谢,您总是回答我的问题。我很感激!它有效,但我只是注意到我也忘了提及如何删除此边框。您介意我编辑问题并提出问题吗?
    • @justRandomLearner 如果你想去掉边框那么就做 self._draw_border = False self.update() ,请理解我的回答,不要只是复制代码。
    • 当然,我是 PyQt5 的新手,并试图学习它以备将来使用,但由于我不知道 .update() 函数是如何工作的,所以我不太了解它。现在很清楚了。
    猜你喜欢
    • 1970-01-01
    • 2013-09-21
    • 2023-03-24
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 2015-07-30
    相关资源
    最近更新 更多