在QLabel上点击获得的效果

时间:2021-08-17 23:05:30

一般说只在button中点击获得事件,作出相应的反应。而往往需要在QLabel上作出点击和触碰的效果。

我用qlabel做出了一个效果,当鼠标碰到label区域,label底下出现一条线,离开后线条消失。当点击label后变颜色

以下是我的代码

// label.h

#include<QLabel>

classlabel:publicQLabel
{
Q_OBJECT
public:
explicitlabel(QStringstr,QWidget*parent=);
virtualvoidmousePressEvent(QMouseEvent*event);
voidmouseReleaseEvent(QMouseEvent*event);
voidenterEvent(QEvent*);
voidleaveEvent(QEvent*);
intcount;
voidpaintEvent(QPaintEvent*event);
boolover;
boolpress;

signals:
//自定义clicked()信号,在mousePressEvent事件发生时触发
voidclicked();
publicslots:
voidchange_color();
};

//label.cpp

#include"label.h"
#include<QMouseEvent>
#include<QPainter>
#include<QPalette>

label::label(QStringstr,QWidget*parent):
QLabel(parent)
{

QPalettepalette;
palette.setColor(QPalette::WindowText,QColor(,,));

this->setText(str);
this->setPalette(palette);

setAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
//this->setStyleSheet("background-color:blue");
this->setCursor(Qt::PointingHandCursor);

count=;
press=false;
over=false;
connect(this,SIGNAL(clicked()),this,SLOT(change_color()));
}

voidlabel::mousePressEvent(QMouseEvent*event)
{
//如果单击了就触发clicked信号
if(event->button()==Qt::LeftButton)
{
//触发clicked信号
count++;
press=true;
emitclicked();

}
//将该事件传给父类处理
QLabel::mousePressEvent(event);
}

voidlabel::mouseReleaseEvent(QMouseEvent*event)
{
press=false;
update();
}

voidlabel::enterEvent(QEvent*)
{
over=true;
update();
}

voidlabel::leaveEvent(QEvent*)
{
over=false;
update();
}

voidlabel::change_color()
{
if(count%)
this->setStyleSheet("background-color:red");
else
this->setStyleSheet("background-color:blue");
}

voidlabel::paintEvent(QPaintEvent*event)
{

QPainterpaint(this);
paint.setPen(QPen(Qt::yellow,));
if(over)
{

paint.drawLine(,this->height()-,this->width()-,this->height()-);

}
else
{
paint.setPen(Qt::NoPen);
}
QLabel::paintEvent(event);
}
//MainWindow.h
#include<QWidget>
#include"label.h"


classMainWindow:publicQWidget
{
Q_OBJECT

public:
label*la;
explicitMainWindow(QWidget*parent=);
~MainWindow();
};
//MainWindow.cpp
#include"mainwindow.h"
#include<QLabel>

MainWindow::MainWindow(QWidget*parent):
QWidget(parent)
{
setFixedSize(,);
la=newlabel("192.168.199.245",this);

la->setGeometry(,,,);

}

MainWindow::~MainWindow()
{

}
//main.cpp
#include"mainwindow.h"
#include<QApplication>

intmain(intargc,char*argv[])
{
QApplicationa(argc,argv);
MainWindoww;
w.show();

returna.exec();
}
仅供初学者参考