【问题标题】:How to show matplotlib.pyplot in qt widget?如何在 qt 小部件中显示 matplotlib.pyplot?
【发布时间】:2018-11-27 01:06:15
【问题描述】:

我想在小部件 (QWidget) 中显示 pyplot 图像,我把它放在 QtDesigner 中设计的 gui 中:

当我按下 Çiz 按钮时,我想显示我可以使用该代码在 python 中创建的图像:

points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])

x = points[:,0]
y = points[:,1]
# calculate polynomial
z = np.polyfit(x, y, 2)
f = np.poly1d(z)

x_fit = np.linspace(min(x), max(x), 10000)
y_fit = [f(_x) for _x in x_fit]

plt.plot(x, y)
plt.plot(x_fit, y_fit)
plt.show()

编辑

我根据answer做了一些修改,但是又出现了新的问题。

在我推广之后:

我在下面重新排列我的代码:

# calculate polynomial and r
self.x_fit = np.linspace(min(self.itemX), max(self.itemY), 10000)
self.y_fit = [f(_x) for _x in self.x_fit]

self._dlg.plotwidget.plot(self.itemX, self.itemY)
self._dlg.plotwidget.plot(self.x_fit, self.y_fit)

self.itemX 是列表中的 x 个值。

self.itemY 是列表中的 y 值。

self._dlg 是您看到的主窗口。

当我尝试打开该窗口时,我收到以下错误消息:

【问题讨论】:

    标签: python python-3.x matplotlib pyqt pyqt5


    【解决方案1】:

    对不起,我没有完全回答这个问题,但我不会将 matplotlib.pyplot 与 pyqt 一起使用。我推荐使用 pyqtgraph (http://pyqtgraph.org),相当方便和强大。使用 Qt 设计器:

    • 您只需在 GUI 中插入“图形视图”
    • 您右键单击它并使用 pyqtgraph 将其提升为“plotwidget”。我猜英文标签是这样的:基类'QGraphicsView';提升类“PlotWidget”;头文件'pyqtgraph',然后'add',然后'promote'
    • 然后您可以制作 plotwidget.plot(x,y,...)、plotwidget.clear() 和 co。它将绘制 plotwidget 中的所有内容,并提供一系列交互的可能性

    【讨论】:

    • 当我点击promete它打开一个窗口。基类名称 QWidget 是正确的。我应该在哪里写“plotwidget”?升级的班级名称?
    【解决方案2】:

    我刚刚测试了下面的代码对我有用:

    import sys
    import numpy as np
    import pyqtgraph as pg
    from pyqtgraph.Qt import QtCore, QtGui, uic
    uifilename = 'test.ui'
    form_class = uic.loadUiType(uifilename)[0] #dirty reading of the ui file. better to convert it to a '.py'
    
    class MyWindowClass(QtGui.QMainWindow, form_class):
    
        def __init__(self):
            QtGui.QMainWindow.__init__(self)
            self.setupUi(self)
            self.onInit()
    
        def onInit(self):
    #usually a lot of connections here
            self.x_fit = np.linspace(1,10000, 10000)
            self.y_fit = [f(_x) for _x in self.x_fit]
            self.plotwidget.plot(self.x_fit,self.y_fit,symbol='o',pen=None)
            self.plotwidget.setLabel('left',text='toto',units='')
            self.plotwidget.setLabel('top',text='tata',units='')
    
    def f(x):
        return x**2+1
    
    if __name__ == '__main__':
        if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
            app = QtGui.QApplication([])
            pg.setConfigOption('background', 'w') 
            win = MyWindowClass()
            win.show()
            app.exec_()
    

    使用这个 test.ui:https://github.com/steph2016/profiles/blob/master/test.ui。 请注意,plotwidget 封装在布局中。我认为它只适用于主窗口,但我不确定了......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-24
      • 1970-01-01
      • 1970-01-01
      • 2021-02-26
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      相关资源
      最近更新 更多