|
- #include "hmieditor.h"
- #include <QPen>
- #include <QBrush>
-
- void Shape::draw(QPainter& painter) const {
- painter.setPen(QPen(Qt::blue, 2));
- painter.setBrush(QBrush(Qt::lightGray, Qt::DiagCrossPattern));
-
- if (type == Circle) {
- painter.drawEllipse(rect);
- } else if (type == Rectangle) {
- painter.drawRect(rect);
- }
- }
- HMIEditor::HMIEditor(QWidget *parent)
- : QWidget(parent), currentShapeType(Shape::Rectangle), isDrawing(false)
- {
- setMinimumSize(400, 300);
- setStyleSheet("background-color: white;");
- }
-
- void HMIEditor::onDrawCircle() {
- currentShapeType = Shape::Circle;
- }
-
- void HMIEditor::onDrawRect() {
- currentShapeType = Shape::Rectangle;
- }
-
- void HMIEditor::paintEvent(QPaintEvent *event) {
- Q_UNUSED(event);
- QPainter painter(this);
-
- // 绘制所有已完成的图形
- for (const auto& shape : shapes) {
- shape.draw(painter);
- }
-
- // 绘制正在绘制的图形
- if (isDrawing) {
- painter.setPen(QPen(Qt::red, 2, Qt::DashLine));
- if (currentShapeType == Shape::Circle) {
- painter.drawEllipse(currentDrawingRect);
- } else {
- painter.drawRect(currentDrawingRect);
- }
- }
- }
-
- void HMIEditor::mousePressEvent(QMouseEvent *event) {
- if (event->button() == Qt::LeftButton) {
- isDrawing = true;
- currentDrawingRect.setTopLeft(event->pos());
- currentDrawingRect.setBottomRight(event->pos());
- update();
- }
- }
-
- void HMIEditor::mouseReleaseEvent(QMouseEvent *event) {
- if (event->button() == Qt::LeftButton && isDrawing) {
- isDrawing = false;
- currentDrawingRect.setBottomRight(event->pos());
- shapes.emplace_back(currentShapeType, currentDrawingRect);
- update();
- }
- }
-
- void HMIEditor::mouseMoveEvent(QMouseEvent *event) {
- if (isDrawing) {
- currentDrawingRect.setBottomRight(event->pos());
- update();
- }
- }
|