Qt中在QLabel上画点,重写QLabel类
QT中label进行绘图
1.首先新建一个类,让这个类继承QLabel
2.在类中对鼠标点击事件及绘图事件进行重写
3.然后在UI框架下添加label控件,
4.右键label控件,添加重写的类,将其提升为刚刚写好的类
mylabel.h文章来源:https://www.toymoban.com/news/detail-647613.html
#ifndef MYLABEL_H
#define MYLABEL_H
#include <QObject>
#include <QLabel>
#include <QMouseEvent>
#include <QPainter>
#include <QPen>
#include <QPoint>
class MyLabel : public QLabel
{
Q_OBJECT
public:
int labelWidth;
int labelHeight;
struct pointCoord{
int x;
int y;
};
std::vector<pointCoord> coordList;
bool paintEnable = true;
public:
explicit MyLabel(QWidget *parent = 0);
void enabelPaint(bool);
void mousePressEvent(QMouseEvent *event);
void paintEvent(QPaintEvent *event);
// void mouseReleaseEvent(QMouseEvent *event);
// void mouseMoveEvent(QMouseEvent *event);
signals:
void updatePoint(int x, int y, int labelWidth, int labelHeight);
};
#endif // MYLABEL_H
mylabel.cpp文章来源地址https://www.toymoban.com/news/detail-647613.html
#include "mylabel.h"
#include <QMessageBox>
#include <QString>
#include <QDebug>
MyLabel::MyLabel(QWidget *parent) : QLabel(parent)
{
;
}
void MyLabel::enabelPaint(bool enable){
if (enable){
paintEnable = true;
} else {
paintEnable = false;
}
}
void MyLabel::mousePressEvent(QMouseEvent *event)
{
if (paintEnable){
int x = event->position().x();
int y = event->position().y();
pointCoord coord;
coord.x = x;
coord.y = y;
coordList.push_back(coord);
labelWidth = this->width();
labelHeight = this->height();
emit updatePoint(x, y, labelWidth, labelHeight);
update();
}
}
void MyLabel::paintEvent(QPaintEvent *event)
{
QLabel::paintEvent(event);
QPainter painter(this);
QPen pen; //设置画笔,颜色、宽度
pen.setColor(Qt::red);
pen.setWidth(5);
painter.setPen(pen);
for (auto coord:coordList){
painter.drawPoint(coord.x, coord.y);
}
}
到了这里,关于Qt中在QLabel上画点,重写QLabel类的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!