如果你想要在Qt QGraphicsView中绘制一个不带有屏幕中心点到鼠标的线的多边形,你可以修改上面的代码如下:
#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QMouseEvent>
class PolygonItem : public QGraphicsItem
{
public:
PolygonItem(QGraphicsItem *parent = nullptr)
: QGraphicsItem(parent), pen_(Qt::black), brush_(Qt::NoBrush) {}
QRectF boundingRect() const override
{
return polygon_.boundingRect();
}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
{
painter->setPen(pen_);
painter->setBrush(brush_);
painter->drawPolygon(polygon_);
}
void addPoint(const QPointF& point)
{
if (polygon_.size() == 0 || polygon_.last() != point) // 只有当当前点和上一个点不同时才添加
{
polygon_ << point;
update(); // 刷新画布
}
}
private:
QPolygonF polygon_;
QPen pen_;
QBrush brush_;
};
class GraphicsView : public QGraphicsView
{
public:
GraphicsView(QWidget *parent = nullptr)
: QGraphicsView(parent)
{
scene_ = new QGraphicsScene(this);
setScene(scene_);
polygon_ = new PolygonItem();
scene_->addItem(polygon_);
// 设置画布大小为500x500
setFixedSize(500, 500);
}
protected:
void mousePressEvent(QMouseEvent *event) override
{
if (event->button() == Qt::LeftButton)
polygon_->addPoint(mapToScene(event->pos()));
}
void mouseMoveEvent(QMouseEvent *event) override
{
if (event->buttons() & Qt::LeftButton)
polygon_->addPoint(mapToScene(event->pos()));
}
private:
QGraphicsScene* scene_;
PolygonItem* polygon_;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
GraphicsView view;
view.show();
return a.exec();
}
这个代码与之前的代码几乎相同,唯一的不同是我们不再显示屏幕中心点到鼠标位置的线。这是因为当你单击或移动鼠标时,使用mapToScene()将鼠标位置从窗口坐标系转换为场景坐标系,所以没有中心点到鼠标位置的线。
希望这可以解决你的问题。