QT中在QLabel顯示圖片并且利用鼠標(biāo)點擊畫線問題
在QLabel顯示圖片并且利用鼠標(biāo)點擊畫線
最近在做在Label上顯示圖片并且通過鼠標(biāo)點擊畫線,在網(wǎng)上查了很多零零散散的東西,收獲也多
很多初學(xué)者更希望直接貼代碼,這樣可以模仿來寫,我下面直接貼出我的項目中自己寫的maLabel類
(如果只是實現(xiàn)利用鼠標(biāo)繪制, 重寫void paintEvent(QPaintEvent *event);void mousePressEvent(QMouseEvent *e); void mouseMoveEvent(QMouseEvent *e); void mouseReleaseEvent(QMouseEvent *e);即可,其他函數(shù)是我項目需求所以多寫的,可以忽略)
申明myLabel類,繼承QLabel,生成myLabel.h和myLabel.cpp文件
以下為我的代碼,供參考
我只是實現(xiàn)了畫一條直線,如果要畫多條,可以用vector將之前若干條的信息干存下來,每次都繪制
myLabel.h
#ifndef MYLABEL_H
#define MYLABEL_H
#include <QLabel>
#include <QPoint>
#include <QColor>
#include <QPaintEvent>
#include <QImage>
#include <QPixmap>
class myLabel : public QLabel
{
//Q_OBJECT
public:
myLabel();
//~myLabel();
//繪制線條
virtual void paintEvent(QPaintEvent *event) override;
//鼠標(biāo)按下
void mousePressEvent(QMouseEvent *e);
//鼠標(biāo)移動
void mouseMoveEvent(QMouseEvent *e);
//鼠標(biāo)抬起
void mouseReleaseEvent(QMouseEvent *e);
//設(shè)置所畫線條屬性
void setLineColor(const QColor lineColor);
void setLineSize(const int lineSize);
//得到畫線的起點和終點
QPoint getStartPoint();
QPoint getEndPoint();
void clear();
private:
QPoint lineStartPoint; //畫線起點
QPoint lineEndPoint; //畫線終點
QColor lineColor; //線條顏色
int lineSize; //5種線型
bool isPressed;
};
#endif // MYLABEL_HmyLabel.cpp
#include "myLabel.h"
#include <QPen>
#include<QPainter>
myLabel::myLabel()
{
this->lineStartPoint = QPoint(0,0);
this->lineEndPoint = QPoint(0,0);
this->lineColor = QColor(Qt::black);
this->lineSize = 3;
}
//繪制線條
void myLabel::paintEvent(QPaintEvent *event)
{
QLabel::paintEvent(event);//必須有,才能讓背景圖片顯示出來
QPainter painter(this);
QPen pen;
pen.setColor(lineColor);
pen.setWidth(lineSize);
painter.setPen(pen);
painter.drawLine(lineStartPoint,lineEndPoint);
}
//鼠標(biāo)按下
void myLabel::mousePressEvent(QMouseEvent *e)
{
lineStartPoint = e->pos();
lineEndPoint = e->pos();
//在圖片上繪制
isPressed = true;
}
//鼠標(biāo)移動
void myLabel::mouseMoveEvent(QMouseEvent *e)
{
if(isPressed)
{
lineEndPoint=e->pos();
update();
}
}
//鼠標(biāo)抬起
void myLabel::mouseReleaseEvent(QMouseEvent *e)
{
isPressed=false;
update();
}
void myLabel::setLineColor(const QColor lineColor)
{
this->lineColor = lineColor;
}
void myLabel::setLineSize(const int lineSize)
{
this->lineSize = lineSize;
}
QPoint myLabel::getStartPoint()
{
return lineStartPoint;
}
QPoint myLabel::getEndPoint()
{
return lineEndPoint;
}
void myLabel::clear()
{
lineStartPoint = QPoint(0,0);
lineEndPoint = QPoint(0,0);
update();
}
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
如何在C++中實現(xiàn)一個正確的時間循環(huán)器詳解
這篇文章主要給大家介紹了關(guān)于如何在C++中實現(xiàn)一個正確的時間循環(huán)器的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
C語言 深入探究動態(tài)規(guī)劃之區(qū)間DP
這幾天在做有關(guān)dp的題,看到一個石子合并的問題,本來以為是個貪心,后來仔細(xì)一想壓根不是貪心。貪心算法的思路是每次都取最大的,然而石子合并問題有個限制條件就是每次只能取相鄰的,這就決定了它不是個貪心2022-04-04

