1.概要
2.代码
2.1 resizablewidget.h
#ifndef RESIZABLEWIDGET_H
#define RESIZABLEWIDGET_H
#include <QWidget>
#include <QMouseEvent>
class ResizableWidget: public QWidget
{
Q_OBJECT
public:
ResizableWidget(QWidget *parent = nullptr);
protected:
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void paintEvent(QPaintEvent *event);
private:
bool resizing;
QPoint resizeStart;
};
#endif // RESIZABLEWIDGET_H
2.2 resizablewidget.cpp
#include "resizablewidget.h"
#include <QPainter>
ResizableWidget::ResizableWidget(QWidget *parent) : QWidget(parent), resizing(false) {
// 启用鼠标追踪
setMouseTracking(true);
}
void ResizableWidget::mousePressEvent(QMouseEvent *event) {
if (event->button() == Qt::LeftButton) {
// 检查是否接近右下角
if (event->pos().x() > width() - 10 && event->pos().y() > height() - 10) {
resizing = true;
resizeStart = event->pos();
}
}
}
void ResizableWidget::mouseMoveEvent(QMouseEvent *event) {
if (resizing) {
int dx = event->x() - resizeStart.x();
int dy = event->y() - resizeStart.y();
// 调整控件大小,同时保持位置不变
resize(width() + dx, height() + dy);
// 更新起始位置,以便下一次移动
resizeStart = event->pos();
}
}
void ResizableWidget::mouseReleaseEvent(QMouseEvent *event) {
if (event->button() == Qt::LeftButton) {
resizing = false;
}
}
void ResizableWidget::paintEvent(QPaintEvent *event) {
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.setBrush(Qt::blue);
painter.drawRect(rect()); // 绘制一个矩形,其大小由QWidget的size决定
}
2.3 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.4 widget.cpp
#include "widget.h"
#include "ui_widget.h"
//#include "resizablerectwidget.h"
#include <QPushButton>
#include "resizablewidget.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));
//ResizableRectWidget* widget = new ResizableRectWidget(this);
//widget->setGeometry(100, 100, 200, 100); // 设置初始位置和大小
//widget.show();
ResizableWidget* p_rw = new ResizableWidget(this);
p_rw->setGeometry(0, 0, 200, 100); // 设置初始位置和大小
}
Widget::~Widget()
{
delete ui;
}
2.5 main.cpp
#include "widget.h"
//#include "resizablewidget.h"
#include <QApplication>
//创建一个可以拖拽并且缩放的矩形
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
//ResizableWidget rw;
//rw.show();
return a.exec();
}
3.运行结果
3.1 拖拽前
3.2 拖拽后