Qt第四十章:按钮增强

秒速五厘米 2024-03-30 08:59 233阅读 0赞

目标:为按钮添加一个颜色属性

自定义按钮

  1. # 自定义按钮
  2. class ElButton(QPushButton):
  3. # 定义信号
  4. colorChanged: Signal = Signal(QColor)
  5. # Setter
  6. def set_color(self, color: QColor):
  7. if self.color_init != color:
  8. self.color_init = color
  9. style_sheet = self.styleSheet()
  10. self.setStyleSheet(style_sheet + f"background-color:rgba{color.toTuple()};")
  11. # 颜色改变时发出信号
  12. self.colorChanged.emit(color)
  13. # Getter
  14. def get_color(self):
  15. return self.color_init
  16. """
  17. 定义类属性(属性type,Getter方法,Setter方法,通知信号...)
  18. """
  19. color = Property(type=QColor, fget=get_color, fset=set_color, notify=colorChanged)
  20. def __init__(self, parent=None):
  21. super(ElButton, self).__init__(parent)
  22. self.color_init = QColor(255, 255, 255)

使用

  1. class ExampleWidget(QWidget):
  2. def __init__(self, parent=None):
  3. super(ExampleWidget, self).__init__(parent)
  4. self.resize(400, 300)
  5. self.button = ElButton(self)
  6. self.button.setText("确定")
  7. self.button.set_color(QColor("yellow"))
  8. # 绑定槽函数
  9. self.button.colorChanged.connect(lambda: print("颜色改变啦"))
  10. if __name__ == '__main__':
  11. app = QApplication([])
  12. main = ExampleWidget()
  13. main.show()
  14. app.exec()

发表评论

表情:
评论列表 (有 0 条评论,233人围观)

还没有评论,来说两句吧...

相关阅读