pyqt mouse hovering on a qpushbutton

  • Last Update :
  • Techknowledgy :

Here is my code:

import sys

from PyQt4
import QtCore
from PyQt4.QtGui
import *

class eventFilterWindow(QMainWindow):

   def __init__(self):
   QMainWindow.__init__(self)
widget = QWidget()

button = QPushButton("Trigger event!")
button.installEventFilter(self)

hbox = QHBoxLayout()
hbox.addWidget(button)
widget.setLayout(hbox)
self.setCentralWidget(widget)
self.show()

def eventFilter(self, object, event):

   if event.type() == QtCore.QEvent.MouseButtonPress:
   print "You pressed the button"
return True

elif event.type() == QtCore.QEvent.MouseMove:
   print "C'mon! CLick-meeee!!!"
return True

return False

def main():
   app = QApplication(sys.argv)
#myWindow = EventsWindow()
window = eventFilterWindow()
sys.exit(app.exec_())

if __name__ == "__main__":
   main()

Suggestion : 2

Last Updated : 22 Apr, 2020

In order to do this we have to change the style sheet and had to add background color of push button when mouse hover over it. Below is the style sheet code.

QPushButton::hover {
   background - color: lightgreen;
}

Suggestion : 3

A tooltip is a hint in a desktop application (graphical user interface). Tooltips frequently appear when you hover the mouse over a widget (without clicking). If you put the mouse on top of a button it often shows information, that information is a tooltip message.,The button has a tooltip message that is shown when hovered, this is set with the method setToolTip().,Pyqt supports tool tips, they can be configured for widgets. In PyQt a tooltip can contain both a plain text message and an HTML formatted message.,The example creates a button in a PyQt window. The button is linked to a callback, meaning you click on it, it will call the clickMethod() function.

pybutton.setToolTip('This is a tooltip for the QPushButton widget')
button.setToolTip('This is a <b>QPushButton</b> widget')
QToolTip.setFont(QFont('SansSerif', 10))
import sysfrom PyQt5
import QtCore, QtWidgetsfrom PyQt5.QtWidgets
import QMainWindow, QWidget, QPushButtonfrom PyQt5.QtCore
import QSize class MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.setMinimumSize(QSize(300, 100)) self.setWindowTitle("PyQt tooltip example - pythonprogramminglanguage.com") pybutton = QPushButton('Pyqt', self) pybutton.clicked.connect(self.clickMethod) pybutton.resize(100, 32) pybutton.move(50, 20) pybutton.setToolTip('This is a tooltip message.') def clickMethod(self): print('PyQt') if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) mainWin = MainWindow() mainWin.show() sys.exit(app.exec_())

Suggestion : 4

I want to change the icons of my buttons when mouse goes over it. They are created like this:,I tried to change the button icon with a styleSheet like this:,No errors come up when I run the programm. Nothing happens when mouse goes over the button. I belive there is a connection to do with the button but I can't figure out how. At least I hope this is the right way to use void QWidget::enterEvent(QEvent *event).,It seems to work, even better than expected since there are the "pressed" status within. For what I want to do it's just great!

I want to change the icons of my buttons when mouse goes over it.
They are created like this:

    btn1 = new QPushButton("", this);
    btn1 - > setGeometry(0, 150, 100, 100);
    btn1 - > setIcon(QIcon("btnLogs/1.jpg"));
    btn1 - > setIconSize(QSize(100, 100));
    QObject::connect(btn1, SIGNAL(clicked()), this, SLOT(slotBtn1()));

I tried something like this for example:

    btn1 - > QEvent::HoverEnter; {
       btn1 - > setIcon(QIcon("btnLogs/1_hover.jpg"));
    }
    btn1 - > QEvent::HoverLeave; {
       btn1 - > setIcon(QIcon("btnLogs/1.jpg"));
    }

In the .h file I declared a function called filterBtn1();

#ifndef TEST_H
#define TEST_H

#include <QApplication>
#include <QWidget>
#include <QPixmap>
#include <QPushButton>
#include <QObject>
#include <QHoverEvent>

