如果按住热键更改 QPushButton 行为?

Change QPushButton behaviour if hotkey is held ?

如果按住热键,是否可以更改 QPushButton 的外观和功能,例如悬停?

我正在寻找一个解决方案,如果我按住 CTRL,然后悬停,然后按下,悬停并按下

会有不同的结果

我目前正在使用 Pyside,此应用程序适用于 Maya

下面是子类化 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 的旧版本,您只需稍作调整即可使此示例正常工作。