PyQT5之QTableWidget

import os, sys, re
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QBrush

'''
void	currentCellChanged(int currentRow, int currentColumn, int previousRow, int previousColumn)
void	currentItemChanged(QTableWidgetItem *current, QTableWidgetItem *previous)
void	itemActivated(QTableWidgetItem *item)
void	itemChanged(QTableWidgetItem *item)
void	itemClicked(QTableWidgetItem *item)
void	itemDoubleClicked(QTableWidgetItem *item)
void	itemEntered(QTableWidgetItem *item)
void	itemPressed(QTableWidgetItem *item)
void	itemSelectionChanged()
'''

class QTableWidgetDemo(QWidget):
    def __init__(self):
        super(QTableWidgetDemo, self).__init__()
        self.setWindowTitle("QTableWidgetDemo")
        self.resize( 600,500 )
        self.mainlayout = QVBoxLayout(self)
        #创建表格 5行,4列
        self.tablewidget = QTableWidget(5,4,self)
        self.mainlayout.addWidget(self.tablewidget)
        # 设置水平表头
        self.tablewidget.setHorizontalHeaderLabels(["第1列", "第2列", "第3列", "第4列"])

        # 设置垂直表头
        self.tablewidget.setVerticalHeaderLabels(["a", "b", "c", "d", "e"])
        self.tablewidget.verticalHeader().setVisible(True)
        # 隐藏垂直表头
        # self.tablewidget.verticalHeader().hide()
        # 宽度适应
        self.tablewidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        # 表头颜色
        self.tablewidget.horizontalHeader().setStyleSheet("QHeaderView::section{background:lightgreen;}")

        # self.tablewidget.setShowGrid(False)  # 隐藏表格线

        # 设置表格项
        for row in range(5):
            for col in range(4):
                item = QTableWidgetItem("第%d行 %d列"%(row,col))
                self.tablewidget.setItem(row, col, item)
        # 常用的信号 setBackground(QBrush(Qt.white))
        self.setMouseTracking(True)

        # self.tablewidget.setEditTriggers(QAbstractItemView.NoEditTriggers)   # 禁止编辑
        self.tablewidget.setSelectionBehavior(QAbstractItemView.SelectRows)    # 整行选择
        #
        # item 被点击 设置背景红色
        self.tablewidget.itemClicked.connect(self.slot_itemClicked)
        # item 被双击 设置背景绿色
        self.tablewidget.itemDoubleClicked.connect(self.slot_itemDoubleClicked)
        # item 进入  设置背景黄
        self.tablewidget.itemEntered.connect(self.slot_itemEntered)
        # press
        self.tablewidget.itemPressed.connect(self.slot_itemPressed)


    def  slot_itemClicked(self,item ):
        item.setBackground(QBrush(Qt.red))

    def  slot_itemDoubleClicked(self, item):
        item.setBackground(QBrush(Qt.green))

    def  slot_itemEntered(self, item):
        item.setBackground(QBrush(Qt.yellow))

    def  slot_itemPressed(self, item):
        item.setBackground(QBrush(Qt.gray))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    test = QTableWidgetDemo()
    test.show()
    sys.exit(app.exec_())

posted @ 2024-06-14 14:25  星空28  阅读(18)  评论(0编辑  收藏  举报