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

相关推荐
沉默媛22 分钟前
如何安装python以及jupyter notebook
开发语言·python·jupyter
TDengine (老段)27 分钟前
TDengine 数据库建模最佳实践
大数据·数据库·物联网·时序数据库·tdengine·涛思数据
Elastic 中国社区官方博客38 分钟前
Elasticsearch 字符串包含子字符串:高级查询技巧
大数据·数据库·elasticsearch·搜索引擎·全文检索·lucene
_Chipen1 小时前
C++基础问题
开发语言·c++
Gauss松鼠会1 小时前
GaussDB应用场景全景解析:从金融核心到物联网的分布式数据库实践
数据库·分布式·物联网·金融·database·gaussdb
止观止1 小时前
JavaScript对象创建9大核心技术解析
开发语言·javascript·ecmascript
守城小轩2 小时前
Chromium 136 编译指南 - Android 篇:开发工具安装(三)
android·数据库·redis
尽兴-2 小时前
如何将多个.sql文件合并成一个:Windows和Linux/Mac详细指南
linux·数据库·windows·sql·macos
小小不董2 小时前
深入理解oracle ADG和RAC
linux·服务器·数据库·oracle·dba
胚芽鞘6812 小时前
查询依赖冲突工具maven Helper
java·数据库·maven