class myMainWindow : public QWidget
{
    public:
    myMainWindow();

    public slots:
    void filterBtn1();

    private:
    QPushButton *btn1;
};

The main.cpp

#include "Test.h"

int main(int argc, char * argv[]) {
   QApplication app(argc, argv);

   myMainWindow mainWindow;
   mainWindow.setFixedSize(1024, 768);
   mainWindow.show();

   return app.exec();
}

Then I added an event filter: "btn1->installEventFilter(filterBtn1);"
And I understood that I have to create a class in the .cpp file and set boolean conditions:
From this point, the example of the Qt documentation is a bit to complicate for me.

#include "Test.h"

myMainWindow::myMainWindow(): QWidget() {
   btn1 = new QPushButton("", this);
   btn1 - > setGeometry(0, 150, 104, 103);
   btn1 - > setIcon(QIcon("btnLogs/1.jpg"));
   btn1 - > setIconSize(QSize(104, 103));
   btn1 - > installEventFilter(filterBtn1);
}

class filterBtn1: public QObject {
   Q_OBJECT
   protected:
      bool eventFilter(QObject ?? ? * , QEvent * ?? ? );
};

bool filterBtn1::eventFilter(QObject * ?? ? , QEvent * ?? ? ) {
   if (event - > type() == QEvent::HoverEnter) {
      btn1 - > setIcon(QIcon("btnLogs/1_hover.jpg"));
   } else {
      ??
      ?
   }
}

I tried with those members like this:
.h file

#ifndef TEST2_H
#define TEST2_H

#include <QApplication>
#include <QWidget>
#include <QPushButton>


class myMainWindow : public QWidget
{
    Q_OBJECT

    public:
    myMainWindow();
    QPushButton *btn1;

    public slots:
    void enterEvent(QPushButton *btn1);
    void leaveEvent(QPushButton *btn1);

    private:
};

#endif // TEST2_H

.cpp file

#include "test2.h"

myMainWindow::myMainWindow(): QWidget() {
   btn1 = new QPushButton("", this);
   btn1 - > setGeometry(0, 150, 104, 103);
   btn1 - > setIcon(QIcon("btnLogs/1.jpg"));
   btn1 - > setIconSize(QSize(104, 103));
}

void myMainWindow::enterEvent(QPushButton * btn1) {
   btn1 - > setIcon(QIcon("btnLogs/1_hover.jpg"));
}

void myMainWindow::leaveEvent(QPushButton * btn1) {
   btn1 - > setIcon(QIcon("btnLogs/1.jpg"));
}

For the sake of discussion and future references, here is the main code:

class CustomButton: public QPushButton {
   // QWidget interface
   protected: virtual void enterEvent(QEvent * ) {
      qDebug() << "entering";
      QPalette pal = palette();
      pal.setColor(QPalette::Button, QColor(Qt::blue));
      setAutoFillBackground(true);
      setPalette(pal);
      update();
   }

   virtual void leaveEvent(QEvent * ) {
      qDebug() << "leaving";
      QPalette pal = palette();
      pal.setColor(QPalette::Button, QColor(Qt::red));
      setAutoFillBackground(true);
      setPalette(pal);
      update();
   }
};

The MainWindow has a pointer to a CustomButton, which is initialized in the ctor:

MainWindow::MainWindow(QWidget * parent):
   QMainWindow(parent),
   ui(new Ui::MainWindow) {
      ui - > setupUi(this);
      cb = new CustomButton;

      cb - > setText("My funny button");
      this - > setCentralWidget(cb);
   }

@c64zottel If it's just the background color you want to change, I would recomment the use of a StyleSheet:

QPushButton * btn = new QPushButton();
btn - > setObjectName("btnName_1");
btn - > show();
btn - > setSteyleSheet(
   "   QPushButton#btnName_1 {"
   "     background-color: yellow;"
   " }"
   " QPushButton#btnName_1:pressed {"
   "     background-color: rgb(224, 0, 0);     "
   " }"
   " QPushButton#btnName_1:hover {"
   "     background-color: rgb(224, 255, 0);"
   " }"

   "QPushButton#btnName_1:hover:pressed"
   "{"
   "    background-color:red;"
   "}"
);

