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

相关推荐
程序定小飞17 分钟前
基于springboot的web的音乐网站开发与设计
java·前端·数据库·vue.js·spring boot·后端·spring
Hello_WOAIAI19 分钟前
2.4 python装饰器在 Web 框架和测试中的实战应用
开发语言·前端·python
搬山.摧城25 分钟前
线程池和单例模式
开发语言·单例模式
小灰灰搞电子26 分钟前
Rust 操作Sqlite数据库详细教程
数据库·rust·sqlite
百锦再29 分钟前
第1章 Rust语言概述
java·开发语言·人工智能·python·rust·go·1024程序员节
一叶之秋141239 分钟前
QT背景介绍与环境搭建
开发语言·qt
IvorySQL39 分钟前
你真的知道你正在运行哪个 PostgreSQL吗?
数据库·postgresql
java1234_小锋1 小时前
PyTorch2 Python深度学习 - 模型保存与加载
开发语言·python·深度学习·pytorch2
l1t1 小时前
利用DeepSeek采用hugeint转字符串函数完善luadbi-duckdb的decimal处理
数据库·lua·c·duckdb·deepseek
无敌最俊朗@1 小时前
Qt 开发终极坑点手册图表版本
数据库