Introduction to PyQt5 (13) Tables & Cells (below)

table of Contents

1. Set the text alignment of the cell

2. Merge cells

Three. Set the size of the cell

Four. Realize the effect of mixed graphics and text in the cell

Five. Change the size of the picture in the cell

6. Display the context menu in the table


1. Set the text alignment of the cell

setTextAlignment
Qt. AlignRight Right align Qt.AlignBottom bottom display

 

Code:

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


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)
        #设置表格字段
        tableWidget.setHorizontalHeaderLabels(['姓名','性别','体重(kg)'])

        newItem=QTableWidgetItem('小明')
        #下面说的对齐与显示都是指在单元格中
        # 右对齐 底端显示,即右下,Qt.AlignRight默认是右上
        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)

        layout.addWidget(tableWidget)
        self.setLayout(layout)


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

operation result:

 

2. Merge cells

setSpan(row, col, the number of rows to be merged, the number of columns to be merged)

 

Code:

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


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

    def initUI(self):
        self.setWindowTitle('合并单元格')
        self.resize(430, 230)

        layout = QHBoxLayout()
        #表格对象
        tableWidget=QTableWidget()
        #四行三列
        tableWidget.setRowCount(4)
        tableWidget.setColumnCount(3)
        #设置表格字段
        tableWidget.setHorizontalHeaderLabels(['姓名','性别','体重(kg)'])

        newItem=QTableWidgetItem('小明')
        tableWidget.setItem(0,0,newItem)
        #setSpan(row, col, 要合并的行数,要合并的列数)
        tableWidget.setSpan(0,0,3,1)

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

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

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

        layout.addWidget(tableWidget)
        self.setLayout(layout)


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

operation result:

 

Three. Set the size of the cell

The cell size can be manually dragged to change the size. When the font is set to a large size, the cell size displayed after running may not be enough to display the text, and only three dots will be displayed and omitted. At this time, the cell size must be set.

Code:

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


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

    def initUI(self):
        self.setWindowTitle('合并单元格')
        self.resize(600, 400)

        layout = QHBoxLayout()
        #表格对象
        tableWidget=QTableWidget()
        #四行三列
        tableWidget.setRowCount(4)
        tableWidget.setColumnCount(3)
        #设置表格字段
        tableWidget.setHorizontalHeaderLabels(['姓名','性别','体重(kg)'])

        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)))  # rgb
        tableWidget.setItem(0, 1, newItem)

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

        tableWidget.setRowHeight(0, 120)  # 设置第一行高度,三个数据项都在第一行上,第一行的单元格高度都变为120
        tableWidget.setColumnWidth(0, 150)  # 设置第一列宽度
        tableWidget.setRowHeight(2,200)#设置第三行高度,注意这是第三行,而不是第三个单元格的高度!!!!!
        tableWidget.setColumnWidth(2,180)# 设置第二列宽度

        layout.addWidget(tableWidget)
        self.setLayout(layout)


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

operation result:

After changing the size before     changing the size

 

Four. Realize the effect of mixed graphics and text in the cell

Code:

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


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

    def initUI(self):
        self.setWindowTitle('合并单元格')
        self.resize(600, 250)

        layout = QHBoxLayout()
        #表格对象
        tableWidget=QTableWidget()
        #四行四列
        tableWidget.setRowCount(4)
        tableWidget.setColumnCount(4)
        #设置表格字段
        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(QIcon('../picture/LinuxLogo.jpg'),'背包')
        tableWidget.setItem(0,3,newItem)

        layout.addWidget(tableWidget)
        self.setLayout(layout)


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

operation result:

 

Five. Change the size of the picture in the cell

setIconSize(QSize(width, height))

bug:

For any pictures downloaded online, only one png picture can be displayed. After the batch is changed to .jpg, most of them can be displayed, but there is still one that cannot be displayed.

Click here to modify the file suffix in batches under Windows

 

