我正在使用Python 3.6和PyQt-5.9.1和Qt Designer进行UI设计的应用程序,我需要包括一些matplotlib图。
经过一番挖掘,我发现为了不每次更新gui部分(这是Qt Designer所期望的)时都不修改从ui文件生成的python代码,我需要在Qt Designer中设置MatplotlibWidget插件。
我的问题是,我为此插件找到的引用来自基于Python 2.7的Python(x,y)包,而无法与Python 3.x一起使用。或在Python 3.x / Qt5环境中不起作用的PyQtdesginerplugins软件包(已在此问题How do I add matplotlib plugin to Qt5.4 Designer plugins?中指出)。
在我的Python 3.6和Qt5环境中,是否有可能将MatplotlibWidget添加到Qt Designer中?在将ui与应用程序逻辑隔离时,这将在很大程度上利用Qt Designer的优势。
最佳答案
在下面,您将找到Qt Designer的MatplotlibPlugin的PyQt5版本。
要使用它,请将两个文件都放在PYQTDESIGNERPATH
环境变量中包含的目录中,或者放在directories that Qt Designer searches for its own plugins之一内的“ python”子目录中。这两个文件的命名必须完全如下所示。
matplotlibwidget.py:
from PyQt5.QtCore import QSize
from PyQt5.QtWidgets import QSizePolicy
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as Canvas
from matplotlib.figure import Figure
from matplotlib import rcParams
rcParams['font.size'] = 9
class MatplotlibWidget(Canvas):
def __init__(self, parent=None, title='', xlabel='', ylabel='',
xlim=None, ylim=None, xscale='linear', yscale='linear',
width=4, height=3, dpi=100):
self.figure = Figure(figsize=(width, height), dpi=dpi)
self.axes = self.figure.add_subplot(111)
self.axes.set_title(title)
self.axes.set_xlabel(xlabel)
self.axes.set_ylabel(ylabel)
if xscale is not None:
self.axes.set_xscale(xscale)
if yscale is not None:
self.axes.set_yscale(yscale)
if xlim is not None:
self.axes.set_xlim(*xlim)
if ylim is not None:
self.axes.set_ylim(*ylim)
super(MatplotlibWidget, self).__init__(self.figure)
self.setParent(parent)
super(MatplotlibWidget, self).setSizePolicy(
QSizePolicy.Expanding, QSizePolicy.Expanding)
super(MatplotlibWidget, self).updateGeometry()
def sizeHint(self):
return QSize(*self.get_width_height())
def minimumSizeHint(self):
return QSize(10, 10)
matplotlibplugin.py:
import os
from PyQt5.QtGui import QIcon
from PyQt5.QtDesigner import QPyDesignerCustomWidgetPlugin
from matplotlib import rcParams
from matplotlibwidget import MatplotlibWidget
rcParams['font.size'] = 9
class MatplotlibPlugin(QPyDesignerCustomWidgetPlugin):
def __init__(self, parent=None):
super(MatplotlibPlugin, self).__init__(parent)
self._initialized = False
def initialize(self, editor):
self._initialized = True
def isInitialized(self):
return self._initialized
def createWidget(self, parent):
return MatplotlibWidget(parent)
def name(self):
return 'MatplotlibWidget'
def group(self):
return 'PyQt'
def icon(self):
return QIcon(os.path.join(
rcParams['datapath'], 'images', 'matplotlib.png'))
def toolTip(self):
return ''
def whatsThis(self):
return ''
def isContainer(self):
return False
def domXml(self):
return '<widget class="MatplotlibWidget" name="mplwidget">\n' \
'</widget>\n'
def includeFile(self):
return 'matplotlibwidget'
关于python - Qt5 Matplotlib Designer插件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47364804/