QTableView、QListView、QListWidget、QTableWidget

QTableView

'''

显示二维表数据(QTableView控件)

数据源

Model

需要创建QTableView实例和一个数据源(Model),然后将两者关联

MVC:Model   Viewer   Controller

MVC的目的是将后端的数据和前端页面的耦合度降低



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

class TableView(QWidget):

	def __init__(self, arg=None):
		super(TableView, self).__init__(arg)
		self.setWindowTitle("QTableView表格视图控件演示")
		self.resize(500,300);

		self.model = QStandardItemModel(4,3)
		self.model.setHorizontalHeaderLabels(['id','姓名','年龄'])

		self.tableview = QTableView()
		# 关联QTableView控件和Model
		self.tableview.setModel(self.model)

		# 添加数据
		item11 = QStandardItem('10')
		item12 = QStandardItem('雷神')
		item13 = QStandardItem('2000')
		self.model.setItem(0,0,item11)
		self.model.setItem(0,1, item12)
		self.model.setItem(0,2, item13)

		item31 = QStandardItem('30')
		item32 = QStandardItem('死亡女神')
		item33 = QStandardItem('3000')
		self.model.setItem(2,0,item31)
		self.model.setItem(2,1, item32)
		self.model.setItem(2,2, item33)

		layout = QVBoxLayout()
		layout.addWidget(self.tableview)
		self.setLayout(layout)

		


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


image


QListView
'''

显示列表数据(QListView控件)

'''

from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QListView, QMessageBox
from PyQt5.QtCore import QStringListModel
import sys


class ListViewDemo(QWidget):
    def __init__(self, parent=None):
        super(ListViewDemo, self).__init__(parent)
        self.setWindowTitle("QListView 例子")
        self.resize(300, 270)
        layout = QVBoxLayout()

        listview = QListView()
        listModel = QStringListModel()
        self.list = ["列表项1","列表项2", "列表项3"]

        listModel.setStringList(self.list)

        listview.setModel(listModel)
        listview.clicked.connect(self.clicked)
        layout.addWidget(listview)

        self.setLayout(layout)

    def clicked(self,item):
        QMessageBox.information(self,"QListView","您选择了:" + self.list[item.row()])



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

image


QListWidget
'''

扩展的列表控件(QListWidget)

QListView
'''
from PyQt5.QtWidgets import *
import sys

class ListWidgetDemo(QMainWindow):
	def __init__(self, parent=None):
		super(ListWidgetDemo, self).__init__(parent)
		self.setWindowTitle("QListWidget 例子")
		self.resize(300, 270)
		self.listwidget = QListWidget()
		self.listwidget.addItem("item1")
		self.listwidget.addItem("item2")
		self.listwidget.addItem("item3")
		self.listwidget.addItem("item4")
		self.listwidget.addItem("item5")
		self.listwidget.itemClicked.connect(self.clicked)
		self.setCentralWidget(self.listwidget)
	def clicked(self,Index):
		QMessageBox.information(self,"QListWidget","您选择了:" + self.listwidget.item(self.listwidget.row(Index)).text())



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


image


QTableWidget
'''

扩展的表格控件(QTableWidget)

QTableView

每一个Cell(单元格)是一个QTableWidgetItem

'''

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


class TableWidgetDemo(QWidget):
    def __init__(self):
        super(TableWidgetDemo,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("QTableWidget演示")
        self.resize(430, 230);
        layout = QHBoxLayout()
        tablewidget = QTableWidget()
        tablewidget.setRowCount(4)
        tablewidget.setColumnCount(3)

        layout.addWidget(tablewidget)

        tablewidget.setHorizontalHeaderLabels(['姓名','年龄','籍贯'])
        nameItem = QTableWidgetItem("小明")
        tablewidget.setItem(0,0,nameItem)

        ageItem = QTableWidgetItem("24")
        tablewidget.setItem(0,1,ageItem)

        jgItem = QTableWidgetItem("北京")
        tablewidget.setItem(0,2,jgItem)

        # 禁止编辑
        tablewidget.setEditTriggers(QAbstractItemView.NoEditTriggers)

        # 整行选择
        tablewidget.setSelectionBehavior(QAbstractItemView.SelectRows)
        # 调整列和行
        tablewidget.resizeColumnsToContents()
        tablewidget.resizeRowsToContents()

        tablewidget.horizontalHeader().setVisible(False)
     #   tablewidget.verticalHeader().setVisible(False)

        tablewidget.setVerticalHeaderLabels(["a","b"])

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

        self.setLayout(layout)


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

image

QTableWidget单元格放置控件
'''

在单元格中放置控件

setItem:将文本放到单元格中
setCellWidget:将控件放到单元格中
setStyleSheet:设置控件的样式(QSS)

