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

相关推荐
whatever who cares8 分钟前
android/java中gson的用法
android·java·开发语言
gongzemin9 分钟前
使用阿里云ECS部署前端应用
前端·vue.js·后端
用户411800341534110 分钟前
Flutter课题汇报
前端
环信13 分钟前
实战教程|快速上线音视频通话:手把手教你实现呼叫与接听全流程
前端
Dgua14 分钟前
✨TypeScript快速入门第一篇:从基础到 any、unknown、never 的实战解析
前端
海云前端114 分钟前
Vue3 大屏项目投屏功能开发:多显示器适配实践
前端
周杰伦fans20 分钟前
C# 中 Entity Framework (EF) 和 EF Core 里的 `AsNoTracking` 方法
开发语言·c#
小灰灰搞电子24 分钟前
Rust Slint实现控件尺寸的扩展与收缩源码分享
开发语言·后端·rust
☆cwlulu25 分钟前
git分支管理详解
开发语言·git·青少年编程
技术小丁30 分钟前
使用 HTML + JavaScript 实现酒店订房日期选择器(附完整源码)
前端·javascript