PyQt——QTableWidget

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

import sys
from PyQt5.QtWidgets import (QWidget, QTableWidget, QHBoxLayout, QApplication, QTableWidgetItem, QAbstractItemView  )

class Table(QWidget):
	def __init__(self):
		super().__init__()
		self.initUI()

	def initUI(self):
		self.setWindowTitle("QTableWidget 例子")
		self.resize(430,230);
		conLayout = QHBoxLayout()
		tableWidget = QTableWidget()
		tableWidget.setRowCount(4)
		tableWidget.setColumnCount(3)
		conLayout.addWidget(tableWidget )
		
		tableWidget.setHorizontalHeaderLabels(['姓名','性别','体重(kg)'])  
        tableWidget.setVerticalHeaderLabels(["行1", "行2", "行3", "行4", "行5"])
        
        tableWidget.horizontalHeader().setSelectionResizeMode(QHeaderView.Stretch)#设置表格为自适应的伸缩模式
		  
		newItem = QTableWidgetItem("张三")  
		tableWidget.setItem(0, 0, newItem)  
		  
		newItem = QTableWidgetItem("男")  
		tableWidget.setItem(0, 1, newItem)  
		  
		newItem = QTableWidgetItem("160")  
		tableWidget.setItem(0, 2, newItem)   
		
		# 将表格变为禁止编辑
		#tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
		
		# 设置表格为整行选择
		#tableWidget.setSelectionBehavior( QAbstractItemView.SelectRows)

		# 将行和列的大小设为与内容相匹配
		#tableWidget.resizeColumnsToContents()
		#tableWidget.resizeRowsToContents()
		
		#表格表头的显示与隐藏
		#tableWidget.verticalHeader().setVisible(False)
		#tableWidget.horizontalHeader().setVisible(False)
		
		# 不显示表格单元格的分割线
		#tableWidget.setShowGrid(False)
        # 不显示垂直表头
		tableWidget.verticalHeader().setVisible(False)
		comBox = QComboBox()
		combox.addItem("男")
		comBox.addItem("女")
		comBox.setStyleSheet("QComboBox{margin:3px};")
		tableWidget.setCellWidget(0, 1, comBox)
		searchBtn = QPushButton("修改")
		searchBtn.setDown(True)
		searchBtn.setStyleSheet("QPushButton{margin:3px};")
		tableWidget.setCellWidget(0, 2, searchBtn)

		self.setLayout(conLayout)

if __name__ == '__main__':
	app = QApplication(sys.argv)
	example = Table()  
	example.show()   
	sys.exit(app.exec_())

在表格中快速定位到指定行
# -*- coding: utf-8 -*- 
'''
    【简介】
	PyQT5的表格控件选中单元格
   
  
'''

import sys
from PyQt5.QtWidgets import  *
from PyQt5 import QtCore  
from PyQt5.QtGui import  QColor , QBrush

