import random
from PySide6.QtCore import Qt, QTimer
from PySide6.QtGui import QColor, QPalette
from PySide6.QtWidgets import QApplication, QLabel, QMainWindow, QVBoxLayout, QWidget
# 构造一个可以设置颜色的 Color Widget
class ColorWidget(QWidget):
def __init__(self, color: QColor):
super().__init__()
self.setAutoFillBackground(True)
palette = self.palette()
palette.setColor(QPalette.ColorGroup.Normal, QPalette.ColorRole.Window, color)
self.setPalette(palette)
def reset_color(self, color: QColor):
palette = self.palette()
palette.setColor(QPalette.ColorGroup.Normal, QPalette.ColorRole.Window, color)
self.setPalette(palette)
print('reset to color:', color.name(QColor.NameFormat.HexRgb))
if __name__ == '__main__':
class test_window(QMainWindow):
def __init__(self):
super().__init__()
color = QColor(QColor.colorNames()[0])
self.window = ColorWidget(color)
self.label = QLabel()
self.label.setAlignment(Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignHCenter)
self.label.setText('color name:{}({})'.format(QColor.colorNames()[0], color.name(QColor.NameFormat.HexRgb)))
self.layout = QVBoxLayout()
self.layout.addWidget(self.label)
self.layout.addWidget(self.window)
self.container = QWidget()
self.container.setLayout(self.layout)
self.setCentralWidget(self.container)
# 基于定时器,让它每一秒出发一次变色动作
self.color_timer = QTimer()
self.color_timer.timeout.connect(self.color_change)
self.color_timer.setInterval(1000)
self.color_timer.start()
def color_change(self):
color_name = random.choice(QColor.colorNames())
color = QColor(color_name)
self.label.setText('color name:{}({})'.format(color_name, color.name(QColor.NameFormat.HexRgb)))
self.window.reset_color(color)
app = QApplication()
ins = test_window()
ins.show()
app.exec()
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。