from PyQt5.QtWidgets import QWidget, QVBoxLayout, QTableWidgetItem from PyQt5.QtCore import Qt from PyQt5 import QtWidgets, QtCore from PyQt5.QtWidgets import (QApplication, QTableWidget, QAbstractItemView, QMessageBox) class TableDemo(QWidget): """窗口类""" def __init__(self, DAT): super().__init__() self.dat = DAT # 接收数据传递 self.initUI() #初始化窗口 # 置顶窗口 self.setWindowFlags(QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.WindowStaysOnTopHint) def initUI(self): self.setWindowTitle('预约') #窗口标题 self.resize(80,200) #窗口大小 # 垂直布局 self.vlayout = QVBoxLayout(self) self.vlayout.setAlignment(Qt.AlignTop) # 设置 垂直布局 的对齐方式 self.setTableWidget() # 设置表格 self.tablewidget.setEditTriggers(QAbstractItemView.NoEditTriggers) # 禁止编辑 self.tablewidget.setSelectionBehavior(QAbstractItemView.SelectRows) # 选择整行 self.show() def move_(self, num): self.tablewidget.removeRow(num) # 删除 第num 条数据 # 设置表格 def setTableWidget(self): self.tablewidget = QTableWidget(3,4) # 表格是 3行4列 #写入表格内容 one_='W' newItem = QTableWidgetItem(one_) self.tablewidget.setItem(1, 1, newItem) self.tablewidget.setFixedWidth(355) # 表格大小 self.setTableHeaderField() self.tablewidget.setAlternatingRowColors(True) # 交替行颜色 self.vlayout.addWidget(self.tablewidget) def buttonForRow(self): widget = QtWidgets.QWidget() self.deleteBtn = QtWidgets.QPushButton('删除') self.deleteBtn.setStyleSheet(''' text-align : center; margin:3px; background-color : LightCoral; height : 30px; border-style: outset; font : 13px; ''') self.deleteBtn.clicked.connect(self.DeleteButton) hLayout = QtWidgets.QHBoxLayout() hLayout.addWidget(self.deleteBtn) hLayout.setContentsMargins(5, 2, 5, 2) widget.setLayout(hLayout) return widget def DeleteButton(self): button = self.sender() if button: # 确定位置的时候这里是关键 close_code = QMessageBox.question(self, "删除提醒", "" + "您将删除!!" "\n" "\n" "是否继续?" , QMessageBox.Yes | QMessageBox.No) if close_code == 65536: pass else: try: row = self.tablewidget.indexAt(button.parent().pos()).row() self.tablewidget.removeRow(row)#删除某行 # ap.del_(row) # 数据库同时删除该条数据 # QtWidgets.QMessageBox.information(self, "", "已删除") except: QtWidgets.QMessageBox.critical(self, "删除失败", "已不存在") # 设置行表头字段 def setTableHeaderField(self): self.tablewidget.setColumnCount(5) # 设置列数 self.tablewidget.setCellWidget(1,2, self.buttonForRow()) header_field = ['日期', '时间', 'c', 'a','b'] self.tablewidget.setHorizontalHeaderLabels(header_field) # 设置行表头字段 self.tablewidget.setColumnWidth(0, 55) # 设置第0列宽度 self.tablewidget.setColumnWidth(1, 60) # 设置第1列宽度 self.tablewidget.setColumnWidth(2, 50) # 设置第2列宽度 self.tablewidget.setColumnWidth(3, 65) # 设置第3列宽度 self.tablewidget.showGrid() self.tablewidget.setShowGrid(True) self.tablewidget.setStyleSheet("QHeaderView::section{background:skyblue;}") if __name__ == "__main__": import sys app = QApplication(sys.argv) lines ='' ui = TableDemo(lines) ui.show() sys.exit(app.exec_())
标签:__,传入,self,QTableWidget,QtWidgets,tablewidget,QMessageBox,数据,def From: https://www.cnblogs.com/wtmb/p/17047971.html