当前位置: 首页 > news >正文

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

http://www.lryc.cn/news/150158.html

相关文章:

  • Flutter启动页
  • 读word模板批量生成制式文件
  • Node.js crypto模块 加密算法
  • Win11 避坑安装WSL2 Ubuntu22.04
  • ESP8266+继电器+MQTT+VUE 实现远程开关灯
  • Android中级——四大组件工作过程
  • 【RabbitMQ】RabbitMQ 服务无法启动。系统出错。发生系统错误 1067。进程意外终止。
  • 如何理解attention中的Q、K、V?
  • Redis----取代RabbitMq 和 Kafka的解决方案
  • 动态规划之连续乘积最大子数组 连续和最大子数组
  • keil在点击debug无法运行(全速运行)
  • go语言-协程
  • 如何伪造http头,让后端认为是本地访问
  • 视频剪辑音效处理软件有哪些?视频剪辑软件那个好用
  • 搭建STM32F407的Freertos系统(基于STM32CubeMX)
  • vite 配置自动补全文件的后缀名
  • 基于Spring Boot的人才公寓管理系统设计与实现(Java+spring boot+MySQL)
  • Python 编写函数
  • C# Solidworks二次开发:创建距离配合以及移动组件API详解
  • Excel:通过Lookup函数提取指定文本关键词
  • sql:SQL优化知识点记录(六)
  • C#搭建WebSocket服务实现通讯
  • eclipse/STS(Spring Tool Suite)安装CDT环境(C/C++)
  • Python爬虫抓取经过JS加密的API数据的实现步骤
  • Nacos基础(2)——nacos的服务器和命名空间 springBoot整合nacos 多个nacos配置的情况
  • Win7设备和打印机里空白,0个对象,但是可以打印的处理办法
  • Python基础学习第六天:Python 数据类型
  • C++信息学奥赛1184:明明的随机数
  • NoSQL技术——Redis
  • 【探索SpringCloud】服务发现-Nacos服务端数据结构和模型