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

相关推荐
阿东在coding6 分钟前
Flutter 测试框架对比指南
前端
2501_941877137 分钟前
在法兰克福企业级场景中落地零信任安全架构的系统设计与工程实践分享
开发语言·php
是李嘉图呀10 分钟前
npm推送包失败需要Two-factor权限认证问题解决
前端
自己记录_理解更深刻10 分钟前
本地完成「新建 GitHub 仓库 react-ts-demo → 关联本地 React+TS 项目 → 提交初始代码」的完整操作流程
前端
借个火er12 分钟前
Chrome 插件开发实战:5 分钟上手 + 原理深度解析
前端
攀登的牵牛花12 分钟前
前端向架构突围系列 - 架构方法(一):概述 4+1 视图模型
前端·设计模式·架构
Hashan13 分钟前
Vue 3 中 v-for 动态组件 ref 收集失败问题排查与解决
前端·vue.js·前端框架
bobringtheboys14 分钟前
[el-tag]使用多个el-tag,自动判断内容是否超出
前端·javascript·vue.js
ccccc__15 分钟前
基于vue3完成领域模型架构建设
前端
Cherry的跨界思维16 分钟前
【AI测试全栈:Vue核心】19、Vue3+ECharts实战:构建AI测试可视化仪表盘全攻略
前端·人工智能·python·echarts·vue3·ai全栈·ai测试全栈