thedoctor
thedoctor

Reputation: 50

How to create hover over effect on a label PyQT5

I am struggling to find information on how to create hover over effects on my labels. I've been trying to get it to work on just a simple version first but am struggling to find any tutorial or information on how to make the hover effect.

from PyQt5.QtWidgets import QApplication, QMainWindow, QFormLayout, QLabel
import sys 
from PyQt5 import QtCore, QtGui, QtWidgets


class window(object):
  def __init__(self):
    MainWindow.setObjectName("MainWindow")
    MainWindow.setGeometry(0,0,700, 600)

    self.centralwidget = QtWidgets.QWidget(MainWindow)
    self.centralwidget.setObjectName("centralwidget")
    MainWindow.setCentralWidget(self.centralwidget)

    self.label = QtWidgets.QLabel(self.centralwidget)
    self.label.setText("Hover Test Label")
    self.label.setGeometry(QtCore.QRect(100, 200, 169, 30))
    self.label.setStyleSheet("border-style:solid; color: black; border-width: 1px;")
    self.label.setObjectName("labeltest")        


if __name__ == "__main__":
  import sys
  app = QtWidgets.QApplication(sys.argv)
  MainWindow = QtWidgets.QMainWindow()
  ui = window()
  MainWindow.show()
  sys.exit(app.exec_())

How to create a hover effect where the background of the Label changes colour.

Upvotes: 0

Views: 1302

Answers (1)

Heike
Heike

Reputation: 24440

You can specify pseudo-states in the style-sheet of the label to differentiate between a normal label and one with a mouse hovering over it. In your example you could do something like

class window(object):
    def __init__(self):
        ....
        self.label.setStyleSheet("""QLabel{border-style:solid; color: black; border-width: 1px;}
QLabel:hover{background-color:red}""")
        ....

The official documentation of Qt also has a page with more elaborate style sheet examples

Upvotes: 1

Related Questions