Skip to content

Commit

Permalink
add mapWidget demo
Browse files Browse the repository at this point in the history
  • Loading branch information
GoodCoder666 committed Dec 14, 2024
1 parent 03448a2 commit 94e7683
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ set(PROJECT_SOURCES
src/localGameDialog/localGameDialog.cpp
src/localGameDialog/localGameDialog.h
src/localGameDialog/localGameDialog.ui
src/mapWidget/mapWidget.cpp
src/mapWidget/mapWidget.h
res/res.qrc
)

Expand Down
31 changes: 31 additions & 0 deletions src/mapWidget/mapWidget.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#include "mapWidget.h"
#include <QPainter>
#include <QWheelEvent>

MapWidget::MapWidget(QWidget* parent) :
QWidget(parent), scale(1.0), offset(0, 0) {
setFixedSize(800, 600);
}

MapWidget::~MapWidget() {
}

void MapWidget::paintEvent(QPaintEvent* event) {
QPainter painter(this);
painter.translate(offset);
painter.scale(scale, scale);
painter.setBrush(Qt::red);
// demo rect
painter.drawRect(50, 50, 200, 100);
}

void MapWidget::wheelEvent(QWheelEvent* event) {
int delta = event->angleDelta().y();
float factor = (delta > 0) ? 1.1 : 0.9;
QPoint globalMousePos = QCursor::pos();
QPoint widgetMousePos = mapFromGlobal(globalMousePos);
QPointF oldMousePos = (widgetMousePos - offset) / scale;
scale *= factor;
offset = widgetMousePos - oldMousePos * scale;
update();
}
23 changes: 23 additions & 0 deletions src/mapWidget/mapWidget.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#ifndef MAPWIDGET_H
#define MAPWIDGET_H

#include <QWidget>
#include <QPointF>

class MapWidget : public QWidget {
Q_OBJECT

public:
explicit MapWidget(QWidget* parent = nullptr);
~MapWidget();

protected:
void paintEvent(QPaintEvent* event) override;
void wheelEvent(QWheelEvent* event) override;

private:
float scale;
QPointF offset;
};

#endif // MAPWIDGET_H

0 comments on commit 94e7683

Please sign in to comment.