'''

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


class PlaceControlInCell(QWidget):
    def __init__(self):
        super(PlaceControlInCell,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("在单元格中放置控件")
        self.resize(430, 300);
        layout = QHBoxLayout()
        tableWidget = QTableWidget()
        tableWidget.setRowCount(4)
        tableWidget.setColumnCount(3)

        layout.addWidget(tableWidget)

        tableWidget.setHorizontalHeaderLabels(['姓名','性别','体重(kg)'])
        textItem = QTableWidgetItem('小明')
        tableWidget.setItem(0,0,textItem)

        combox = QComboBox()
        combox.addItem('男')
        combox.addItem('女')
        # QSS Qt StyleSheet
        combox.setStyleSheet('QComboBox{margin:3px};')
        tableWidget.setCellWidget(0,1,combox)

        modifyButton = QPushButton('修改')
        modifyButton.setDown(True)
        modifyButton.setStyleSheet('QPushButton{margin:3px};')
        tableWidget.setCellWidget(0,2,modifyButton)

        self.setLayout(layout)



if __name__ == '__main__':
    app = QApplication(sys.argv)
    example = PlaceControlInCell()
    example.show()
    sys.exit(app.exec_())
image
QTableWidget单元格搜索和定位
'''

在表格中快速定位到特定的行

1. 数据的定位:findItems  返回一个列表
2. 如果找到了满足条件的单元格,会定位到单元格所在的行:setSliderPosition(row)

'''

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


class DataLocation(QWidget):
    def __init__(self):
        super(DataLocation,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("QTableWidget 例子")
        self.resize(600, 800);

        layout = QHBoxLayout()
        tableWidget = QTableWidget()
        tableWidget.setRowCount(40)
        tableWidget.setColumnCount(4)

        layout.addWidget(tableWidget)

        for i in range(40):
            for j in range(4):
                itemContent = '(%d,%d)' %(i,j)
                tableWidget.setItem(i,j,QTableWidgetItem(itemContent))
        self.setLayout(layout)

        # 搜索满足条件的Cell
        text = '(1'
        items = tableWidget.findItems(text,QtCore.Qt.MatchStartsWith)
        if len(items) > 0:
            item = items[0]
            item.setBackground(QBrush(QColor(0,255,0)))
            item.setForeground(QBrush(QColor(255,0,0)))

            row = item.row()

            # 定位到指定的行
            tableWidget.verticalScrollBar().setSliderPosition(row)

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



image
QTableWidget单元格字体和颜色
'''
设置单元格字体和颜色



'''

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


class CellFontAndColor(QWidget):
    def __init__(self):
        super(CellFontAndColor,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("设置单元格字体和颜色")
        self.resize(430, 230);
        layout = QHBoxLayout()
        tableWidget = QTableWidget()
        tableWidget.setRowCount(4)
        tableWidget.setColumnCount(3)
        layout.addWidget(tableWidget)

        tableWidget.setHorizontalHeaderLabels(['姓名', '性别', '体重(kg)'])

        newItem = QTableWidgetItem('雷神')
        newItem.setFont(QFont('Times',14,QFont.Black))
        newItem.setForeground(QBrush(QColor(255,0,0)))
        tableWidget.setItem(0,0,newItem)

        newItem = QTableWidgetItem('女')
        newItem.setForeground(QBrush(QColor(255,255,0)))
        newItem.setBackground(QBrush(QColor(0,0,255)))
        tableWidget.setItem(0,1,newItem)

        newItem = QTableWidgetItem('160')
        newItem.setFont(QFont('Times',20,QFont.Black))
        newItem.setForeground(QBrush(QColor(0,0,255)))
        tableWidget.setItem(0,2,newItem)

        self.setLayout(layout)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    example = CellFontAndColor()
    example.show()
    sys.exit(app.exec_())
image
QTableWidget列排序
'''

按列排序

1. 按哪一列排序
2. 排序类型:升序或降序

sortItems(columnIndex,orderType)

