pySide2 tableWidget 学习笔记
本帖最后由 Cool_Breeze 于 2021-8-11 08:51 编辑色码对照网站: http://www.divcss5.com/peise/#character_2
图标查找网站:https://igoutu.cn/icon/set/%E7%83%AD%E9%97%A8/office
PyQtAPI 网站:https://www.riverbankcomputing.c ... widgets-module.html
# -*- coding : utf-8 -*-
from PySide2.QtWidgets import QApplication, QMessageBox, QDesktopWidget,QToolTip,QDialog,QPushButton,QInputDialog,QFontDialog,QFileDialog,QHeaderView,QTableWidgetItem,QAbstractItemView,QComboBox,QSpinBox,QMenu
from PySide2.QtUiTools import QUiLoader
from PySide2.QtGui import QFont, QMovie, QIntValidator, QDoubleValidator, QRegExpValidator, Qt, QPixmap,QStandardItemModel, QStandardItem,QColor,QIcon
from PySide2.QtCore import QObject, QThread, Signal, Slot, QRegExp, QDateTime, QTime, QStringListModel,QSize
import time
import sys
import os
import threading
import datetime
class HomeMain:
def __init__(self):
self.ui = QUiLoader().load('tableView.ui')
# ==========================================================================================
#tableView
self.ui.tableView.horizontalHeader().setStretchLastSection(False)# 最后一列是否延生
self.ui.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)# 表格大小自适应
self.model = QStandardItemModel(4, 4)
self.model.setHorizontalHeaderLabels(["标题1","标题2","标题3","标题4"])
self.ui.tableView.setModel(self.model)
for row in range(4):
for column in range(4):
item = QStandardItem(f"row {row}, column {column}")
self.model.setItem(row, column, item)
# ==========================================================================================
#listView 需要模型
stringListModel = QStringListModel()
self.listViewData = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"]
stringListModel.setStringList(self.listViewData) # 通过模型添加数据
self.ui.listView.setModel(stringListModel)
self.ui.listView.clicked.connect(self.listViewClicked)
# ==========================================================================================
#listWeiget 可以直接添加字符串
self.ui.listWidget.addItems(self.listViewData)
self.ui.listWidget.itemClicked.connect(self.listWidgetClicked)
self.ui.listWidget.sortItems()
# ==========================================================================================
#tableWidget
# tableWidget 可使用 QTableWidgetItem 以及 widget 控件对象填充表格
# 将行列高度与显示内容匹配
# self.ui.tableWidget.resizeColumnsToContents()
# self.ui.tableWidget.resizeRowsToContents()
# 行列
self.ui.tableWidget.setRowCount(30)
self.ui.tableWidget.setColumnCount(4)
# 水平表头
# self.ui.tableWidget.setHorizontalHeaderLabels(["姓名", "年龄", "体重(KG)"])
self.ui.tableWidget.setHorizontalHeaderLabels(["Row", "Column", "Invalid", "查找"])
# 竖立表头
# self.ui.tableWidget.setVerticalHeaderLabels(["一号", "二号", "三号"])
for row in range(30):
# if row == 0: continue
# if row == 29: break
for column in range(4):
item = QTableWidgetItem() # 模型
item.setTextAlignment(Qt.AlignHCenter| Qt.AlignVCenter) # 文本显示位置
item.setText(f"{row + 1},{column + 1}")
item.setFont(QFont("微软雅黑", 12, QFont.Black)) # 设置字体
self.ui.tableWidget.setItem(row, column, item)
# 表格大小自适应
self.ui.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
# 最后一列是否延伸
self.ui.tableWidget.horizontalHeader().setStretchLastSection(False)
# 表格不能编辑(QAbstractItemView枚举值)
self.ui.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
# 选中一行(鼠标点击表格,选中一行)
self.ui.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)
# 添加 widget 控件
# tableWidgetComboBox = QComboBox()
# tableWidgetComboBox.addItems(["男", "女"])
# tableWidgetButton = QPushButton("修改")
# tableWidgetButton.setDown(True)
# tableWidgetButton.setStyleSheet("QPushButton{margin:1px}")
self.tableWidgetItemOld = None # 记录查找到的 tableWidgetItem
self.rowSpinBox = QSpinBox()
self.rowSpinBox.setRange(1, 30)
self.columnSpinBox = QSpinBox()
self.columnSpinBox.setRange(1, 4)
findButton = QPushButton("查找")
findButton.clicked.connect(self.findButtonClicked)
# span 合并 (int1, int2, int3, int4)
# (int1, int2) 表示开始位置
# (int3) 表示合并几行
# (int4) 表示合并几列
self.ui.tableWidget.setSpan(0, 2, 1, 2)
# 添加控件 setCellWidget
self.ui.tableWidget.setCellWidget(0, 0, self.rowSpinBox)
self.ui.tableWidget.setCellWidget(0, 1, self.columnSpinBox)
self.ui.tableWidget.setCellWidget(0, 3, findButton)
# 设置行宽,行高
# self.ui.tableWidget.setColumnWidth()
self.ui.tableWidget.setRowHeight(0, 40)
# 隐藏分割线
# self.ui.tableWidget.setShowGrid(False)
# 隐藏表头
# self.ui.tableWidget.horizontalHeader().setVisible(False)
# self.ui.tableWidget.sortItems(0, Qt.DescendingOrder) 排序方式
# ==========================================================================================
# tableWidget 显示图片
self.ui.tableWidgetShowImage.setColumnCount(3) # 列
self.ui.tableWidgetShowImage.setRowCount(3)
self.ui.tableWidgetShowImage.setIconSize(QSize(80, 80)) # 设置图片大小
self.ui.tableWidgetShowImage.itemClicked.connect(self.tableWidgetShowImageItemClicked) # 表格点击事件
self.ui.tableWidgetShowImage.setHorizontalHeaderLabels(["图片1", "图片2", "图片3"])
self.ui.tableWidgetShowImage.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) # 大小延伸
for i in range(3):
self.ui.tableWidgetShowImage.setColumnWidth(i, 80)
for i in range(3):
self.ui.tableWidgetShowImage.setRowHeight(i, 80)
imagePath = ".\image"
x = 0
y = 0
for i in os.listdir(imagePath):
item = QTableWidgetItem(QIcon(os.path.join(imagePath, i)), i) # 拼接路径
item.setFlags(Qt.ItemIsEnabled) # ...
if self.ui.tableWidgetShowImage.columnCount() == y:
y = 0
x += 1
# if self.ui.tableWidgetShowImage.rowCount() == x:
# x = 0
self.ui.tableWidgetShowImage.setItem(x, y, item)
y += 1
# tableWidgetItem 右键菜单
self.ui.tableWidgetShowImage.setContextMenuPolicy(Qt.CustomContextMenu) # 开启自定义菜单 (继承自 QWidget)
self.ui.tableWidgetShowImage.customContextMenuRequested.connect(self.tableWidgetShowImageCustomContextMenu) # 继承自 QWidget
# 菜单栏信息
def tableWidgetShowImageCustomContextMenu(self, pos):
menu = QMenu()
save = menu.addAction("保存")
bigImage = menu.addAction("查看大图")
# 对应位置显示菜单栏
# mapToGlobal 返回 Point
# exec 返回 action
action = menu.exec_(self.ui.tableWidgetShowImage.mapToGlobal(pos))
if action:
print(action.text())
def tableWidgetShowImageItemClicked(self, item):
print(item.text())
def findButtonClicked(self):
text = f"{self.rowSpinBox.value()},{self.columnSpinBox.value()}"
items = self.ui.tableWidget.findItems(text, Qt.MatchExactly) # 在表格中搜索 text
if self.tableWidgetItemOld:
self.tableWidgetItemOld.setBackground(QColor(Qt.white)) # 背景颜色
# 选中
# item = items
# item.setSelected(True)
if len(items) > 0:
item = items
self.tableWidgetItemOld = item
# print(item.text())
item.setBackground(QColor("#FF9999")) # 背景颜色
# print(item.row())
self.ui.tableWidget.verticalScrollBar().setSliderPosition(item.row()) # 定位数据位置
def listViewClicked(self, modelIndex):
QMessageBox.information(self.ui, "ListWeiget", "选中:" + self.listViewData)
def listWidgetClicked(self, widgetItem):
QMessageBox.information(self.ui, "ListWeiget", "选中:" + widgetItem.text())
# 开始运行
app = QApplication([])
HomeMain = HomeMain()
HomeMain.ui.show()
sys.exit(app.exec_())
还是非常有用的,谢谢分享! 缺ui文件. 非常有用的
页:
[1]