Qt制作可点击的Label

特此记录,供以后使用:

.cpp

#include "clicklabel.h"

QClickLabel::QClickLabel(QWidget *parent) : QLabel(parent)
{
    init();
}
void QClickLabel::init()
{
    m_number = 0;
}
void QClickLabel::setClieckNumber(int num)
{
    m_number = num;
    update();
}
void QClickLabel::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        emit clicked(m_number);
    }
    QLabel::mousePressEvent(event);     //将该事件传给父类处理
}


.h:

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


调用(部分代码):

      for(int i = 0; i < m_labelNum; i++)
    {
        backLabel[i] = new QLabel(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] = new QClickLabel(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)));
        }
        }

其中 closeButton[i]为clickLabel类型,如何定义就不用说了吧,声明如下:

QClickLabel *closeButton[4];

你可能感兴趣的:(QT)