tabelwidget怎么设置标题背景色?
时间: 2023-12-06 07:43:18 浏览: 69
可以通过设置QHeaderView的样式来设置表格标题的背景色,具体步骤如下:
1. 获取表格的水平标题头(horizontalHeader)对象。
2. 设置水平标题头样式表,如下:
```python
header_style = "::section{background-color: #333; color: white;}"
self.tableWidget.horizontalHeader().setStyleSheet(header_style)
```
其中,`::section`表示表头的某个部分,`background-color`表示背景色,`color`表示文字颜色。
完整代码示例:
```python
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidget, QTableWidgetItem
from PyQt5.QtGui import QFont
from PyQt5.QtCore import Qt
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle("TableWidget Demo")
self.setGeometry(300, 300, 500, 300)
self.tableWidget = QTableWidget(self)
self.tableWidget.setGeometry(20, 20, 460, 260)
self.tableWidget.setColumnCount(3)
self.tableWidget.setRowCount(5)
self.tableWidget.setHorizontalHeaderLabels(["Name", "Age", "Gender"])
header_style = "::section{background-color: #333; color: white;}"
self.tableWidget.horizontalHeader().setStyleSheet(header_style)
font = QFont("Arial", 12)
for i in range(self.tableWidget.rowCount()):
for j in range(self.tableWidget.columnCount()):
item = QTableWidgetItem()
item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
item.setFont(font)
item.setText(f"Row {i}, Column {j}")
self.tableWidget.setItem(i, j, item)
if __name__ == "__main__":
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
```
运行效果如下图所示:
![tablewidget_title_background_color.png](https://cdn.jsdelivr.net/gh/katoluo/imgHosting/img/tablewidget_title_background_color.png)
阅读全文