如果按住热键,是否可以更改QPushButton的外观和功能(如悬停)?
我正在寻找一种解决方案,如果我按住CTRL,然后将鼠标悬停然后按,则将鼠标悬停并按
我当前正在使用Pyside,此应用程序适用于Maya
答案 0 :(得分:0)
下面是一个示例,它继承了QPushButton
的进入和离开事件。按住ctrl时将更改样式表,并且执行的功能与不按下ctrl时不同:
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()
我在Maya 2018上对此进行了测试,因此它位于PySide2
中。如果您使用的是带有PySide
的旧版本,则只需稍作调整即可使该示例正常工作。