QT开发中文网

不要屏幕中心点到鼠标的线

如果你想要在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()将鼠标位置从窗口坐标系转换为场景坐标系,所以没有中心点到鼠标位置的线。

希望这可以解决你的问题。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=1965

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?