pyqt设计界面,将鼠标轨迹绘制成彩色曲线,可以保存曲线为csv文件
时间: 2024-03-17 21:44:35 浏览: 57
好的,我可以帮你回答这个问题。你可以使用Python中的PyQt库来设计界面,并使用QPainter类来绘制鼠标轨迹。下面是一个简单的代码示例:
```python
import sys
from PyQt5.QtCore import Qt, QPoint, QRect, QIODevice
from PyQt5.QtGui import QPainter, QColor, QPen, QBrush
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog
import csv
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Mouse Tracking")
self.setFixedSize(800, 600)
self.tracking = False
self.points = []
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.tracking = True
self.points = [event.pos()]
def mouseMoveEvent(self, event):
if self.tracking:
self.points.append(event.pos())
self.update()
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton:
self.tracking = False
self.save_csv()
def save_csv(self):
file_name, _ = QFileDialog.getSaveFileName(self, "Save CSV", "", "CSV Files (*.csv)")
if file_name:
with open(file_name, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["X", "Y", "R", "G", "B"])
for i in range(len(self.points)-1):
x1, y1 = self.points[i].x(), self.points[i].y()
x2, y2 = self.points[i+1].x(), self.points[i+1].y()
r, g, b = 255, 255, 255
pen = QPen(QColor(r, g, b), 3, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing, True)
painter.setPen(pen)
painter.drawLine(x1, y1, x2, y2)
writer.writerow([x2, y2, r, g, b])
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing, True)
pen = QPen(QColor(255, 0, 0), 3, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)
painter.setPen(pen)
brush = QBrush(QColor(255, 0, 0, 100))
painter.setBrush(brush)
for i in range(len(self.points)-1):
x1, y1 = self.points[i].x(), self.points[i].y()
x2, y2 = self.points[i+1].x(), self.points[i+1].y()
painter.drawLine(x1, y1, x2, y2)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
在这个例子中,我们创建了一个`MainWindow`类,它继承自`QMainWindow`。我们在`MainWindow`类中实现了`mousePressEvent`、`mouseMoveEvent`和`mouseReleaseEvent`函数,分别用于开始、跟踪和结束鼠标轨迹。我们还实现了`save_csv`函数,用于将鼠标轨迹保存为CSV文件。在`paintEvent`函数中,我们使用`QPainter`类来绘制鼠标轨迹。
当你启动程序后,你可以使用鼠标绘制轨迹,并在绘制完成后保存它们为CSV文件。
阅读全文