class Table(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("QTableWidget 例子")
        self.resize(600,800);
        conLayout = QHBoxLayout()
        tableWidget = QTableWidget()
        tableWidget.setRowCount(30)
        tableWidget.setColumnCount(4)
        conLayout.addWidget(tableWidget )
        
        for i in range(30):
            for j in range(4):
                itemContent = '(%d,%d)'% (i,j)  
                tableWidget.setItem(i,j, QTableWidgetItem( itemContent ) )
        self.setLayout(conLayout)
        
        #遍历表查找对应的item
        text = "(10,1)"
        items = tableWidget.findItems(text, QtCore.Qt.MatchExactly)             
        item = items[0]
        # 选中单元格
        #item.setSelected( True)
        # 设置单元格的背景颜色为红色
        item.setForeground(QBrush(QColor(255, 0, 0))) 
                
        row = item.row()   
        #滚轮定位过去,快速定位到第17行
        tableWidget.verticalScrollBar().setSliderPosition(row)  
        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    example = Table()  
    example.show()   
    sys.exit(app.exec_())
    

2、设置单元格

(1)设置单元格文本颜色

# -*- coding: utf-8 -*- 

'''
    【简介】
	PyQT5中单元格内的文本颜色
   
  
'''

import sys
from PyQt5.QtWidgets import (QWidget, QTableWidget, QHBoxLayout, QApplication, QTableWidgetItem )
from PyQt5.QtGui import QBrush,  QColor ,  QFont 

class Table(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("QTableWidget 例子")
        self.resize(430,230);
        conLayout = QHBoxLayout()
        tableWidget = QTableWidget()
        tableWidget.setRowCount(4)
        tableWidget.setColumnCount(3)
        conLayout.addWidget(tableWidget )
        
        tableWidget.setHorizontalHeaderLabels(['姓名','性别','体重(kg)'])  
          
        newItem = QTableWidgetItem("张三")  
        newItem.setForeground(QBrush(QColor(255, 0, 0)))
        tableWidget.setItem(0, 0, newItem)  
                 
        newItem = QTableWidgetItem("男")  
        newItem.setForeground(QBrush(QColor(255, 0, 0)))
        tableWidget.setItem(0, 1, newItem)  
          
        newItem = QTableWidgetItem("160") 
        newItem.setForeground(QBrush(QColor(255, 0, 0))) 
        tableWidget.setItem(0, 2, newItem)     
        
        self.setLayout(conLayout)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    example = Table()  
    example.show()   
    sys.exit(app.exec_())

(2)字体加粗

# -*- coding: utf-8 -*- 

'''
    【简介】
	PyQT5中单元格内的字体大小
    
  
'''

import sys
from PyQt5.QtWidgets import (QWidget, QTableWidget, QHBoxLayout, QApplication, QTableWidgetItem )
from PyQt5.QtGui import QBrush,  QColor ,  QFont 

class Table(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("QTableWidget 例子")
        self.resize(430,230);
        conLayout = QHBoxLayout()
        tableWidget=QTableWidget()
        tableWidget.setRowCount(4)
        tableWidget.setColumnCount(3)
        conLayout.addWidget(tableWidget )
        
        tableWidget.setHorizontalHeaderLabels(['姓名','性别','体重(kg)'])  
          
        newItem = QTableWidgetItem("张三")  
        newItem.setFont( QFont( "Times", 12, QFont.Black ) )
        tableWidget.setItem(0, 0, newItem)  
                 
        newItem = QTableWidgetItem("男")  
        newItem.setFont( QFont( "Times", 12, QFont.Black ) )
        tableWidget.setItem(0, 1, newItem)  
          
        newItem = QTableWidgetItem("160") 
        newItem.setFont( QFont( "Times", 12, QFont.Black ) )
        tableWidget.setItem(0, 2, newItem)   
        
        self.setLayout(conLayout)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    example = Table()  
    example.show()   
    sys.exit(app.exec_())

(3)设置单元格的排序方式

# -*- coding: utf-8 -*- 

'''
    【简介】
	PyQT5中单元格排序
   
  
'''

import sys
from PyQt5.QtWidgets import (QWidget, QTableWidget, QHBoxLayout, QApplication, QTableWidgetItem )
from PyQt5.QtCore import Qt

class Table(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("QTableWidget 例子")
        self.resize(430, 230);
        conLayout = QHBoxLayout()
        tableWidget=QTableWidget()
        tableWidget.setRowCount(4)
        tableWidget.setColumnCount(3)
        conLayout.addWidget(tableWidget )
        
        tableWidget.setHorizontalHeaderLabels(['姓名','性别','体重(kg)'])  
          
        newItem = QTableWidgetItem("张三")  
        tableWidget.setItem(0, 0, newItem)  
                 
        newItem = QTableWidgetItem("男")  
        tableWidget.setItem(0, 1, newItem)  
          
        newItem = QTableWidgetItem("160") 
        tableWidget.setItem(0, 2, newItem)   
      
        newItem = QTableWidgetItem("李四")  
        tableWidget.setItem(1, 0, newItem)  
                 
        newItem = QTableWidgetItem("女")  
        tableWidget.setItem(1, 1, newItem)  
          
        newItem = QTableWidgetItem("155") 
        tableWidget.setItem(1, 2, newItem)      
       
        newItem = QTableWidgetItem("王五")  
        tableWidget.setItem(2, 0, newItem)  
                 
        newItem = QTableWidgetItem("男")  
        tableWidget.setItem(2, 1, newItem)  
          
        newItem = QTableWidgetItem("170") 
        tableWidget.setItem(2, 2, newItem)        
        
   
        # Qt.DescendingOrder 降序
        # Qt.AscendingOrder 升序
        tableWidget.sortItems(2,  Qt.DescendingOrder )
        
        self.setLayout(conLayout)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    example = Table()  
    example.show()   
    sys.exit(app.exec_())

(4)设置单元格文本的对其方式

# -*- coding: utf-8 -*- 
'''
    【简介】
	PyQT5中单元格中文本对齐方式例子
   
  
'''

import sys
from PyQt5.QtWidgets import (QWidget, QTableWidget, QHBoxLayout, QApplication, QTableWidgetItem )
from PyQt5.QtCore import Qt
 
class Table(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("QTableWidget 例子")
        self.resize(430,230);
        conLayout = QHBoxLayout()
        tableWidget = QTableWidget()
        tableWidget.setRowCount(4)
        tableWidget.setColumnCount(3)
        conLayout.addWidget(tableWidget )
        
        tableWidget.setHorizontalHeaderLabels(['姓名','性别','体重(kg)'])  
        newItem = QTableWidgetItem("张三")  
        
        newItem.setTextAlignment( Qt.AlignRight| Qt.AlignBottom )      
        tableWidget.setItem(0, 0, newItem)  
                          
        newItem = QTableWidgetItem("男")  
        tableWidget.setItem(0, 1, newItem)  
          
        newItem = QTableWidgetItem("160")  
        tableWidget.setItem(0, 2, newItem)   
        
        self.setLayout(conLayout)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    example = Table()  
    example.show()   
    sys.exit(app.exec_())

(5)合并单元格效果的实现

# -*- coding: utf-8 -*- 

'''
    【简介】
	PyQT5中单元格合并例子
   
  
'''

import sys
from PyQt5.QtWidgets import (QWidget, QTableWidget, QHBoxLayout, QApplication, QTableWidgetItem )

class Table(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("QTableWidget 例子")
        self.resize(430,230 );
        conLayout = QHBoxLayout()
        tableWidget= QTableWidget()
        tableWidget.setRowCount(4)
        tableWidget.setColumnCount(3)
        conLayout.addWidget(tableWidget )
        
        tableWidget.setHorizontalHeaderLabels(['姓名','性别','体重(kg)'])  
        tableWidget.setSpan(0, 0, 3, 1)   
          
        newItem = QTableWidgetItem("张三")  
        tableWidget.setItem(0, 0, newItem)  
          
        newItem = QTableWidgetItem("男")  
        tableWidget.setItem(0, 1, newItem)  
          
        newItem = QTableWidgetItem("160")  
        tableWidget.setItem(0, 2, newItem)   
        
        self.setLayout(conLayout)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    example = Table()  
    example.show()   
    sys.exit(app.exec_())

(6)设置单元格的大小

# -*- coding: utf-8 -*- 
'''
    【简介】
    PyQT5中单元格的宽度和高度例子
 
  
'''

import sys
from PyQt5.QtWidgets import (QWidget, QTableWidget, QHBoxLayout, QApplication, QTableWidgetItem )

class Table(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("QTableWidget 例子")
        self.resize(530,300);
        conLayout = QHBoxLayout()
        tableWidget=QTableWidget()
        tableWidget.setRowCount(4)
        tableWidget.setColumnCount(3)
        conLayout.addWidget(tableWidget )
        
        tableWidget.setHorizontalHeaderLabels(['姓名','性别','体重(kg)'])  
          
        newItem = QTableWidgetItem("张三")  
        tableWidget.setItem(0, 0, newItem)  
        
        #将第1列的单元格,设置成150宽度
        tableWidget.setColumnWidth(0,150)  
        #将第1行的单元格,设置成120的高度
        tableWidget.setRowHeight(0,120)      

        newItem = QTableWidgetItem("男")  
        tableWidget.setItem(0, 1, newItem)  
          
        newItem = QTableWidgetItem("160")  
        tableWidget.setItem(0, 2, newItem)   
        
        self.setLayout(conLayout)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    example = Table()  
    example.show()   
    sys.exit(app.exec_())

(7)单元格中不显示分割线

tabelWidget.setShowGrid(False)
tabelWidget.verticalHeader().setVisible(False)

(8)为单元格添加图片

# -*- coding: utf-8 -*- 

'''
    【简介】
	PyQT5中单元格添加图片例子
   
  
'''

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore  import *

class Table( QWidget ):
         
	def __init__(self):
		super().__init__()
		self.initUI()

	def initUI(self):
		self.setWindowTitle("QTableWidget 例子")
		self.resize(500,300);
		conLayout = QHBoxLayout()
		self.tableWidget= QTableWidget()
		self.tableWidget.setRowCount(5)
		self.tableWidget.setColumnCount(4)
		conLayout.addWidget(self.tableWidget )
				 
		self.tableWidget.setHorizontalHeaderLabels(['姓名','性别','体重', '显示图片'])  
		self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
		                                		
		newItem = QTableWidgetItem("张三")    
		self.tableWidget.setItem(0, 0, newItem)  
		  
		newItem = QTableWidgetItem("男")  
		self.tableWidget.setItem(0, 1, newItem)  
		  
		newItem = QTableWidgetItem("160")  
		self.tableWidget.setItem(0, 2, newItem)   
		
		newItem = QTableWidgetItem(QIcon("./images/bao1.png"), "背包")
		self.tableWidget.setItem(0, 3, newItem ) 
		self.setLayout(conLayout)

if __name__ == '__main__':
	app = QApplication(sys.argv)
	example = Table()  
	example.show()   
	sys.exit(app.exec_())

(9)改变单元格中显示的图片大小

# -*- coding: utf-8 -*- 

'''
    【简介】
	PyQT5中单元格改变每行单元格显示的图标大小例子
   
  
'''

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore  import *

class Table(QWidget):
	def __init__(self):
		super().__init__()
		self.initUI()

	def initUI(self):
		self.setWindowTitle("QTableWidget 例子")
		self.resize(1000,900);
		conLayout = QHBoxLayout()
		
		table= QTableWidget()
		table.setColumnCount(3)  
		table.setRowCount(5)  
		
		table.setHorizontalHeaderLabels(['图片1','图片2','图片3'])  
		  
		table.setEditTriggers( QAbstractItemView.NoEditTriggers)  
		
		table.setIconSize(QSize(300,200));
		
		for i in range(3):   # 让列宽和图片相同  
		   table.setColumnWidth(i , 300)  
		for i in range(5):   # 让行高和图片相同  
			table.setRowHeight(i , 200)  
		
		for k in range(15): # 27 examples of DDA  
			i = k/3  
			j = k%3  
			item = QTableWidgetItem()  
			item.setFlags(Qt.ItemIsEnabled)  #用户点击时表格时,图片被选中  
			icon = QIcon(r'.\images\bao%d.png' % k  ) 
			item.setIcon(QIcon(icon )  )  
									
			print('e/icons/%d.png i=%d  j=%d' %( k , i , j ) )   				   
			table.setItem(i,j,item)  
		
		conLayout.addWidget( table)  
		self.setLayout(conLayout)
       
if __name__ == '__main__':
	app = QApplication(sys.argv)
	example = Table()  
	example.show()   
	sys.exit(app.exec_())

(10)获取单元格的内容

tableWidget.itemCliked.connect(self.handleItemClick)
def getItem(self, item)
	print("you selected => " + item.text())
3、支持右键菜单
# -*- coding: utf-8 -*- 
'''
    【简介】
    PyQT5的表格中支持右键菜单例子
    
  
'''

import sys
from PyQt5.QtWidgets import ( QMenu , QPushButton,  QWidget, QTableWidget, QHBoxLayout, QApplication, QTableWidgetItem, QHeaderView)
from PyQt5.QtCore import  QObject, Qt 

class Table( QWidget ):
                   
	def __init__(self):
		super().__init__()
		self.initUI()

	def initUI(self):
		self.setWindowTitle("QTableWidget 例子")
		self.resize(500,300);
		conLayout = QHBoxLayout()
		self.tableWidget= QTableWidget()
		self.tableWidget.setRowCount(5)
		self.tableWidget.setColumnCount(3)
		conLayout.addWidget(self.tableWidget )
				
		self.tableWidget.setHorizontalHeaderLabels(['姓名','性别','体重' ])  
		self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
		
		newItem = QTableWidgetItem("张三")      
		self.tableWidget.setItem(0, 0, newItem)  
		  
		newItem = QTableWidgetItem("男")  
		self.tableWidget.setItem(0, 1, newItem)  
		  
		newItem = QTableWidgetItem("160")  
		self.tableWidget.setItem(0, 2, newItem)   
		#表格中第二行记录
		newItem = QTableWidgetItem("李四")      
		self.tableWidget.setItem(1, 0, newItem)  
		  
		newItem = QTableWidgetItem("女")  
		self.tableWidget.setItem(1, 1, newItem)  
		  
		newItem = QTableWidgetItem("170")  
		self.tableWidget.setItem(1, 2, newItem)   
		
		self.tableWidget.setContextMenuPolicy(Qt.CustomContextMenu)######允许右键产生子菜单
		self.tableWidget.customContextMenuRequested.connect(self.generateMenu)   ####右键菜单
		self.setLayout(conLayout)
        
	def generateMenu(self,pos):
		#rint( pos)
		row_num = -1
		for i in self.tableWidget.selectionModel().selection().indexes():
			row_num = i.row()
		
		if row_num < 2 :
			menu = QMenu()
			item1 = menu.addAction(u"选项一")
			item2 = menu.addAction(u"选项二")
			item3 = menu.addAction(u"选项三" )
			action = menu.exec_(self.tableWidget.mapToGlobal(pos))
			if action == item1:
				print( '您选了选项一,当前行文字内容是:',self.tableWidget.item(row_num,0).text(),self.tableWidget.item(row_num,1).text() ,self.tableWidget.item(row_num,2).text())

			elif action == item2:
				print( '您选了选项二,当前行文字内容是:',self.tableWidget.item(row_num,0).text(),self.tableWidget.item(row_num,1).text() ,self.tableWidget.item(row_num,2).text() )

			elif action == item3:
				print( '您选了选项三,当前行文字内容是:', self.tableWidget.item(row_num,0).text(),self.tableWidget.item(row_num,1).text() ,self.tableWidget.item(row_num,2).text() )
			else:
				return
		
if __name__ == '__main__':
	app = QApplication(sys.argv)
	example = Table()  
	example.show()   
	sys.exit(app.exec_())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

极地星光

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值