前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >PySide6 GUI 编程(15):构造可变色的QWidget

PySide6 GUI 编程(15):构造可变色的QWidget

原创
作者头像
bowenerchen
发布2024-07-25 08:01:45
910
发布2024-07-25 08:01:45
举报
文章被收录于专栏:编码视界

示例代码

代码语言:python
代码运行次数:0
复制
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()

运行效果

周期性定时变色 Widget
周期性定时变色 Widget

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 示例代码
  • 运行效果
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档