Making a clickable Label in Qt

It is hereby recorded for later use:

.cpp

#include"clicklabel.h"

QClickLabel::QClickLabel(QWidget *parent) :QLabel(parent) 
{
    init();
}
voidQClickLabel::init() 
{
    m_number =0; 
}
voidQClickLabel::setClieckNumber(intnum)  
{
    m_number = num;
    update();
}
voidQClickLabel::mousePressEvent(QMouseEvent*event)  
{
    if(event->button() ==Qt::LeftButton) 
    {
        emit clicked(m_number);
    }
    QLabel :: mousePressEvent (event); //Pass the event to the parent class for processing     
}


.h:

#include<QLabel> 
#include<QMouseEvent> 
class QClickLabel : public QLabel    
{
    Q_OBJECT
public:
    QClickLabel(QWidget* parent =0); 
    void init();
    void setClieckNumber(int num);
signals:
    void clicked(int num);
protected:
    voidmousePressEvent(QMouseEvent*event);  
private:
    intm_number; 
};


Call (part of code):

      for(int i =0;i<m_labelNum;i++)     
    {
        backLabel[i] =newQLabel(this);  
        backLabel[i]->setFixedSize(this->width() /m_labelNum-m_margin,this->height()-m_margin*m_labelNum);        
        backLabel[i]->setStyleSheet(backString);
        backLabel[i]->installEventFilter(this);
        if(i>0)
        {
            closeButton[i] =newQClickLabel(backLabel[i]);  
            closeButton[i]->setFixedSize(20,20); 
            closeButton[i]->move(backLabel[i]->width() -closeButton[i]->width(),0);  
            closeButton[i]->installEventFilter(this);
            closeButton[i]->setClieckNumber(i);
            connect(closeButton[i],SIGNAL(myclicked(int)),this,SLOT(slotCloseBackLabel(int)));   
        }
        }

Among them, closeButton[i] is of type clickLabel. It goes without saying how to define it. The declaration is as follows:

QClickLabel *closeButton[4];

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325653079&siteId=291194637