pyside实现matplotlib画板嵌入QT界面,通过鼠标按住拖动画板中的球交互的代码
时间: 2024-05-09 13:18:00 浏览: 125
可以参考下面的代码:
```python
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
class MyMplCanvas(FigureCanvas):
def __init__(self):
self.fig = Figure()
self.axes = self.fig.add_subplot(111)
self.axes.set_xlim([0, 10])
self.axes.set_ylim([0, 10])
self.axes.set_xlabel('X')
self.axes.set_ylabel('Y')
self.axes.set_title('My Plot')
self.circle = self.axes.plot([5], [5], 'o', markersize=20, color='r')[0]
FigureCanvas.__init__(self, self.fig)
self.setFixedSize(400, 400)
self.setMouseTracking(True)
self.start_x, self.start_y = None, None
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.start_x, self.start_y = event.x(), event.y()
def mouseMoveEvent(self, event):
if event.buttons() == Qt.LeftButton:
dx = event.x() - self.start_x
dy = event.y() - self.start_y
self.circle.set_xdata([self.circle.get_xdata() + dx])
self.circle.set_ydata([self.circle.get_ydata() + dy])
self.draw()
self.start_x, self.start_y = event.x(), event.y()
class MyMainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setWindowTitle('My Window')
self.canvas = MyMplCanvas()
self.setCentralWidget(self.canvas)
if __name__ == '__main__':
app = QApplication(sys.argv)
win = MyMainWindow()
win.show()
sys.exit(app.exec_())
```
这段代码实现了将 matplotlib 画板嵌入到 PyQt 界面中,并通过鼠标拖动画板中的球实现交互。具体实现过程可以参考代码注释。
阅读全文