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.运行结果

相关推荐
于越海13 分钟前
材料电子理论核心四个基本模型的python编程学习
开发语言·笔记·python·学习·学习方法
代码方舟18 分钟前
Java后端实战:构建基于天远手机号码归属地核验的金融级风控模块
java·大数据·开发语言·金融
wuk99824 分钟前
基于MATLAB实现栅格地图全覆盖移动路径规划
开发语言·matlab
幽络源小助理44 分钟前
PHP虚拟商品自动发卡系统源码 – 支持文章付费阅读与自动发货
开发语言·php
故事不长丨1 小时前
C#集合:解锁高效数据管理的秘密武器
开发语言·windows·c#·wpf·集合·winfrom·字典
龙亘川1 小时前
【课程5.1】城管住建核心功能需求分析:市政设施、市容秩序等场景痛点拆解
数据库·oracle·智慧城市·城管住建
飞鸟真人1 小时前
Redis面试常见问题详解
数据库·redis·面试
superman超哥1 小时前
Rust 内部可变性模式:突破借用规则的受控机制
开发语言·后端·rust·rust内部可变性·借用规则·受控机制
豆沙沙包?1 小时前
2026年--Lc329-735. 小行星碰撞(栈)--java版
java·开发语言
weibkreuz1 小时前
收集表单数据@10
开发语言·前端·javascript