qt 一个可以拖拽的矩形

1.概要

2.代码

2.1 mycotrl.h

复制代码
#ifndef MYCOTRL_H
#define MYCOTRL_H

#include <QWidget>
#include <QMouseEvent>

class MyCotrl: public QWidget
{
    Q_OBJECT
public:
    //MyCotrl();
    MyCotrl(QWidget *parent = nullptr);
protected:
    void paintEvent(QPaintEvent *event);
    void mousePressEvent(QMouseEvent *event);
    void mouseMoveEvent(QMouseEvent *event);
    void mouseReleaseEvent(QMouseEvent *event);
private:
    bool dragging;
    QPoint oldPos;
};

2.2 widget.h

复制代码
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

QT_BEGIN_NAMESPACE
namespace Ui {
class Widget;
}
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();

private:
    Ui::Widget *ui;
};
#endif // WIDGET_H

2.3 mycotrl.cpp

复制代码
#include "mycotrl.h"
#include <QPainter>

//MyCotrl::MyCotrl() {}

MyCotrl::MyCotrl(QWidget *parent) : QWidget(parent), dragging(false)
{

}

void MyCotrl::paintEvent(QPaintEvent *event)  {
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setBrush(Qt::blue);
    painter.drawRect(rect()); // 绘制一个矩形,其大小由QWidget的size决定
}

void MyCotrl::mousePressEvent(QMouseEvent *event){
    if (event->button() == Qt::LeftButton) {
        dragging = true;
        oldPos = event->pos();
    }
}

void MyCotrl::mouseMoveEvent(QMouseEvent *event){
    if (dragging) {
        move(mapToParent(event->pos()) - oldPos);
        oldPos = event->pos();
    }
}

void MyCotrl::mouseReleaseEvent(QMouseEvent *event) {
    Q_UNUSED(event)
    dragging = false;
}

2.4 widget.cpp

复制代码
#include "widget.h"
#include "ui_widget.h"
#include <QPushButton>
#include "mycotrl.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    QPushButton *button = new QPushButton("My Button", this);
    // 设置按钮的位置和大小(可选)
    // 注意:在 QMainWindow 中,你可能需要先设置一个 central widget 或其他容器
    button->setGeometry(QRect(10, 10, 100, 30));

    MyCotrl* my = new MyCotrl(this);
    button->setGeometry(QRect(100, 100, 100, 30));
}

Widget::~Widget()
{
    delete ui;
}

2.5 main.cpp

复制代码
#include "widget.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
    return a.exec();
}

3.运行结果

相关推荐
coding随想1 分钟前
掌控网页的魔法之书:JavaScript DOM的奇幻之旅
开发语言·javascript·ecmascript
SHUIPING_YANG7 分钟前
根据用户id自动切换表查询
java·服务器·数据库
爱吃烤鸡翅的酸菜鱼20 分钟前
IDEA高效开发:Database Navigator插件安装与核心使用指南
java·开发语言·数据库·编辑器·intellij-idea·database
超奇电子24 分钟前
阿里云OSS预签名URL上传与临时凭证上传的技术对比分析
数据库·阿里云·云计算
神仙别闹37 分钟前
基于C#+SQL Server实现(Web)学生选课管理系统
前端·数据库·c#
m0_653031361 小时前
PostgreSQL技术大讲堂 - 第97讲:PG数据库编码和区域(locale)答疑解惑
数据库·postgresql
心情好的小球藻1 小时前
Python应用进阶DAY9--类型注解Type Hinting
开发语言·python
惜.己1 小时前
使用python读取json数据,简单的处理成元组数组
开发语言·python·测试工具·json
会编程的林俊杰1 小时前
MySQL中的锁有哪些
数据库·mysql
cts6181 小时前
Milvus分布式数据库工作职责
数据库·分布式·milvus