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文库

相关推荐
云上空几秒前
C#初级知识总结
开发语言·c#
yuanmenglxb20043 分钟前
微信小程序核心技术栈
前端·javascript·vue.js·笔记·微信小程序·小程序
爱编程的鱼4 分钟前
如何让 HTML 文件嵌入另一个 HTML 文件:详解与实践
前端·html
_09278 分钟前
Vue 2 与 Vue 3 的核心区别及 Vue 3 新特性详解
前端
David凉宸9 分钟前
一文带你使用Vue完成移动端(apk)项目
前端
钢铁男儿21 分钟前
C# 深入理解类:面向对象编程的核心数据结构
开发语言·数据结构·c#
会飞的鱼先生22 分钟前
Vue3的内置组件 -实现过渡动画 TransitionGroup
前端·javascript·vue.js·vue
晓得迷路了22 分钟前
10 分钟开发一个 Chrome 插件?Trae 让你轻松实现!
前端·javascript·trae
秋天的一阵风27 分钟前
Vue3探秘系列— 路由:vue-router的实现原理(十六-上)
前端·vue.js·面试
karatttt27 分钟前
用go从零构建写一个RPC(仿gRPC,tRPC)--- 版本1
后端·qt·rpc·架构·golang