gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:02:33 26 4
gpt4 key购买 nike

我想要一个小部件,它可以使用 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()

最佳答案

当您重写paintEvent()方法并且不调用父方法时,您将消除导致您观察到的问题的默认行为。解决方案是调用父级的paintEvent()方法。

def paintEvent(self, event):
<b>super(InstancesFC, self).paintEvent(event)</b>
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

关于python - Pyqt 小部件FigureCanvas 边框和内容共存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60238552/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com