简体   繁体   中英

Pyqt widget FigureCanvas border and content coexist

i want a widget,it can use matplotlib drawing an image and it can setting it's border.

so i'm create a class,it's parent is FigureCanvas,that i can drawing image. It seems that setting a border must be rewrite paintEvent method,so i do. But i find when i rewrite paintEvent method,drawing failed.

When i note the paintEvent method method,drawing success.

Who can help me improve the code or give me some tips.

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

When you override the paintEvent() method and if you don't call the parent method then you will eliminate the default behavior causing the problem you are observing. The solution is to call the paintEvent() method of the parent.

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)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM