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

相关推荐
LXS_3574 分钟前
Day17 C++提高 之 类模板案例
开发语言·c++·笔记·算法·学习方法
leo__5204 分钟前
基于MATLAB实现的鲁棒性音频数字水印系统
开发语言·matlab·音视频
2301_789015624 分钟前
C++:多态(面向对象的主要手段之一)
c语言·开发语言·c++·多态
小年糕是糕手5 分钟前
【C++】string类(一)
linux·开发语言·数据结构·c++·算法·leetcode·改行学it
小小鸟0085 分钟前
Vue响应式原理
前端·javascript·vue.js
sali-tec6 分钟前
C# 基于halcon的视觉工作流-章70 深度学习-Deep OCR
开发语言·人工智能·深度学习·算法·计算机视觉·c#·ocr
晚霞的不甘6 分钟前
C语言利用数组处理批量数据详解
android·c语言·开发语言
lee5767 分钟前
鄙人的 Vue 3.0 商业级开源甘特图已经发布到 npm
前端·vue.js·npm·开源·甘特图
前端老曹10 分钟前
vue3 三级路由无法缓存的终终终终终终极解决方案
前端·javascript·vue.js
1024小神11 分钟前
uniapp + vue3 + scss 定义全局样式变量,并使用
前端·uni-app·scss