Pyqt小部件FigureCanvas边框和内容共存

问题描述 投票:0回答:1

我想要一个小部件,它可以使用matplotlib绘制图像,并且可以设置其边框。

所以我要创建一个类,它的父级是FigureCanvas,可以绘制图像。似乎设置边框必须重写paintEvent方法,所以我这样做。但是我发现当我重写paintEvent方法时,绘制失败。

[当我注意到paintEvent方法方法时,绘制成功。

谁可以帮助我改进代码或给我一些提示。

import pydicom
from PyQt4 import QtGui
from matplotlib.backends.backend_template import FigureCanvas
from matplotlib.pylab import *
from PyQt4.QtGui import *
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas


class InstancesFC(FigureCanvas):
    def __init__(self):
        self.figure = plt.figure(figsize=(2, 2))
        super(InstancesFC, self).__init__(self.figure)
        self.update_area()
        self.setObjectName('InstancesFC')
        self.ax = self.figure.add_subplot(111)
        plt.axis('off')
        x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
        y = [23, 21, 32, 13, 3, 132, 13, 3, 1]
        self.ax.plot(x, y)

    def update_area(self):
        self.setStyleSheet("""
            #InstancesFC{
                          border-width: 1px;
             border-style: solid;
             border-color: red;
             min-width:%s;
             max-width:%s;
             min-height:%s;
             max-height:%s;
             padding:0px;
             margin:1px;
            }
        """ % ('300px', '300px', '300px', '300px'))

    def paintEvent(self, event):
        opt = QStyleOption()
        opt.initFrom(self)
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        self.style().drawPrimitive(QStyle.PE_Widget, opt, painter, self)


class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):
        h = QtGui.QHBoxLayout()
        h.addWidget(InstancesFC())
        self.setLayout(h)
        self.setGeometry(100, 100, 500, 500)
        self.show()


def main():
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
python matplotlib pyqt
1个回答
0
投票

当您重写paintEvent()方法时,如果不调用父方法,则将消除导致观察到的问题的默认行为。解决方法是调用父对象的paintEvent()方法。

def paintEvent(self, event):
    super(InstancesFC, self).paintEvent(event)
    opt = QStyleOption()
    opt.initFrom(self)
    painter = QPainter(self)
    painter.setRenderHint(QPainter.Antialiasing)
    self.style().drawPrimitive(QStyle.PE_Widget, opt, painter, self)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.