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

相关推荐
nongcunqq28 分钟前
abap 操作 excel
java·数据库·excel
rain bye bye1 小时前
calibre LVS 跑不起来 就将setup 的LVS Option connect下的 connect all nets by name 打开。
服务器·数据库·lvs
R-G-B1 小时前
【02】C#入门到精通——C# 变量、输入/输出、类型转换
开发语言·c#·c# 变量·c#输入/输出·c#类型转换
星河队长1 小时前
C# 软件加密方法,有使用时间限制,同时要防止拷贝
开发语言·c#
史迪奇_xxx1 小时前
10、一个简易 vector:C++ 模板与 STL
java·开发语言·c++
2301_801252221 小时前
Java中的反射
java·开发语言
Kiri霧2 小时前
Rust开发环境搭建
开发语言·后端·rust
weixin-a153003083162 小时前
[数据抓取-1]beautifulsoup
开发语言·python·beautifulsoup
阿里云大数据AI技术2 小时前
云栖实录|MaxCompute全新升级:AI时代的原生数据仓库
大数据·数据库·云原生
小杨同学yx3 小时前
有关maven的一些知识点
java·开发语言