在QLabel上点击获得的效果

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


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


以下是我的代码

// label.h

 

#include<QLabel>

classlabel:publicQLabel
{
Q_OBJECT
public:
explicitlabel(QStringstr,QWidget*parent=0);
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(50,255,255));

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

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

count=0;
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%2)
this->setStyleSheet("background-color:red");
else
this->setStyleSheet("background-color:blue");
}

voidlabel::paintEvent(QPaintEvent*event)
{

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

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

}
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=0);
~MainWindow();
};
//MainWindow.cpp
#include"mainwindow.h"
#include<QLabel>

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

la->setGeometry(50,30,100,30);

}

MainWindow::~MainWindow()
{

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

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

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

 

 

 

你可能感兴趣的:(label)