Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyQt: Changing cursor when hovering a button

Tags:

python

pyqt

pyqt4

I'm trying to make a button (or any other Qwidget), That will change users cursor when hovered.

So for instance, when i hover QPushButton, it will change cursor from Arrow to Pointing Hand.

I am using Qt Style Sheet, so i'm not entirely sure, but is there any way to do something like that there?, should look something like this:

btn.setStyleSheet("#btn {background-image: url(':/images/Button1.png'); border: none; }"
"#btn:hover { change-cursor: cursor('PointingHand'); } 

Note: Code above is for example, second line will have no functionality at all.


However, if not, if there any other way i can achieve this?

like image 829
ShellRox Avatar asked Dec 14 '22 06:12

ShellRox


1 Answers

For anyone who wants to achieve this in PyQt5, this is how I managed to do it. Let's say you have a button and you want your cursor to change to the 'PointingHandCursor' when you hover over the button. You can do it with your_button.setCursor(QCursor(QtCore.Qt.PointingHandCursor)). For example:

from PyQt5.QtWidgets import QWidget, QApplication, QPushButton, QLabel, QProgressBar, 
    QLineEdit, QFileDialog
from PyQt5 import QtGui, QtCore
from PyQt5.QtGui import QCursor

import sys

class Window(QWidget):
    def __init__(self):
        super().__init__()

        self.title = "your_title"

        self.screen_dim = (1600, 900)

        self.width = 650
        self.height = 400

        self.left = int(self.screen_dim[0]/2 - self.width/2)
        self.top = int(self.screen_dim[1]/2 - self.height/2)

        self.init_window()

    def init_window(self):
        self.setWindowIcon(QtGui.QIcon('path_to_icon.png'))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.setStyleSheet('background-color: rgb(52, 50, 51);')

        self.create_layout()

        self.show()

    def create_layout(self):
        self.button = QPushButton('Click Me', self)
        self.button.setCursor(QCursor(QtCore.Qt.PointingHandCursor))

if __name__ == '__main__':

    App = QApplication(sys.argv)
    window = Window()
    sys.exit(App.exec())
like image 159
jaakdentrekhaak Avatar answered Dec 31 '22 13:12

jaakdentrekhaak