> 情感 >

气轻PyQt5 30 表(QTableWidget)插入一行

时间:2023-05-30 08:19:49       来源:哔哩哔哩

from PyQt5.QtWidgets import *

from PyQt5.QtGui import QFont

import sys


(资料图)

class PyQt530(QWidget):

def __init__(self):

super().__init__()

self.initUI()

def initUI(self):

self.setWindowTitle('气轻PyQt5')                # 设置窗口标题

self.resize(490, 300)                           # 设置窗口大小

self.setStyleSheet('background-color:#FFE4B5')

self.delRow = QPushButton('删除一行', self)

self.delRow.setGeometry(10, 60, 80, 30)

self.delRow.setStyleSheet('background-color:#66CDAA;color : #8B8682; \

font: bold large /"SimSun/";font-size:16px')

self.delRow.clicked.connect(lambda :self.buttonClicked(self.delRow))

self.insRow = QPushButton('插入一行', self)

self.insRow.setGeometry(10, 90, 80, 30)

self.insRow.setStyleSheet('background-color:#66CDAA;color : #8B8682; \

font: bold large /"SimSun/";font-size:16px')

self.insRow.clicked.connect(lambda :self.buttonClicked(self.insRow))

titles = ['编号', ' 第一列 ', ' 第二列 ', ' 第三列 ', ' 第四列 ']

self.table = QTableWidget(8,5,self)             # 创n行m列建空表格

self.table.setGeometry(100, 60,380,200)         # 设置位置和大小

self.table.setStyleSheet('background-color:#E6E6FA;color : #696969; \

font: bold italic large /"Times New Roman/";font-size:16px')

self.table.setHorizontalHeaderLabels(titles)    # 水平标题

vtitle = list(map(str, list(range(8))))

self.table.setVerticalHeaderLabels(vtitle)      # 垂直标题

# 自动调整列宽

self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.ResizeToContents)

self.table.setAlternatingRowColors(True)        # 行自动变色

self.table.setFont(QFont("宋体",20))

item=QTableWidgetItem('气轻')

self.table.setItem(0,0, item)

item=QTableWidgetItem('气轻python')

self.table.setItem(2,0, item)

item=QTableWidgetItem('气轻PyQt6')

self.table.setItem(4,0, item)

self.show()

def buttonClicked(self,b):

rowPosition = self.table.currentRow()

if rowPosition == -1:                           # 无效行?

msg = '请选择要%s的位置' % b.text()[0:2]

reply = QMessageBox()

reply.setText(msg)

reply.setStandardButtons(QMessageBox.StandardButton.Yes)

x = reply.exec()

return

reply = QMessageBox()

action = b.text()[0:2]

mdict = {'删除' : '要删除第%d行吗?' %rowPosition,

'插入' : '要在第%d行后插入一行吗?' %rowPosition}

reply.setText(mdict[action])

reply.setStandardButtons(QMessageBox.StandardButton.Yes |

QMessageBox.StandardButton.No)

x = reply.exec()

if x == QMessageBox.StandardButton.No:

return

fdict = {'删除' : self.table.removeRow,

'插入' : self.table.insertRow}

fdict[action](rowPosition)

if __name__ == '__main__':

app = QApplication(sys.argv)

window = PyQt530()

sys.exit(app.exec_())

关键词:
精彩推送