用QT实现画多边形,可拖动多边形的点,并给出代码
时间: 2024-06-10 12:04:37 浏览: 173
您好,非常感谢您的提问。以下是使用QT实现可拖动多边形点的代码:
MainWindow.h文件:
```cpp
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QGraphicsScene>
#include <QGraphicsPolygonItem>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_actionNew_triggered();
private:
Ui::MainWindow *ui;
QGraphicsScene *scene;
QGraphicsPolygonItem *polygonItem;
bool isDragging;
QPointF lastPosition;
void addPolygon();
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
};
#endif // MAINWINDOW_H
```
MainWindow.cpp文件:
```cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPolygonF>
#include <QMouseEvent>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
scene(new QGraphicsScene(this)),
polygonItem(nullptr),
isDragging(false)
{
ui->setupUi(this);
ui->graphicsView->setScene(scene);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_actionNew_triggered()
{
addPolygon();
}
void MainWindow::addPolygon()
{
QPolygonF polygon;
polygon << QPointF(0, 0) << QPointF(100, 0) << QPointF(100, 100) << QPointF(0, 100);
if (polygonItem != nullptr) {
scene->removeItem(polygonItem);
delete polygonItem;
polygonItem = nullptr;
}
polygonItem = new QGraphicsPolygonItem(polygon);
polygonItem->setFlag(QGraphicsItem::ItemIsMovable);
polygonItem->setFlag(QGraphicsItem::ItemIsSelectable);
scene->addItem(polygonItem);
}
void MainWindow::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
QGraphicsPolygonItem *item = qgraphicsitem_cast<QGraphicsPolygonItem*>(scene->itemAt(ui->graphicsView->mapToScene(event->pos()), QTransform()));
if (item == polygonItem) {
isDragging = true;
lastPosition = item->mapFromScene(ui->graphicsView->mapToScene(event->pos())) ;
}
}
QMainWindow::mousePressEvent(event);
}
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
if (isDragging) {
QPointF delta = item->mapFromScene(ui->graphicsView->mapToScene(event->pos())) - lastPosition;
for (int i = 0; i < polygonItem->polygon().size(); ++i) {
polygonItem->setPolygon(polygonItem->polygon().replace(i, polygonItem->polygon().at(i) + delta));
}
lastPosition = item->mapFromScene(ui->graphicsView->mapToScene(event->pos()));
}
QMainWindow::mouseMoveEvent(event);
}
void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
if (isDragging) {
isDragging = false;
}
QMainWindow::mouseReleaseEvent(event);
}
```
以上代码实现了一个可拖动多边形的窗口,用户可以根据需要添加多个多边形等形状。由于代码量较大,本代码仅供参考,具体操作请仔细阅读。
阅读全文