目标:为按钮添加一个颜色属性
自定义按钮
# 自定义按钮
class ElButton(QPushButton):
# 定义信号
colorChanged: Signal = Signal(QColor)
# Setter
def set_color(self, color: QColor):
if self.color_init != color:
self.color_init = color
style_sheet = self.styleSheet()
self.setStyleSheet(style_sheet + f"background-color:rgba{color.toTuple()};")
# 颜色改变时发出信号
self.colorChanged.emit(color)
# Getter
def get_color(self):
return self.color_init
"""
定义类属性(属性type,Getter方法,Setter方法,通知信号...)
"""
color = Property(type=QColor, fget=get_color, fset=set_color, notify=colorChanged)
def __init__(self, parent=None):
super(ElButton, self).__init__(parent)
self.color_init = QColor(255, 255, 255)
使用
class ExampleWidget(QWidget):
def __init__(self, parent=None):
super(ExampleWidget, self).__init__(parent)
self.resize(400, 300)
self.button = ElButton(self)
self.button.setText("确定")
self.button.set_color(QColor("yellow"))
# 绑定槽函数
self.button.colorChanged.connect(lambda: print("颜色改变啦"))
if __name__ == '__main__':
app = QApplication([])
main = ExampleWidget()
main.show()
app.exec()