前言
Pyside6官方教程给了一个使用表格显示颜色的教程,原教程地址如下:源地址, 结合前面button信号的学习,就魔改添加了如下功能:增加一列按钮,可以修改该行的颜色值,通过点击按钮生成指定的颜色背景。
代码如下
import sys
from functools import partial
from PySide6.QtGui import QColor
from PySide6.QtWidgets import QApplication, QTableWidget, QPushButton, QTableWidgetItemcolors = [("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信息传递到信号函数中
注:本文为作者原创,转载需注明出处!