要在QTableView中添加按钮并设置按钮的位置和大小,可以使用自定义委托(QItemDelegate)来实现。
以下是一个简单的示例代码,演示如何在QTableView中添加一个按钮,并设置其位置和大小:
”`python from PyQt5.QtWidgets import QApplication, QTableView, QWidget, QPushButton, QHBoxLayout, QVBoxLayout from PyQt5.QtCore import Qt, QModelIndex from PyQt5.QtGui import QPainter
class ButtonDelegate(QItemDelegate):
def __init__(self):
super().__init__()
def paint(self, painter: QPainter, option: 'QStyleOptionViewItem', index: QModelIndex) -> None:
if index.column() == 0:
button = QPushButton("Button")
button.setGeometry(option.rect)
button.clicked.connect(lambda: print(f"Button clicked at row {index.row()}"))
widget = QWidget()
layout = QHBoxLayout(widget)
layout.addWidget(button)
layout.setAlignment(Qt.AlignCenter)
layout.setContentsMargins(0, 0, 0, 0)
widget.setGeometry(option.rect)
painter.save()
painter.translate(option.rect.topLeft())
widget.render(painter)
painter.restore()
else:
super().paint(painter, option, index)
if name == “main”:
app = QApplication([])
tableView = QTableView()
# 设置代理为自定义的ButtonDelegate
delegate = ButtonDelegate()
tableView.setItemDelegateForColumn(0, delegate)
# 添加数据模型及数据
model = QStandardItemModel(4, 3)
for row in range(4):
for col in range(3):
item = QStandardItem(f"Data {row}-{col}")
<br/><br/><br/><font size=1 color=#CCCCCC>内容由零声教学AI助手提供,问题来源于学员提问</font>