'''

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


class ColumnSort(QWidget):
    def __init__(self):
        super(ColumnSort,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("按列排序")
        self.resize(430, 230);
        layout = QVBoxLayout()
        self.tableWidget = QTableWidget()
        self.tableWidget.setRowCount(4)
        self.tableWidget.setColumnCount(3)
        layout.addWidget(self.tableWidget)

        self.tableWidget.setHorizontalHeaderLabels(['姓名', '性别', '体重(kg)'])

        newItem = QTableWidgetItem('张三')
        self.tableWidget.setItem(0,0,newItem)

        newItem=QTableWidgetItem('男')
        self.tableWidget.setItem(0,1,newItem)

        newItem=QTableWidgetItem('165')
        self.tableWidget.setItem(0,2,newItem)

        newItem = QTableWidgetItem('李四')
        self.tableWidget.setItem(1, 0, newItem)

        newItem = QTableWidgetItem('女')
        self.tableWidget.setItem(1, 1, newItem)

        newItem = QTableWidgetItem('160')
        self.tableWidget.setItem(1, 2, newItem)

        newItem = QTableWidgetItem('王五')
        self.tableWidget.setItem(2, 0, newItem)

        newItem = QTableWidgetItem('男')
        self.tableWidget.setItem(2, 1, newItem)

        newItem = QTableWidgetItem('170')
        self.tableWidget.setItem(2, 2, newItem)

        self.button = QPushButton('排序')
        self.button.clicked.connect(self.order)
        layout.addWidget(self.button)

        self.orderType = Qt.DescendingOrder
        self.setLayout(layout)


    def order(self):
        if self.orderType == Qt.DescendingOrder:
            self.orderType = Qt.AscendingOrder
        else:
            self.orderType = Qt.DescendingOrder
        self.tableWidget.sortItems(2,self.orderType)
if __name__ == '__main__':
    app = QApplication(sys.argv)
    example = ColumnSort()
    example.show()
    sys.exit(app.exec_())
image
QTableWidget单元格文本对齐方式
'''

设置单元格的文本对齐方式

setTextAlignment

Qt.AlignRight   Qt.AlignBottom

'''

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


class CellTextAlignment(QWidget):
    def __init__(self):
        super(CellTextAlignment,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("设置单元格的文本对齐方式")
        self.resize(430, 230);
        layout = QHBoxLayout()
        tableWidget = QTableWidget()
        tableWidget.setRowCount(4)
        tableWidget.setColumnCount(3)
        layout.addWidget(tableWidget)

        tableWidget.setHorizontalHeaderLabels(['姓名', '性别', '体重(kg)'])

        newItem = QTableWidgetItem('雷神')
        newItem.setTextAlignment(Qt.AlignRight | Qt.AlignBottom)
        tableWidget.setItem(0,0,newItem)

        newItem = QTableWidgetItem('男')
        newItem.setTextAlignment(Qt.AlignCenter | Qt.AlignBottom)
        tableWidget.setItem(0,1,newItem)

        newItem = QTableWidgetItem('190')
        newItem.setTextAlignment(Qt.AlignRight)
        tableWidget.setItem(0,2,newItem)

        self.setLayout(layout)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    example = CellTextAlignment()
    example.show()
    sys.exit(app.exec_())
image
QTableWidget合并单元格
'''

合并单元格

setSpan(row,col,要合并的行数,要合并的列数)

'''

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


class Span(QWidget):
    def __init__(self):
        super(Span,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("合并单元格")
        self.resize(430, 230);
        layout = QHBoxLayout()
        tableWidget = QTableWidget()
        tableWidget.setRowCount(4)
        tableWidget.setColumnCount(3)
        layout.addWidget(tableWidget)

        tableWidget.setHorizontalHeaderLabels(['姓名', '性别', '体重(kg)'])

        newItem = QTableWidgetItem('雷神')
        tableWidget.setItem(0,0,newItem)
        tableWidget.setSpan(0, 0, 3, 1)

        newItem = QTableWidgetItem('男')
        tableWidget.setItem(0,1,newItem)
        tableWidget.setSpan(0,1,2,1)

        newItem = QTableWidgetItem('160')
        tableWidget.setItem(0,2,newItem)
        tableWidget.setSpan(0,2,4,1)


        self.setLayout(layout)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    example = Span()
    example.show()
    sys.exit(app.exec_())
image
QTableWidget单元格尺寸
'''

设置单元格尺寸

'''

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

class CellSize(QWidget):
    def __init__(self):
        super(CellSize,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("QTableWidget 例子")
        self.resize(530, 300);
        layout = QHBoxLayout()
        tableWidget = QTableWidget()
        tableWidget.setRowCount(4)
        tableWidget.setColumnCount(3)
        layout.addWidget(tableWidget)

        tableWidget.setHorizontalHeaderLabels(['姓名', '性别', '体重(kg)'])
        tableWidget.setRowHeight(0, 80)
        tableWidget.setColumnWidth(2, 120)
        tableWidget.setRowHeight(2,100)
        newItem = QTableWidgetItem('雷神')
        newItem.setFont(QFont('Times',40,QFont.Black))
        newItem.setForeground(QBrush(QColor(255,0,0)))
        tableWidget.setItem(0,0,newItem)

        newItem = QTableWidgetItem('女')
        newItem.setForeground(QBrush(QColor(255,255,0)))
        newItem.setBackground(QBrush(QColor(0,0,255)))
        tableWidget.setItem(0,1,newItem)

        newItem = QTableWidgetItem('160')
        newItem.setFont(QFont('Times',60,QFont.Black))
        newItem.setForeground(QBrush(QColor(0,0,255)))
        tableWidget.setItem(0,2,newItem)

        self.setLayout(layout)


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

image
QTableWidget单元格图文混排
'''

在单元格中实现图文混排的效果

'''

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



class CellImageText(QWidget):

    def __init__(self):
        super(CellImageText,self).__init__()
        self.initUI()
    def initUI(self):
        self.setWindowTitle("在单元格中实现图文混排的效果")
        self.resize(500, 300);
        layout = QHBoxLayout()
        self.tableWidget = QTableWidget()
        self.tableWidget.setRowCount(5)
        self.tableWidget.setColumnCount(4)
        layout.addWidget(self.tableWidget)

        self.tableWidget.setHorizontalHeaderLabels(['姓名', '性别', '体重', '显示图片'])

        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(layout)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    example = CellImageText()
    example.show()
    sys.exit(app.exec_())
image
QTableWidget改变单元格图片尺寸
'''

改变单元格中图片的尺寸

setIconSize(QSize(width,height))

'''

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


class CellImageSize(QWidget):
    def __init__(self):
        super(CellImageSize,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("改变单元格中图片的尺寸")
        self.resize(1000, 900);
        layout = QHBoxLayout()

        tablewidget = QTableWidget()
        tablewidget.setIconSize(QSize(300,200))
        tablewidget.setColumnCount(3)
        tablewidget.setRowCount(5)

        tablewidget.setHorizontalHeaderLabels(['图片1', '图片2', '图片3'])

        # 让列的宽度和图片的宽度相同
        for i in range(3):
            tablewidget.setColumnWidth(i,300)

        # 让行的高度和图片的高度相同
        for i in range(15):
            tablewidget.setRowHeight(i,200)

        for k in range(15):
            i = k / 3   # 行
            j = k % 3   # 列
            item = QTableWidgetItem()

            item.setIcon(QIcon('./images/bao%d.png' % k))
            tablewidget.setItem(i,j,item)


        layout.addWidget(tablewidget)

        self.setLayout(layout)


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

image
QTableWidget表格中显示上下文菜单
'''

在表格中显示上下文菜单

1.  如何弹出菜单
2.  如果在满足条件的情况下弹出菜单

QMenu.exec_
'''

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


class TableWidgetContextMenu(QWidget):

    def __init__(self):
        super(TableWidgetContextMenu,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("在表格中显示上下文菜单")
        self.resize(500, 300);
        layout = QHBoxLayout()
        self.tableWidget = QTableWidget()
        self.tableWidget.setRowCount(5)
        self.tableWidget.setColumnCount(3)
        layout.addWidget(self.tableWidget)

        self.tableWidget.setHorizontalHeaderLabels(['姓名', '性别', '体重'])


        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)

        # 表格中第二行记录
        newItem = QTableWidgetItem("李")
        self.tableWidget.setItem(2, 0, newItem)

        newItem = QTableWidgetItem("女")
        self.tableWidget.setItem(2, 1, newItem)

        newItem = QTableWidgetItem("170")
        self.tableWidget.setItem(2, 2, newItem)

        self.tableWidget.setContextMenuPolicy(Qt.CustomContextMenu)

        self.tableWidget.customContextMenuRequested.connect(self.generateMenu)

        self.setLayout(layout)

    def generateMenu(self,pos):
        print(pos)

        for i in self.tableWidget.selectionModel().selection().indexes():
            rowNum = i.row()
        # 如果选择的行索引小于2,弹出上下文菜单
        if rowNum < 2:
            menu = QMenu()
            item1 = menu.addAction("菜单项1")
            item2 = menu.addAction("菜单项2")
            item3 = menu.addAction("菜单项3")
            screenPos = self.tableWidget.mapToGlobal(pos)
            print(screenPos)
            # 被阻塞
            action = menu.exec(screenPos)
            if action == item1:
                print('选择了第1个菜单项',self.tableWidget.item(rowNum,0).text(),
                                        self.tableWidget.item(rowNum,1).text(),
                                        self.tableWidget.item(rowNum, 2).text())
            elif action == item2:
                print('选择了第2个菜单项',self.tableWidget.item(rowNum,0).text(),
                                        self.tableWidget.item(rowNum,1).text(),
                                        self.tableWidget.item(rowNum, 2).text())
            elif action == item3:
                print('选择了第3个菜单项',self.tableWidget.item(rowNum,0).text(),
                                        self.tableWidget.item(rowNum,1).text(),
                                        self.tableWidget.item(rowNum, 2).text())
            else:
                return




if __name__ == '__main__':
    app = QApplication(sys.argv)
    example = TableWidgetContextMenu()
    example.show()
    sys.exit(app.exec_())
image
posted @ 2021-05-26 11:10  wuyuan2011woaini  阅读(727)  评论(0编辑  收藏  举报