我正在使用PyQt5尝试为我的数据分析工具生成GUI。我的问题是,我不知道如何嵌入具有完整功能的matplotlib图形。
所有关于PyQt5和嵌入matplotlib的教程都展示了一个非常简单的方法,即直接在代码中创建所有图形对象。但我不想这样做,因为我的GUI是使用Qt Designer生成的。我创建了一个QWidget来绘制其中的数据。因此,我在代码中导入UI文件:
发生的情况是,我能看到窗口中的工具栏但是没有数据。我可以使用“保存”图标将绘图保存为图像。我想我正在创建与我在Qt Designer中创建的对象不相关的小部件对象的第二个实例。
我该如何解决这个问题? 提前感谢!
所有关于PyQt5和嵌入matplotlib的教程都展示了一个非常简单的方法,即直接在代码中创建所有图形对象。但我不想这样做,因为我的GUI是使用Qt Designer生成的。我创建了一个QWidget来绘制其中的数据。因此,我在代码中导入UI文件:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import numpy as np
from PyQt5.QtGui import QPixmap
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget, QTableWidget, QTableWidgetItem
from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit, QFileDialog
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import QSize
from PyQt5 import QtCore, QtGui, uic
import matplotlib
matplotlib.use('QT5Agg')
import matplotlib.pylab as plt
from matplotlib.backends.qt_compat import QtCore, QtWidgets, is_pyqt5
from matplotlib.backends.backend_qt5agg import FigureCanvas, NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
class MyWindow(QMainWindow):
def __init__(self):
super(MyWindow, self).__init__()
self.ui = uic.loadUi('test.ui', self)
# test data
data = np.array([0.7,0.7,0.7,0.8,0.9,0.9,1.5,1.5,1.5,1.5])
fig, ax1 = plt.subplots()
bins = np.arange(0.6, 1.62, 0.02)
n1, bins1, patches1 = ax1.hist(data, bins, alpha=0.6, density=False, cumulative=False)
# plot
self.plotWidget = FigureCanvas(fig)
# add toolbar
self.addToolBar(QtCore.Qt.BottomToolBarArea, NavigationToolbar(self.plotWidget, self))
#########################################
# show window
self.show()
#########################################
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = MyWindow()
sys.exit(app.exec_())
这是由Qt Designer创建的test.ui文件:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Form</class>
<widget class="QWidget" name="Form">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>772</width>
<height>650</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<widget class="QWidget" name="plotWidge" native="true">
<property name="geometry">
<rect>
<x>20</x>
<y>20</y>
<width>721</width>
<height>571</height>
</rect>
</property>
</widget>
</widget>
<resources/>
<connections/>
</ui>
发生的情况是,我能看到窗口中的工具栏但是没有数据。我可以使用“保存”图标将绘图保存为图像。我想我正在创建与我在Qt Designer中创建的对象不相关的小部件对象的第二个实例。
我该如何解决这个问题? 提前感谢!