QT开发中文网

QTableView添加按钮并设置按钮位置和大小

要在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>

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=6063

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?