Issue
Is it possible to change the appearance and function of a QPushButton , such as hover , if a hotkey is held ?
I’m after a solution whereby if I held CTRL down , then hovered , then pressed, it would have a different outcome to hover and press
I’m using Pyside currently and this application is for maya
Solution
Here's an example subclassing QPushButton
's enter and leave events. It will change stylesheets when ctrl is held down, and will also execute different function than when ctrl is not pressed:
from PySide2 import QtCore, QtGui, QtWidgets
class CustomButton(QtWidgets.QPushButton):
def __init__(self, label, parent=None):
super(CustomButton, self).__init__(label, parent)
self.entered = False # Track when the cursor enters this widget.
self.normal_style = "QPushButton {background-color:red;}"
self.alt_style = "QPushButton {background-color:blue;}"
self.setStyleSheet(self.normal_style)
self.clicked.connect(self.click_event)
def enterEvent(self, event):
self.entered = True
self.set_style()
def leaveEvent(self, event):
self.entered = False
self.setStyleSheet(self.normal_style)
def set_style(self):
if self.entered and self.parent().is_ctrl_down:
self.setStyleSheet(self.alt_style)
else:
self.setStyleSheet(self.normal_style)
def func_1(self):
print "1"
def func_2(self):
print "2"
def click_event(self):
if self.entered and self.parent().is_ctrl_down:
self.func_2()
else:
self.func_1()
class Window(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.is_ctrl_down = False # Track when ctrl is held down.
self.my_button = CustomButton("Hello World!", parent=self)
self.main_layout = QtWidgets.QVBoxLayout()
self.main_layout.addWidget(self.my_button)
self.setLayout(self.main_layout)
self.resize(400, 400)
self.setWindowTitle("Button behaviour example")
def keyPressEvent(self, event):
ctrl_state = event.modifiers() == QtCore.Qt.CTRL
if ctrl_state != self.is_ctrl_down:
self.is_ctrl_down = ctrl_state
self.my_button.set_style()
def keyReleaseEvent(self, event):
self.is_ctrl_down = False
self.my_button.set_style()
tool = Window()
tool.show()
I tested this on Maya 2018, so it's in PySide2
. If you're using an older version with PySide
you just need minor tweaks to make this example work.
Answered By - Green Cell
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.