在PyQt6中使用matplotlib库于QGraphicsView部件中画图演示代码
时间: 2024-05-15 12:19:59 浏览: 269
可以,以下是一个简单的示例代码:
```python
import sys
from PyQt6.QtWidgets import *
from PyQt6.QtCore import *
from PyQt6.QtGui import *
from matplotlib.backends.backend_qt6agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Matplotlib in PyQt6")
self.setGeometry(100, 100, 800, 600)
# Create a QGraphicsView widget
self.view = QGraphicsView(self)
self.view.setGeometry(0, 0, 800, 600)
self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
# Create a QGraphicsScene and set it to the QGraphicsView
self.scene = QGraphicsScene(self)
self.view.setScene(self.scene)
# Create a Matplotlib figure and add a subplot
self.fig = Figure()
self.ax = self.fig.add_subplot(111)
# Create a Matplotlib canvas and add it to the QGraphicsScene
self.canvas = FigureCanvas(self.fig)
self.scene.addWidget(self.canvas)
# Plot a sine wave
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
self.ax.plot(x, y)
if __name__ == '__main__':
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec())
```
运行这个代码,你会看到一个 Pyqt6 窗口中嵌入了一个 Matplotlib 图形。
阅读全文