Issue
I have the following test script.
from PyQt5.QtWidgets import *
import sys
class MW(QMainWindow):
def __init__(self):
super(MW, self).__init__()
widget = QWidget()
widget.setStyleSheet('QWidget {background-color:#000000; color:#FFFFFF}'
"QPushButton:hover {background-color:#202020}")
self.setCentralWidget(widget)
box = QVBoxLayout(widget)
but1_box = QHBoxLayout()
but1 = QPushButton("Button 1")
lab1 = QLabel("Label 1")
but1_box.addWidget(but1)
but1_box.addWidget(lab1)
box.addLayout(but1_box)
but2_box = QHBoxLayout()
but2 = QPushButton("Button 2")
lab2 = QLabel("Label 2")
but2_box.addWidget(but2)
but2_box.addWidget(lab2)
box.addLayout(but2_box)
self.show()
app = QApplication(sys.argv)
mw = MW()
sys.exit(app.exec_())
If I hover over the PushButton it changes its color to a gray and I want that the associated Label changes its color while hovering over the button.
Solution
It is not possible to implement directly using the pseudo-states of the Qt Style Sheet but you will have to use an eventFilter that detects the changes of the hover (enter and leave) and that modifies the stylesheet of the other elements
from PyQt5.QtCore import pyqtSignal, QEvent, QObject
from PyQt5.QtWidgets import (
QApplication,
QHBoxLayout,
QLabel,
QMainWindow,
QPushButton,
QVBoxLayout,
QWidget,
)
import sys
class HoverListener(QObject):
entered = pyqtSignal()
leaved = pyqtSignal()
def __init__(self, widget):
super(HoverListener, self).__init__(widget)
self._widget = widget
self.widget.installEventFilter(self)
@property
def widget(self):
return self._widget
def eventFilter(self, obj, event):
if obj == self.widget:
if event.type() == QEvent.Enter:
self.entered.emit()
elif event.type() == QEvent.Leave:
self.leaved.emit()
return super(HoverListener, self).eventFilter(obj, event)
class MW(QMainWindow):
def __init__(self):
super(MW, self).__init__()
widget = QWidget()
widget.setStyleSheet(
"QWidget {background-color:#000000; color:#FFFFFF}"
"QPushButton:hover {background-color:#202020}"
)
self.setCentralWidget(widget)
but1 = QPushButton("Button 1")
lab1 = QLabel("Label 1")
hover_listener1 = HoverListener(but1)
hover_listener1.entered.connect(
lambda label=lab1: label.setStyleSheet("background-color:#202020")
)
hover_listener1.leaved.connect(lambda label=lab1: label.setStyleSheet(""))
but2 = QPushButton("Button 2")
lab2 = QLabel("Label 2")
hover_listener2 = HoverListener(but2)
hover_listener2.entered.connect(
lambda label=lab2: label.setStyleSheet("background-color:#202020")
)
hover_listener2.leaved.connect(lambda label=lab2: label.setStyleSheet(""))
box = QVBoxLayout(widget)
but1_box = QHBoxLayout()
but1_box.addWidget(but1)
but1_box.addWidget(lab1)
box.addLayout(but1_box)
but2_box = QHBoxLayout()
but2_box.addWidget(but2)
but2_box.addWidget(lab2)
box.addLayout(but2_box)
self.show()
app = QApplication(sys.argv)
mw = MW()
sys.exit(app.exec_())
Answered By - eyllanesc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.