Home > Software design >  How to create a click effect on a QLabel?
How to create a click effect on a QLabel?

Time:10-01

How i could create a click effect similar to push buttons on a QLabel?

QPixmap pixmap;
pixmap.load(":/files/hotkeys.png");

int w = 131;
int h = 71;
pixmap = pixmap.scaled(w, h, Qt::KeepAspectRatio);

// Label
ui.label->setGeometry(220, 220, w, h);
ui.label->setPixmap(pixmap);

// Button
QIcon icon(pixmap);
ui.toolButton->setIconSize(QSize(w, h));
ui.toolButton->setIcon(icon);    
ui.toolButton->setStyleSheet("QToolButton { background-color: transparent }");

By click effect i mean like when you click on a push button containing a picture:

enter image description here

CodePudding user response:

Ideally you'd just use a QToolButton or QPushButton, but if you must use a QLabel, you could do it by subclassing QLabel with a custom paintEvent() to give the desired effect, something like this:

class MyLabel : public QLabel
{
public:
   MyLabel(const QPixmap & pm) : _isMouseDown(false) {setPixmap(pm);}

   virtual void mousePressEvent(  QMouseEvent * e) {_isMouseDown = true;  update(); e->accept();}
   virtual void mouseReleaseEvent(QMouseEvent * e) {_isMouseDown = false; update(); e->accept();}

   virtual void paintEvent(QPaintEvent * e)
   {
      QPainter p(this);
      const int offset = _isMouseDown ? 2 : 0;
      p.drawPixmap(QPoint(offset, offset), *pixmap());
   }

private:
   bool _isMouseDown;
};
  •  Tags:  
  • c qt
  • Related