custom widget in qt

TstUsrCtrl.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#pragma once
 
#include <qwidget>
 
class TstUsrCtrl : public QWidget
{
	Q_OBJECT
 
	QPoint oldPos_;
	QPoint curPos_;
 
public:
	explicit TstUsrCtrl(QWidget *parent = nullptr);
	~TstUsrCtrl();
 
	void paintEvent(QPaintEvent* event);
	void mousePressEvent(QMouseEvent* event);
	void mouseMoveEvent(QMouseEvent* event);
	void mouseReleaseEvent(QMouseEvent* event);
	void mouseToPosition(QMouseEvent* event);
};
</qwidget>


TstUsrCtrl.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include "tstusrctrl.h"
 
#include <QMouseEvent>
#include <QPainter>
 
TstUsrCtrl::TstUsrCtrl(QWidget* parent) :
	QWidget(parent)
{
	setAttribute(Qt::WA_OpaquePaintEvent, true);
}
 
TstUsrCtrl::~TstUsrCtrl()
{
}
 
void TstUsrCtrl::paintEvent(QPaintEvent* event)
{
	QPainter painter(this);
 
	painter.setPen(QPen(Qt::red));
	painter.setBrush(QBrush(Qt::red));
	painter.drawLine(oldPos_, curPos_);
}
 
void TstUsrCtrl::mousePressEvent(QMouseEvent* event)
{
	mouseToPosition(event);
	this->update();
}
 
void TstUsrCtrl::mouseMoveEvent(QMouseEvent* event)
{
	mouseToPosition(event);
	this->update();
}
 
void TstUsrCtrl::mouseReleaseEvent(QMouseEvent* event)
{
	mouseToPosition(event);
	this->update();
}
 
void TstUsrCtrl:: mouseToPosition(QMouseEvent* event)
{
	oldPos_ = curPos_;
	curPos_ = event->pos();
}

MainWindow.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <memory>
#include <tstusrctrl.h>
class MainWindow : public QMainWindow
{
	...
	std::unique_ptr<TstUsrCtrl> ctrl_;
};
MainWindow::MainWindow(QWidget *parent)
	: QMainWindow(parent)
	, ui(new Ui::MainWindow)
{
	ui->setupUi(this);
	ctrl_.reset(new TstUsrCtrl(this));
	ctrl_->setFixedSize(200, 200);
	ctrl_->move(50, 30);
	ctrl_->show();
}

ps: to refrain from erasing background, setAttribute WA_OpaquePaintEvent is the key.

refer to:
默默地EEer
https://doc.qt.io/archives/qq/qq16-background.html