I tried to change the button icon with a styleSheet like this:

#include "test2.h"

myMainWindow::myMainWindow(): QWidget() {
   btn1 = new QPushButton("", this);
   btn1 - > setGeometry(0, 150, 104, 103);
   btn1 - > setObjectName("btn1_Name");
   btn1 - > show();
   btn1 - > setStyleSheet(
      "   QPushButton#btn1_Name {"
      "     background-image: url('btnLogs/1.jpg');"
      " }"
      " QPushButton#btn1_Name:pressed {"
      "     background-image: url('btnLogs/1_pressed.jpg');"
      " }"
      " QPushButton#btn1_Name:hover {"
      "     background-image: url('btnLogs/1_hover.jpg');"
      " }"
      "QPushButton#btn1_Name:hover:pressed"
      "{"
      "     background-image: url('btnLogs/1_pressed.jpg');"
      "}"
   );
}

Suggestion : 5

2022-02-27 , 2022-04-27 , 2022-03-19 , 2022-05-15

123
right_clicked = QtCore.Signal() left_clicked = QtCore.Signal() double_clicked = QtCore.Signal()
btn = MyButton('Button1') btn.doubled_clicked.connect(func1) btn.right_clicked.connect(func2)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
class HoverBtn(QtWidgets.QLabel): clicked = QtCore.Signal(QtCore.QObject) def __init__(self, parent): super(HoverBtn, self).__init__(parent) style = ""
"        QFrame{            border-radius: 25px;            border-width: 2px;            border-style: solid;            border-color: rgb(20, 20, 20);            background-color: rgb(170, 170, 170);        }        "
""
self.installEventFilter(self) self.setStyleSheet(style) def eventFilter(self, obj, event): if event.type() == QtCore.QEvent.Enter: self.set_outline(1) return True elif event.type() == QtCore.QEvent.Leave: self.set_outline(0) return True
if event.type() == QtCore.QEvent.MouseButtonPress\ and event.button() == QtCore.Qt.LeftButton: self.clicked.emit(self) return True
return False def set_outline(self, status): ""
"        Update widget stylesheet when highlight        "
""
style = self.styleSheet() border_pattern = r 'border-color\: rgb\(\d+, \d+, \d+\)'
dark = 'border-color: rgb(20, 20, 20)'
light = 'border-color: rgb(21, 255, 9)'
if status == 1: style = re.sub(border_pattern, light, style) elif status == 0: style = re.sub(border_pattern, dark, style) self.setStyleSheet(style)

Suggestion : 6

A tooltip is a message that is shown when hovering the mouse on a widget. In PyQt you can add tooltips to widgets, which then show small hints when hovering over the widget.,You can set any message you want inside the tooltip message. In the program below two buttons are added.Each button has a different tooltip, which is shown when you hover over the button.,This can be a plain text message or a formatted message (HTML). You can add a tooltip by calling .setToolTip("text") on a widget. This is often used to assist the user.,The program below adds tooltip messages to the buttons. This can be either plain text or HTML formatted tags (the tags bold and italic work).A simple tooltip would be:

12
button = QPushButton("Button") button.setToolTip("This is a text")
button = QPushButton("Button")button.setToolTip("<b>HTML</b> <i>can</i> be shown too..")
12345678910111213141516171819202122
from PyQt5.QtWidgets import *import sysclass Window(QWidget): def __init__(self): QWidget.__init__(self) layout = QGridLayout() self.setLayout(layout) button = QPushButton("Button") button.setToolTip("This is a text") layout.addWidget(button, 0, 0) button = QPushButton("Button") button.setToolTip("<b>HTML</b> <i>can</i> be shown too..") layout.addWidget(button, 1, 0)app = QApplication(sys.argv)screen = Window()screen.show()sys.exit(app.exec_())