PySide6 Tutorials (一)表格小部件魔改

前言

Pyside6官方教程给了一个使用表格显示颜色的教程,原教程地址如下:源地址, 结合前面button信号的学习,就魔改添加了如下功能:增加一列按钮,可以修改该行的颜色值,通过点击按钮生成指定的颜色背景。

代码如下
import sys
from functools import partial
from PySide6.QtGui import QColor
from PySide6.QtWidgets import QApplication, QTableWidget, QPushButton, QTableWidgetItem


colors = [("Red", "#FF0000"),
          ("Green", "#00FF00"),
          ("Blue", "#0000FF"),
          ("Black", "#000000"),
          ("White", "#FFFFFF"),
          ("Electric Green", "#41CD52"),
          ("Dark Blue", "#222840"),
          ("Yellow", "#F9E56d")]


def get_rgb_from_hex(code):
    code_hex = code.replace("#", "")
    rgb = tuple(int(code_hex[i:i+2], 16) for i in (0, 2, 4))
    return QColor.fromRgb(rgb[0], rgb[1], rgb[2])


def change_background(button):
    row = button.property("row")
    col = button.property("col")

    if row is not None and col is not None:
        item_color = QTableWidgetItem()
        text = get_rgb_from_hex(table.item(row, 1).text())
        item_color.setBackground(text)
        table.setItem(row, 2, item_color)


app = QApplication()
table = QTableWidget()
table.setRowCount(len(colors))
table.setColumnCount(len(colors[0]) + 2)
table.setHorizontalHeaderLabels(["Name", "Hex Code", "Color", "Change"])

for i, (name, code) in enumerate(colors):
    item_name = QTableWidgetItem(name)
    item_code = QTableWidgetItem(code)
    item_color = QTableWidgetItem()
    item_color.setBackground(get_rgb_from_hex(code))
    table.setItem(i, 0, item_name)
    table.setItem(i, 1, item_code)
    table.setItem(i, 2, item_color)

    button = QPushButton("Click me!")
    button.setProperty("row", i)
    button.setProperty("col", 3)
    button.clicked.connect(partial(change_background, button))

    table.setCellWidget(i, 3, button)


table.show()
table.resize(600, 800)
sys.exit(app.exec())

效果如下图

效果图

涉及知识点
  • 如何获取表格中button所在的行列信息
  • 如何将button信息传递到信号函数中

注:本文为作者原创,转载需注明出处!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值