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