Mouse Events on QLabel Widget
Mouse Events on QLabel Widget
This is a problem when I want to detect Mouse Events on QLabel Widget. By default, we can not use QLabel to detect Mouse Events on QLabel Widget. If we want to add this feature, we must create a custum QLabel by self. With this tutorial, you can extend to create other QWidget by yourself.
We can detect Mouse Events on QLabel Widget with method mousePressEvent ( QMouseEvent * ev ). For example, I create a class with name labelClick, implement mousePressEvent method with this code :
void labelClick::mousePressEvent ( QMouseEvent * event ) { if(event->button() == Qt::LeftButton) emit leftClickAction(); else if(event->button() == Qt::RightButton) emit rightClickAction(); else if(event->button() == Qt::MidButton) emit midClickAction(); }
We can use this labelClick class in other class and if want to detect Mouse Events on QLabel Widget, we can that signal with this command :
// add label click signal and slot connect(labelclick, SIGNAL(leftClickAction()), this, SLOT(leftclick())); connect(labelclick, SIGNAL(rightClickAction()), this, SLOT(rightclick())); connect(labelclick, SIGNAL(midClickAction()), this, SLOT(midclick()));
This is a sample image when start running Mouse Events on QLabel Widget from above code :
And this is a sample output when we click with mouse button over our modification QLabel above :
This is a simple tutorial how to detect Mouse Events on QLabel Widget. You can extend this tutorial to get mouseEvents on other Widget. If you have other method how to detect Mouse Events on QLabel Widget, please share 🙂
You can download the complete Mouse Events on QLabel Widget source code at here.
Very useful tutorial. Thanks very much 🙂
Thanks very much 🙂