向第三方库的现有方法添加功能

2024-06-08 00:33:22 发布

您现在位置:Python中文网/ 问答频道 /正文

如何向第三方对象的现有方法添加功能?你知道吗

我不确定这个问题是否表达正确,所以这里有一个我想要达到的目标的例子。你知道吗

以下功能用于闪烁按钮:

def clickColor(button, color):
    beforeColor = button.palette().color(QPalette.Background)
    button.setStyleSheet("background-color: %s" % color)
    QTimer.singleShot(100, lambda: unClickColor(button, beforeColor))

def unClickColor(button, beforeColor):
    button.setStyleSheet("background-color: %s" % beforeColor.name())

我希望PyQt5库的每个QPushButton在单击时都闪烁。你知道吗

我的想法是将clickColor函数添加到已单击。连接QPushButton的方法,但保持现有方法不变。你知道吗

做我想做的事的正确方法是什么?你知道吗


Tags: 对象方法功能目标defbutton按钮例子
1条回答
网友
1楼 · 发布于 2024-06-08 00:33:22

您可以创建一个自定义子类,然后在需要闪烁效果的任何地方使用它而不是普通的QPushButton。如果您使用的是Qt设计器,那么还可以使用widget promotion将添加到ui文件中的任何按钮替换为自定义类(有关详细信息,请参见this answer)。你知道吗

下面是一个基本的演示脚本:

import sys
from PyQt5 import QtCore, QtGui, QtWidgets

class BlinkButton(QtWidgets.QPushButton):
    def __init__(self, *args, **kwargs):
        super(BlinkButton, self).__init__(*args, **kwargs)
        self.clicked.connect(self._blink)
        self._blink_color = QtGui.QColor()

    def blinkColor(self):
        return QtGui.QColor(self._blink_color)

    def setBlinkColor(self, color=None):
        self._blink_color = QtGui.QColor(color)

    def _blink(self):
        if self._blink_color.isValid():
            self.setStyleSheet(
                'background-color: %s' % self._blink_color.name())
            QtCore.QTimer.singleShot(100, lambda: self.setStyleSheet(''))

class Window(QtWidgets.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.button = BlinkButton('Test', self)
        self.button.setBlinkColor('red')
        self.button.clicked.connect(self.handleButton)
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(self.button)
        layout.addWidget(self.button2)

    def handleButton(self):
        print('Hello World!')

if __name__ == '__main__':

    app = QtWidgets.QApplication(sys.argv)
    window = Window()
    window.setGeometry(600, 100, 200, 100)
    window.show()
    sys.exit(app.exec_())

相关问题 更多 >

    热门问题