QT创建可移动点类

效果如图所示:

创建新类MovablePoint,继承自QWidget.

MovablePoint头文件:

复制代码
#ifndef MOVABLEPOINT_H
#define MOVABLEPOINT_H

#include <QWidget>
#include <QPainter>
#include <QPaintEvent>
#include <QStyleOption>
#include <QMouseEvent>

class MovablePoint : public QWidget
{
    Q_OBJECT
public:
    explicit MovablePoint(QWidget *parent = nullptr);

public:
    int      radius;
    bool    mouse_pressed;
    QPoint pressed_pos;
    QPoint previous_pos;
    QPoint current_pos;

protected:
    void paintEvent(QPaintEvent*);
    void mousePressEvent(QMouseEvent*);
    void mouseReleaseEvent(QMouseEvent*);
    void mouseMoveEvent(QMouseEvent*);
};

#endif // MOVABLEPOINT_H

MovablePoint.cpp:

复制代码
#include "movablepoint.h"

MovablePoint::MovablePoint(QWidget *parent)
    : QWidget{parent}
{
    mouse_pressed = false;

    radius = 5;
    this->setFixedSize(2*radius + 1,2*radius + 1);

    //this->setCursor(Qt::SizeAllCursor);

    setAttribute(Qt::WA_TranslucentBackground);

    this->setStyleSheet("QWidget{background-color: blue;border-radius:5px;}");
}

void MovablePoint::mouseMoveEvent(QMouseEvent *event)
{
    if (mouse_pressed){
        QPoint _cur_pos = this->mapToGlobal(event->pos());
        QPoint _off        =  _cur_pos - previous_pos;

        QRect _rect = this->geometry();
        _rect.moveTopLeft(_rect.topLeft() + _off);
        this->setGeometry(_rect);

        previous_pos = _cur_pos;
    }
}

void MovablePoint::mouseReleaseEvent(QMouseEvent* event)
{
    mouse_pressed = false;
}

void MovablePoint::mousePressEvent(QMouseEvent *event)
{
    mouse_pressed = true;
    previous_pos = this->mapToGlobal(event->pos());

}

void MovablePoint::paintEvent(QPaintEvent*)
{
    QStyleOption opt;
    opt.init(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}

为了使部件变成圆形:

第一 设置了背景透明及边缘半径:

setAttribute(Qt::WA_TranslucentBackground);

this->setStyleSheet("QWidget{background-color: blue;border-radius:5px;}");

第二 在paintEvent中重绘部件

复制代码
    QStyleOption opt;
    opt.init(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);

【免费】QT可移动点类及其测试程序资源-CSDN文库

相关推荐
技术猿1887027835115 小时前
PHP 与 WebAssembly 的 “天然隔阂”
开发语言·php·wasm
薄荷撞~可乐15 小时前
C#Task(Api)应用
开发语言·c#
雾恋16 小时前
最近一年的感悟
前端·javascript·程序员
another heaven17 小时前
【Qt VS2022调试时无法查看QString等Qt变量信息】解决方法
开发语言·qt
A黄俊辉A17 小时前
axios+ts封装
开发语言·前端·javascript
小李小李不讲道理17 小时前
「Ant Design 组件库探索」四:Input组件
前端·javascript·react.js
连合机器人18 小时前
晨曦中的守望者:当科技为景区赋予温度
java·前端·科技
杨福瑞18 小时前
C语⾔内存函数
c语言·开发语言
eqwaak018 小时前
科技信息差(9.12)
开发语言·python·科技·量子计算
axban18 小时前
QT M/V架构开发实战:QStringListModel介绍
开发语言·数据库·qt