Code:

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui 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.setRowCount(5)
        tableWidget.setColumnCount(3)
        #设置表格字段
        tableWidget.setHorizontalHeaderLabels(['image1','image2','image3'])
        #让列的宽度和图片的宽度相同
        for i in range(3):
            tableWidget.setColumnWidth(i,300)
        #让行的高度和图片的高度相同
        for i in range(5):
            tableWidget.setRowHeight(i,200)

        for k in range(15):
            i=k/3 #行
            j=k%3 #列
            item=QTableWidgetItem()
            item.setIcon(QIcon('../picture/bag/bag%d.jpg' % (k+1)))
            tableWidget.setItem(i,j,item)

        layout.addWidget(tableWidget)
        self.setLayout(layout)


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

operation result:

 

6. Display the context menu in the table

1. How to pop up menu
2. If pop up menu
QMenu. exec_() if the conditions are met

 

Code:

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


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

    def initUI(self):
        self.setWindowTitle('在表格中显示上下文菜单')
        self.resize(500, 200)

        layout = QHBoxLayout()
        #表格对象
        self.tableWidget=QTableWidget()
        #五行三列
        self.tableWidget.setRowCount(4)
        self.tableWidget.setColumnCount(3)
        #设置表格字段
        self.tableWidget.setHorizontalHeaderLabels(['name','sex','weigh'])

        #添加数据
        newItem = QTableWidgetItem('小明')
        self.tableWidget.setItem(0, 0, newItem)
        newItem = QTableWidgetItem('男')
        self.tableWidget.setItem(0, 1, newItem)
        newItem = QTableWidgetItem('190')
        self.tableWidget.setItem(0, 2, newItem)

        newItem = QTableWidgetItem('小亮')
        self.tableWidget.setItem(1, 0, newItem)
        newItem = QTableWidgetItem('男')
        self.tableWidget.setItem(1, 1, newItem)
        newItem = QTableWidgetItem('100')
        self.tableWidget.setItem(1, 2, newItem)

        newItem = QTableWidgetItem('小红')
        self.tableWidget.setItem(2, 0, newItem)
        newItem = QTableWidgetItem('女')
        self.tableWidget.setItem(2, 1, newItem)
        newItem = QTableWidgetItem('90')
        self.tableWidget.setItem(2, 2, newItem)

        #设置允许弹出上下文你菜单
        self.tableWidget.setContextMenuPolicy(Qt.CustomContextMenu)
        #信号与槽
        self.tableWidget.customContextMenuRequested.connect(self.generateMenu)

        layout.addWidget(self.tableWidget)
        self.setLayout(layout)

    def generateMenu(self,pos):
        print('pos=',pos)
        for i in self.tableWidget.selectionModel().selection().indexes():
            rowNum=i.row()
            print('选择了第%d行' % (rowNum+1))
        #如果选择的行索引小于2,弹出上下文菜单
        if rowNum<2:
            menu=QMenu()
            item1=menu.addAction('菜单项1')#一个动作
            #print(type(item1))
            item2 = menu.addAction('菜单项2')
            item3 = menu.addAction('菜单项3')
            #pos是相对于整个屏幕的坐标,所以要转换为窗口坐标
            screenPos=self.tableWidget.mapToGlobal(pos)
            print('screenPos=',screenPos)
            #被阻塞
            action=menu.exec_(screenPos)
            if action==item1:
                print('选择了第一个菜单项',self.tableWidget.item(rowNum,0).text(),
                      self.tableWidget.item(rowNum, 1).text(),
                      self.tableWidget.item(rowNum, 2).text())
            elif action==item2:
                print('选择了第二个菜单项',self.tableWidget.item(rowNum,0).text(),
                      self.tableWidget.item(rowNum, 1).text(),
                      self.tableWidget.item(rowNum, 2).text())
            elif action==item3:
                print('选择了第三个菜单项',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)
    main=CellImageSize()
    main.show()
    sys.exit(app.exec_())

operation result:

Right-click the cell and the context menu will appear      

 

 

 

Guess you like

Origin blog.csdn.net/weixin_44593822/article/details/113552913